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/xsite/statetransfer/failures/SiteProviderTopologyChangeTest.java
package org.infinispan.xsite.statetransfer.failures; import static org.infinispan.distribution.DistributionTestHelper.addressOf; import static org.infinispan.test.TestingUtil.WrapFactory; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.wrapComponent; import static org.infinispan.test.TestingUtil.wrapGlobalComponent; import static org.infinispan.util.BlockingLocalTopologyManager.replaceTopologyManagerDefaultCache; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.Cache; import org.infinispan.manager.CacheContainer; import org.infinispan.remoting.transport.AbstractDelegatingTransport; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.Transport; import org.infinispan.remoting.transport.XSiteResponse; import org.infinispan.remoting.transport.impl.XSiteResponseImpl; import org.infinispan.test.fwk.CheckPoint; import org.infinispan.util.BlockingLocalTopologyManager; import org.infinispan.xsite.XSiteBackup; import org.infinispan.xsite.XSiteReplicateCommand; import org.infinispan.xsite.statetransfer.XSiteProviderDelegator; import org.infinispan.xsite.statetransfer.XSiteStateProvider; import org.infinispan.xsite.statetransfer.XSiteStatePushCommand; import org.testng.annotations.Test; /** * Cross-Site replication state transfer tests. It tests topology changes in producer site. * * @author Pedro Ruivo * @since 7.0 */ //unstable: it looks like not all cases are handled properly. Needs to be revisited! ISPN-6228 @Test(groups = {"xsite", "unstable"}, testName = "xsite.statetransfer.failures.SiteProviderTopologyChangeTest") public class SiteProviderTopologyChangeTest extends AbstractTopologyChangeTest { public SiteProviderTopologyChangeTest() { super(); } public void testJoinAfterXSiteST() throws Exception { doTopologyChangeAfterXSiteStateTransfer(TopologyEvent.JOIN); } public void testLeaveAfterXSiteST() throws Exception { doTopologyChangeAfterXSiteStateTransfer(TopologyEvent.LEAVE); } public void testCoordinatorLeaveAfterXSiteST() throws Exception { doTopologyChangeAfterXSiteStateTransfer(TopologyEvent.COORDINATOR_LEAVE); } public void testSiteMasterLeaveAfterXSiteST() throws Exception { doTopologyChangeAfterXSiteStateTransfer(TopologyEvent.SITE_MASTER_LEAVE); } public void testJoinDuringXSiteST() throws Exception { doTopologyChangeDuringXSiteStateTransfer(TopologyEvent.JOIN); } public void testLeaveDuringXSiteST() throws Exception { doTopologyChangeDuringXSiteStateTransfer(TopologyEvent.LEAVE); } public void testCoordinatorLeaveDuringXSiteST() throws Exception { doTopologyChangeDuringXSiteStateTransfer(TopologyEvent.COORDINATOR_LEAVE); } public void testSiteMasterLeaveDuringXSiteST() throws Exception { doTopologyChangeDuringXSiteStateTransfer(TopologyEvent.SITE_MASTER_LEAVE); } public void testXSiteSTDuringJoin() throws Exception { doXSiteStateTransferDuringTopologyChange(TopologyEvent.JOIN); } public void testXSiteSTDuringLeave() throws Exception { doXSiteStateTransferDuringTopologyChange(TopologyEvent.LEAVE); } @Test(groups = {"xsite", "unstable"}, description = "See ISPN-6749") public void testXSiteSTDuringSiteMasterLeave() throws Exception { doXSiteStateTransferDuringTopologyChange(TopologyEvent.SITE_MASTER_LEAVE); } /** * the test node starts and finishes the x-site state transfer (some other node didn't sent anything). the topology * change is triggered. */ private void doTopologyChangeAfterXSiteStateTransfer(TopologyEvent event) throws Exception { log.debugf("Start topology change after x-site state transfer with %s", event); initBeforeTest(); log.debug("Setting blocking conditions"); final TestCaches<Object, Object> testCaches = createTestCache(event, LON); final AtomicReference<StateTransferRequest> pendingRequest = new AtomicReference<>(null); log.debugf("Controlled cache=%s, Coordinator cache=%s, Cache to remove=%s", addressOf(testCaches.controllerCache), addressOf(testCaches.coordinator), testCaches.removeIndex < 0 ? "NONE" : addressOf(cache(LON, testCaches.removeIndex))); if (testCaches.removeIndex >= 0) { log.debugf("Discard x-site state transfer start command in cache %s to remove", addressOf(cache(LON, testCaches.removeIndex))); wrapComponent(cache(LON, testCaches.removeIndex), XSiteStateProvider.class, (WrapFactory<XSiteStateProvider, XSiteStateProvider, Cache<?, ?>>) (wrapOn, current) -> new XSiteProviderDelegator(current) { @Override public void startStateTransfer(String siteName, Address requestor, int minTopologyId) { log.debugf("Discard state transfer request to %s from %s", siteName, requestor); //no-op, i.e. discard it! } }, true); } else { log.debugf("Block x-site state transfer start command in cache %s", addressOf(cache(LON, 1))); wrapComponent(cache(LON, 1), XSiteStateProvider.class, (WrapFactory<XSiteStateProvider, XSiteStateProvider, Cache<?, ?>>) (wrapOn, current) -> new XSiteProviderDelegator(current) { @Override public void startStateTransfer(String siteName, Address requestor, int minTopologyId) { log.debugf("Blocking state transfer request to %s from %s", siteName, requestor); pendingRequest.set(new StateTransferRequest(siteName, requestor, minTopologyId, xSiteStateProvider)); } }, true); } log.debug("Start x-site state transfer"); startStateTransfer(testCaches.coordinator, NYC); assertOnline(LON, NYC); //the controller cache will finish the state transfer before the cache topology command log.debug("Await until X-Site state transfer is finished!"); eventually(() -> extractComponent(testCaches.controllerCache, XSiteStateProvider.class).getCurrentStateSending().isEmpty(), TimeUnit.SECONDS.toMillis(30)); Future<Void> topologyEventFuture = triggerTopologyChange(LON, testCaches.removeIndex); topologyEventFuture.get(); awaitLocalStateTransfer(LON); if (pendingRequest.get() != null) { log.debug("Let the blocked x-site state transfer request to proceed"); pendingRequest.get().execute(); } awaitXSiteStateSent(LON); log.debug("Check data in both sites."); assertData(); } /** * the test node starts the x-site state transfer and sends a chunk of data. the next chunk is blocked and we trigger * the cache topology change. */ private void doTopologyChangeDuringXSiteStateTransfer(TopologyEvent event) throws Exception { log.debugf("Start topology change during x-site state transfer with %s", event); initBeforeTest(); final TestCaches<Object, Object> testCaches = createTestCache(event, LON); log.debugf("Controlled cache=%s, Coordinator cache=%s, Cache to remove=%s", addressOf(testCaches.controllerCache), addressOf(testCaches.coordinator), testCaches.removeIndex < 0 ? "NONE" : addressOf(cache(LON, testCaches.removeIndex))); //the test node will start the x-site state transfer and it will block. next, it the topology will change. //strategy: let the first push command to proceed a block the next one. final CheckPoint checkPoint = new CheckPoint(); final AtomicBoolean firstChunk = new AtomicBoolean(false); wrapGlobalComponent(testCaches.controllerCache.getCacheManager(), Transport.class, new WrapFactory<Transport, Transport, CacheContainer>() { @Override public Transport wrap(CacheContainer wrapOn, Transport current) { return new AbstractDelegatingTransport(current) { @Override public void start() { //no-op; avoid re-start the transport again... } @Override public XSiteResponse backupRemotely(XSiteBackup backup, XSiteReplicateCommand rpcCommand) { if (rpcCommand instanceof XSiteStatePushCommand) { if (firstChunk.compareAndSet(false, true)) { checkPoint.trigger("before-second-chunk"); try { checkPoint.awaitStrict("second-chunk", 30, TimeUnit.SECONDS); } catch (InterruptedException | TimeoutException e) { XSiteResponseImpl rsp = new XSiteResponseImpl(TIME_SERVICE, backup); rsp.completeExceptionally(e); return rsp; } } } return super.backupRemotely(backup, rpcCommand); } }; } }, true); log.debug("Start x-site state transfer"); startStateTransfer(testCaches.coordinator, NYC); assertOnline(LON, NYC); checkPoint.awaitStrict("before-second-chunk", 30, TimeUnit.SECONDS); final Future<Void> topologyEventFuture = triggerTopologyChange(LON, testCaches.removeIndex); topologyEventFuture.get(); checkPoint.triggerForever("second-chunk"); awaitLocalStateTransfer(LON); awaitXSiteStateSent(LON); assertData(); } /** * x-site state transfer is triggered during a cache topology change. */ private void doXSiteStateTransferDuringTopologyChange(TopologyEvent event) throws Exception { log.debugf("Start topology change during x-site state transfer with %s", event); initBeforeTest(); final TestCaches<Object, Object> testCaches = createTestCache(event, LON); log.debugf("Controlled cache=%s, Coordinator cache=%s, Cache to remove=%s", addressOf(testCaches.controllerCache), addressOf(testCaches.coordinator), testCaches.removeIndex < 0 ? "NONE" : addressOf(cache(LON, testCaches.removeIndex))); BlockingLocalTopologyManager topologyManager = replaceTopologyManagerDefaultCache(testCaches.controllerCache.getCacheManager()); final Future<Void> topologyEventFuture = triggerTopologyChange(LON, testCaches.removeIndex); // We could get either the NO_REBALANCE update or the READ_OLD rebalance start first BlockingLocalTopologyManager.BlockedTopology blockedTopology = topologyManager.expectTopologyUpdate(); log.debug("Start x-site state transfer"); startStateTransfer(testCaches.coordinator, NYC); assertOnline(LON, NYC); blockedTopology.unblock(); topologyEventFuture.get(); awaitLocalStateTransfer(LON); awaitXSiteStateSent(LON); assertData(); } private static class StateTransferRequest { private final String siteName; private final Address requestor; private final int minTopologyId; private final XSiteStateProvider provider; private StateTransferRequest(String siteName, Address requestor, int minTopologyId, XSiteStateProvider provider) { this.siteName = siteName; this.requestor = requestor; this.minTopologyId = minTopologyId; this.provider = provider; } public void execute() { provider.startStateTransfer(siteName, requestor, minTopologyId); } } }
12,435
44.889299
148
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/failures/RetryMechanismTest.java
package org.infinispan.xsite.statetransfer.failures; import static org.infinispan.test.TestingUtil.wrapComponent; import static org.infinispan.test.TestingUtil.wrapInboundInvocationHandler; import static org.infinispan.xsite.statetransfer.XSiteStateTransferManager.STATUS_ERROR; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.Cache; import org.infinispan.commands.remote.CacheRpcCommand; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.MagicKey; import org.infinispan.remoting.inboundhandler.AbstractDelegatingHandler; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler; import org.infinispan.remoting.inboundhandler.Reply; import org.infinispan.remoting.responses.ExceptionResponse; import org.infinispan.xsite.BackupReceiver; import org.infinispan.xsite.BackupReceiverDelegator; import org.infinispan.xsite.statetransfer.XSiteState; import org.infinispan.xsite.statetransfer.XSiteStateConsumer; import org.infinispan.xsite.statetransfer.XSiteStatePushCommand; import org.testng.annotations.Test; /** * Tests the multiple retry mechanism implemented in Cross-Site replication state transfer. * * @author Pedro Ruivo * @since 7.1 */ @Test(groups = "xsite", testName = "xsite.statetransfer.failures.RetryMechanismTest") public class RetryMechanismTest extends AbstractTopologyChangeTest { private static final String VALUE = "value"; /** * Simple scenario where the primary owner throws an exception. The NYC site master retries and at the 3rd retry, it * will apply the data (test retry in NYC). */ public void testExceptionWithSuccessfulRetry() { takeSiteOffline(); final Object key = new MagicKey(cache(NYC, 1)); final FailureHandler handler = FailureHandler.replaceOn(cache(NYC, 1)); final CounterBackupReceiver counterRepository = replaceBackupReceiverOn(cache(NYC, 0)); cache(LON, 0).put(key, VALUE); handler.fail(); //it fails 3 times and then succeeds. startStateTransfer(); assertOnline(LON, NYC); awaitXSiteStateSent(LON); assertEventuallyNoStateTransferInReceivingSite(null); assertEquals(0, handler.remainingFails()); assertEquals(1, counterRepository.counter.get()); assertInSite(NYC, cache -> assertEquals(VALUE, cache.get(key))); } /** * Simple scenario where the primary owner always throws an exception. The state transfer will not be successful * (test retry in NYC and LON). */ public void testExceptionWithFailedRetry() { takeSiteOffline(); final Object key = new MagicKey(cache(NYC, 1)); final FailureHandler handler = FailureHandler.replaceOn(cache(NYC, 1)); final CounterBackupReceiver counterRepository = replaceBackupReceiverOn(cache(NYC, 0)); cache(LON, 0).put(key, VALUE); handler.failAlways(); startStateTransfer(); assertOnline(LON, NYC); awaitXSiteStateSent(LON); assertEventuallyNoStateTransferInReceivingSite(null); assertXSiteErrorStatus(); assertEquals(3 /*max_retry + 1*/, counterRepository.counter.get()); assertInSite(NYC, cache -> assertNull(cache.get(key))); } /** * Simple scenario where the primary owner leaves the cluster and the site master will apply the data locally (tests * retry in NYC, from remote to local). */ public void testRetryLocally() throws ExecutionException, InterruptedException { takeSiteOffline(); final Object key = new MagicKey(cache(NYC, 1)); final DiscardHandler handler = DiscardHandler.replaceOn(cache(NYC, 1)); final CounterBackupReceiver counterRepository = replaceBackupReceiverOn(cache(NYC, 0)); cache(LON, 0).put(key, VALUE); startStateTransfer(); assertOnline(LON, NYC); eventually(() -> handler.discarded); triggerTopologyChange(NYC, 1).get(); awaitXSiteStateSent(LON); assertEventuallyNoStateTransferInReceivingSite(null); assertEquals(1, counterRepository.counter.get()); assertInSite(NYC, cache -> assertEquals(VALUE, cache.get(key))); } /** * Simple scenario where the primary owner leaves the cluster and the NYC site master will apply the data locally. * The 1st and the 2nd time will fail and only the 3rd will succeed (testing local retry) */ public void testMultipleRetryLocally() throws ExecutionException, InterruptedException { takeSiteOffline(); final Object key = new MagicKey(cache(NYC, 1)); final DiscardHandler handler = DiscardHandler.replaceOn(cache(NYC, 1)); final FailureXSiteConsumer failureXSiteConsumer = FailureXSiteConsumer.replaceOn(cache(NYC, 0)); final CounterBackupReceiver counterRepository = replaceBackupReceiverOn(cache(NYC, 0)); failureXSiteConsumer.fail(); cache(LON, 0).put(key, VALUE); startStateTransfer(); assertOnline(LON, NYC); eventually(() -> handler.discarded); triggerTopologyChange(NYC, 1).get(); awaitXSiteStateSent(LON); assertEventuallyNoStateTransferInReceivingSite(null); assertEquals(0, failureXSiteConsumer.remainingFails()); assertEquals(1, counterRepository.counter.get()); assertInSite(NYC, cache -> assertEquals(VALUE, cache.get(key))); } /** * Simple scenario where the primary owner leaves the cluster and the NYC site master will apply the data locally * (test retry in the LON site). */ public void testFailRetryLocally() throws ExecutionException, InterruptedException { takeSiteOffline(); final Object key = new MagicKey(cache(NYC, 1)); final DiscardHandler handler = DiscardHandler.replaceOn(cache(NYC, 1)); final FailureXSiteConsumer failureXSiteConsumer = FailureXSiteConsumer.replaceOn(cache(NYC, 0)); final CounterBackupReceiver counterRepository = replaceBackupReceiverOn(cache(NYC, 0)); failureXSiteConsumer.failAlways(); cache(LON, 0).put(key, VALUE); startStateTransfer(); assertOnline(LON, NYC); eventually(() -> handler.discarded); triggerTopologyChange(NYC, 1).get(); awaitXSiteStateSent(LON); assertEventuallyNoStateTransferInReceivingSite(null); //tricky part. When the primary owners dies, the site master or the other node can become the primary owner //if the site master is enabled, it will never be able to apply the state (XSiteStateConsumer is throwing exception!) //otherwise, the other node will apply the state if (STATUS_ERROR.equals(getXSitePushStatus())) { assertEquals(3 /*max_retry + 1*/, counterRepository.counter.get()); assertInSite(NYC, cache -> assertNull(cache.get(key))); } else { assertEquals(2 /*the 1st retry succeed*/, counterRepository.counter.get()); assertInSite(NYC, cache -> assertEquals(VALUE, cache.get(key))); } } @Override protected void adaptLONConfiguration(BackupConfigurationBuilder builder) { super.adaptLONConfiguration(builder); builder.stateTransfer().maxRetries(2).waitTime(1000); builder.clustering().hash().numSegments(8); //we only use 1 key; no need for 256 segments } @Override protected ConfigurationBuilder getNycActiveConfig() { ConfigurationBuilder builder = super.getNycActiveConfig(); builder.clustering().hash().numSegments(8); //we only use 1 key; no need for 256 segments return builder; } private static class FailureXSiteConsumer implements XSiteStateConsumer { static final int FAIL_FOR_EVER = -1; private final XSiteStateConsumer delegate; //fail if > 0 private int nFailures = 0; private FailureXSiteConsumer(XSiteStateConsumer delegate) { this.delegate = delegate; } @Override public void startStateTransfer(String sendingSite) { delegate.startStateTransfer(sendingSite); } @Override public void endStateTransfer(String sendingSite) { delegate.endStateTransfer(sendingSite); } @Override public void applyState(XSiteState[] chunk) throws Exception { boolean fail; synchronized (this) { fail = nFailures == FAIL_FOR_EVER; if (nFailures > 0) { fail = true; nFailures--; } } if (fail) { throw new CacheException("Induced Fail"); } delegate.applyState(chunk); } @Override public String getSendingSiteName() { return delegate.getSendingSiteName(); } static FailureXSiteConsumer replaceOn(Cache<?, ?> cache) { return wrapComponent(cache, XSiteStateConsumer.class, (wrapOn, current) -> new FailureXSiteConsumer(current), true); } void fail() { synchronized (this) { this.nFailures = 3; } } void failAlways() { synchronized (this) { this.nFailures = FAIL_FOR_EVER; } } int remainingFails() { synchronized (this) { return nFailures; } } } private static class DiscardHandler extends AbstractDelegatingHandler { private volatile boolean discarded = false; private DiscardHandler(PerCacheInboundInvocationHandler delegate) { super(delegate); } static DiscardHandler replaceOn(Cache<?, ?> cache) { return wrapInboundInvocationHandler(cache, DiscardHandler::new); } @Override protected boolean beforeHandle(CacheRpcCommand command, Reply reply, DeliverOrder order) { if (!discarded) { discarded = command instanceof XSiteStatePushCommand; } return !discarded; } } private static class FailureHandler extends AbstractDelegatingHandler { static final int FAIL_FOR_EVER = -1; //fail if > 0 private int nFailures = 0; private FailureHandler(PerCacheInboundInvocationHandler delegate) { super(delegate); } static FailureHandler replaceOn(Cache<?, ?> cache) { return wrapInboundInvocationHandler(cache, FailureHandler::new); } void fail() { synchronized (this) { this.nFailures = 3; } } void failAlways() { synchronized (this) { this.nFailures = FAIL_FOR_EVER; } } int remainingFails() { synchronized (this) { return nFailures; } } @Override protected synchronized boolean beforeHandle(CacheRpcCommand command, Reply reply, DeliverOrder order) { if (command instanceof XSiteStatePushCommand) { boolean fail; synchronized (this) { fail = nFailures == FAIL_FOR_EVER; if (nFailures > 0) { fail = true; nFailures--; } } if (fail) { reply.reply(new ExceptionResponse(new CacheException("Induced Fail."))); return false; } } return true; } } private static class CounterBackupReceiver extends BackupReceiverDelegator { private final AtomicInteger counter; CounterBackupReceiver(BackupReceiver delegate) { super(delegate); this.counter = new AtomicInteger(); } @Override public CompletionStage<Void> handleStateTransferState(XSiteStatePushCommand cmd) { counter.getAndIncrement(); return super.handleStateTransferState(cmd); } } private static CounterBackupReceiver replaceBackupReceiverOn(Cache<?,?> cache) { return wrapComponent(cache, BackupReceiver.class, CounterBackupReceiver::new); } }
12,234
32.612637
123
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/failures/AbstractTopologyChangeTest.java
package org.infinispan.xsite.statetransfer.failures; import static org.infinispan.distribution.DistributionTestHelper.addressOf; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.xsite.statetransfer.XSiteStateTransferManager.STATUS_ERROR; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.statetransfer.StateConsumer; import org.infinispan.statetransfer.StateProvider; import org.infinispan.xsite.statetransfer.AbstractStateTransferTest; import org.infinispan.xsite.statetransfer.XSiteStateProvider; /** * Helper methods for x-site state transfer during topology changes. * * @author Pedro Ruivo * @since 7.0 */ public abstract class AbstractTopologyChangeTest extends AbstractStateTransferTest { private static final int NR_KEYS = 20; //10 * chunk size AbstractTopologyChangeTest() { this.implicitBackupCache = true; this.cleanup = CleanupPhase.AFTER_METHOD; this.initialClusterSize = 3; } private static ConfigurationBuilder createConfiguration() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.clustering().hash().numOwners(2); return builder; } void awaitLocalStateTransfer(String site) { log.debugf("Await until rebalance in site '%s' is finished!", site); assertEventuallyInSite(site, cache -> !extractComponent(cache, StateConsumer.class).isStateTransferInProgress() && !extractComponent(cache, StateProvider.class).isStateTransferInProgress(), 30, TimeUnit.SECONDS); } void awaitXSiteStateSent(String site) { log.debugf("Await until all nodes in '%s' has sent the state!", site); assertEventuallyInSite(site, cache -> extractComponent(cache, XSiteStateProvider.class).getCurrentStateSending().isEmpty(), 30, TimeUnit.SECONDS); } Future<Void> triggerTopologyChange(final String siteName, final int removeIndex) { if (removeIndex >= 0) { return fork(() -> { log.debugf("Shutting down cache %s", addressOf(cache(siteName, removeIndex))); site(siteName).kill(removeIndex); log.debugf("Wait for cluster to form on caches %s", site(siteName).getCaches(null)); site(siteName).waitForClusterToForm(null, 60, TimeUnit.SECONDS); return null; }); } else { log.debug("Adding new cache"); site(siteName).addCache(globalConfigurationBuilderForSite(siteName), lonConfigurationBuilder()); return fork(() -> { log.debugf("Wait for cluster to form on caches %s", site(siteName).getCaches(null)); site(siteName).waitForClusterToForm(null, 60, TimeUnit.SECONDS); return null; }); } } void initBeforeTest() { takeSiteOffline(); assertOffline(); putData(); assertDataInSite(LON); assertInSite(NYC, cache -> assertTrue(cache.isEmpty())); } void assertData() { assertDataInSite(LON); assertDataInSite(NYC); } void assertDataInSite(String siteName) { assertInSite(siteName, cache -> { for (int i = 0; i < NR_KEYS; ++i) { assertEquals(val(Integer.toString(i)), cache.get(key(Integer.toString(i)))); } }); } void assertXSiteErrorStatus() { assertEquals(STATUS_ERROR, getXSitePushStatus()); } String getXSitePushStatus() { return adminOperations().getPushStateStatus().get(NYC); } <K, V> TestCaches<K, V> createTestCache(TopologyEvent topologyEvent, String siteName) { switch (topologyEvent) { case JOIN: return new TestCaches<>(this.cache(LON, 0), this.cache(siteName, 0), -1); case COORDINATOR_LEAVE: return new TestCaches<>(this.cache(LON, 1), this.cache(siteName, 0), 1); case LEAVE: return new TestCaches<>(this.cache(LON, 0), this.cache(siteName, 0), 1); case SITE_MASTER_LEAVE: return new TestCaches<>(this.cache(LON, 1), this.cache(siteName, 1), 0); default: //make sure we select the caches throw new IllegalStateException(); } } void printTestCaches(TestCaches<?, ?> testCaches) { log.debugf("Controlled cache=%s, Coordinator cache=%s, Cache to remove=%s", addressOf(testCaches.controllerCache), addressOf(testCaches.coordinator), testCaches.removeIndex < 0 ? "NONE" : addressOf(cache(LON, testCaches.removeIndex))); } @Override protected void adaptLONConfiguration(BackupConfigurationBuilder builder) { builder.stateTransfer().chunkSize(2).timeout(2000); } @Override protected ConfigurationBuilder getNycActiveConfig() { return createConfiguration(); } @Override protected ConfigurationBuilder getLonActiveConfig() { return createConfiguration(); } private void putData() { for (int i = 0; i < NR_KEYS; ++i) { cache(LON, 0).put(key(Integer.toString(i)), val(Integer.toString(i))); } } protected enum TopologyEvent { /** * Some node joins the cluster. */ JOIN, /** * Some non-important node (site master neither the coordinator) leaves. */ LEAVE, /** * Site master leaves. */ SITE_MASTER_LEAVE, /** * X-Site state transfer coordinator leaves. */ COORDINATOR_LEAVE } protected static class TestCaches<K, V> { public final Cache<K, V> coordinator; final Cache<K, V> controllerCache; final int removeIndex; TestCaches(Cache<K, V> coordinator, Cache<K, V> controllerCache, int removeIndex) { this.coordinator = coordinator; this.controllerCache = controllerCache; this.removeIndex = removeIndex; } } }
6,227
33.40884
120
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/failures/SiteConsumerTopologyChangeTest.java
package org.infinispan.xsite.statetransfer.failures; import static org.infinispan.test.TestingUtil.wrapComponent; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.distribution.DistributionManager; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.remoting.transport.Address; import org.infinispan.test.fwk.CheckPoint; import org.infinispan.topology.CacheTopology; import org.infinispan.util.BlockingLocalTopologyManager; import org.infinispan.xsite.BackupReceiver; import org.infinispan.xsite.BackupReceiverDelegator; import org.infinispan.xsite.statetransfer.XSiteState; import org.infinispan.xsite.statetransfer.XSiteStatePushCommand; import org.testng.annotations.Test; /** * Cross-Site replication state transfer tests. It tests topology changes in consumer site. * * @author Pedro Ruivo * @since 7.0 */ //unstable: it looks like not all cases are handled properly. Needs to be revisited! ISPN-6228, ISPN-6872 @Test(groups = {"xsite", "unstable"}, testName = "xsite.statetransfer.failures.SiteConsumerTopologyChangeTest") public class SiteConsumerTopologyChangeTest extends AbstractTopologyChangeTest { public SiteConsumerTopologyChangeTest() { super(); } @Test(enabled = false, description = "Will be fixed by ISPN-6228") public void testJoinDuringXSiteST() throws InterruptedException, ExecutionException, TimeoutException { doTopologyChangeDuringXSiteST(TopologyEvent.JOIN); } public void testLeaveDuringXSiteST() throws InterruptedException, ExecutionException, TimeoutException { doTopologyChangeDuringXSiteST(TopologyEvent.LEAVE); } public void testSiteMasterLeaveDuringXSiteST() throws InterruptedException, ExecutionException, TimeoutException { doTopologyChangeDuringXSiteST(TopologyEvent.SITE_MASTER_LEAVE); } public void testXSiteDuringJoin() throws InterruptedException, ExecutionException, TimeoutException { doXSiteStateTransferDuringTopologyChange(TopologyEvent.JOIN); } public void testXSiteSTDuringLeave() throws InterruptedException, ExecutionException, TimeoutException { doXSiteStateTransferDuringTopologyChange(TopologyEvent.LEAVE); } /** * Site consumer receives some chunks and then, the topology changes. */ private void doTopologyChangeDuringXSiteST(TopologyEvent event) throws TimeoutException, InterruptedException, ExecutionException { log.debugf("Start topology change during x-site state transfer with %s", event); initBeforeTest(); final TestCaches<Object, Object> testCaches = createTestCache(event, NYC); printTestCaches(testCaches); final CheckPoint checkPoint = new CheckPoint(); final AtomicBoolean discard = new AtomicBoolean(true); wrapComponent(cache(NYC, 0), BackupReceiver.class, current -> new BlockingBackupReceiver(current, discard, checkPoint)); log.debug("Start x-site state transfer"); startStateTransfer(testCaches.coordinator, NYC); assertOnline(LON, NYC); checkPoint.awaitStrict("before-block", 30, TimeUnit.SECONDS); Future<?> topologyChangeFuture = triggerTopologyChange(NYC, testCaches.removeIndex); discard.set(false); checkPoint.triggerForever("blocked"); topologyChangeFuture.get(); awaitXSiteStateSent(LON); awaitLocalStateTransfer(NYC); assertEventuallyNoStateTransferInReceivingSite(null); assertData(); } private void doXSiteStateTransferDuringTopologyChange(TopologyEvent event) throws TimeoutException, InterruptedException, ExecutionException { /* note: this is not tested with SITE_MASTER_LEAVE because it can start the state transfer in NYC. (startStateTransfer() throws an exception) */ log.debugf("Start topology change during x-site state transfer with %s", event); initBeforeTest(); final TestCaches<Object, Object> testCaches = createTestCache(event, NYC); printTestCaches(testCaches); final BlockingLocalTopologyManager topologyManager = BlockingLocalTopologyManager.replaceTopologyManagerDefaultCache(testCaches.controllerCache.getCacheManager()); final CheckPoint checkPoint = new CheckPoint(); wrapComponent(cache(NYC, 0), BackupReceiver.class, current -> new NotifierBackupReceiver(current, checkPoint)); final Future<Void> topologyEventFuture = triggerTopologyChange(NYC, testCaches.removeIndex); if (event == TopologyEvent.LEAVE) { topologyManager.confirmTopologyUpdate(CacheTopology.Phase.NO_REBALANCE); } topologyManager.confirmTopologyUpdate(CacheTopology.Phase.READ_OLD_WRITE_ALL); log.debug("Start x-site state transfer"); startStateTransfer(testCaches.coordinator, NYC); assertOnline(LON, NYC); //in the current implementation, the x-site state transfer is not triggered while the rebalance is in progress. checkPoint.awaitStrict("before-chunk", 30, TimeUnit.SECONDS); topologyManager.confirmTopologyUpdate(CacheTopology.Phase.READ_ALL_WRITE_ALL); topologyManager.confirmTopologyUpdate(CacheTopology.Phase.READ_NEW_WRITE_ALL); topologyManager.confirmTopologyUpdate(CacheTopology.Phase.NO_REBALANCE); topologyEventFuture.get(); awaitXSiteStateSent(LON); awaitLocalStateTransfer(NYC); assertEventuallyNoStateTransferInReceivingSite(null); assertData(); } private static class NotifierBackupReceiver extends BackupReceiverDelegator { private final CheckPoint checkPoint; NotifierBackupReceiver(BackupReceiver delegate, CheckPoint checkPoint) { super(delegate); this.checkPoint = checkPoint; } @Override public CompletionStage<Void> handleStateTransferState(XSiteStatePushCommand cmd) { checkPoint.trigger("before-chunk"); return delegate.handleStateTransferState(cmd); } } @Scope(Scopes.NAMED_CACHE) static class BlockingBackupReceiver extends BackupReceiverDelegator { private final Set<Address> addressSet = new HashSet<>(); private final AtomicBoolean discard; private final CheckPoint checkPoint; @Inject DistributionManager manager; BlockingBackupReceiver(BackupReceiver delegate, AtomicBoolean discard, CheckPoint checkPoint) { super(delegate); this.discard = discard; this.checkPoint = checkPoint; } @Override public CompletionStage<Void> handleStateTransferState(XSiteStatePushCommand cmd) { if (!discard.get()) { return delegate.handleStateTransferState(cmd); } synchronized (addressSet) { //discard the state message when all member has received at least one chunk! if (addressSet.size() == 3) { checkPoint.trigger("before-block"); try { checkPoint.awaitStrict("blocked", 30, TimeUnit.SECONDS); } catch (InterruptedException | TimeoutException e) { return CompletableFuture.failedFuture(e); } return delegate.handleStateTransferState(cmd); } for (XSiteState state : cmd.getChunk()) { addressSet.add(manager.getCacheTopology().getDistribution(state.key()).primary()); } } return delegate.handleStateTransferState(cmd); } } }
7,821
38.908163
145
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/failures/StateTransferLinkFailuresTest.java
package org.infinispan.xsite.statetransfer.failures; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.wrapGlobalComponent; import static org.infinispan.xsite.XSiteAdminOperations.SUCCESS; import static org.infinispan.xsite.statetransfer.XSiteStateTransferManager.STATUS_ERROR; import static org.testng.Assert.assertNotEquals; 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.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.manager.CacheContainer; import org.infinispan.remoting.transport.AbstractDelegatingTransport; import org.infinispan.remoting.transport.BackupResponse; import org.infinispan.remoting.transport.Transport; import org.infinispan.remoting.transport.XSiteResponse; import org.infinispan.remoting.transport.impl.XSiteResponseImpl; import org.infinispan.statetransfer.CommitManager; import org.infinispan.util.concurrent.TimeoutException; import org.infinispan.xsite.XSiteAdminOperations; import org.infinispan.xsite.XSiteBackup; import org.infinispan.xsite.XSiteReplicateCommand; import org.infinispan.xsite.statetransfer.XSiteStatePushCommand; import org.infinispan.xsite.statetransfer.XSiteStateTransferManager; import org.testng.annotations.Test; /** * Tests the Cross-Site replication state transfer with a broken connection between sites. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "xsite", testName = "xsite.statetransfer.failures.StateTransferLinkFailuresTest") public class StateTransferLinkFailuresTest extends AbstractTopologyChangeTest { public StateTransferLinkFailuresTest() { super(); this.cleanup = CleanupPhase.AFTER_METHOD; this.implicitBackupCache = true; } /* tests: * request the state transfer without link to other site. * lose link while transferring data */ private static ConfigurationBuilder createConfiguration() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.clustering().hash().numOwners(2); return builder; } public void testStartStateTransferWithoutLink() { initBeforeTest(); List<ControllerTransport> transports = replaceTransportInSite(); for (ControllerTransport transport : transports) { transport.fail = true; } assertNotEquals(extractComponent(cache(LON, 0), XSiteAdminOperations.class).pushState(NYC), SUCCESS); assertDataInSite(LON); assertInSite(NYC, cache -> assertTrue(cache.isEmpty())); } public void testLinkBrokenDuringStateTransfer() { initBeforeTest(); List<ControllerTransport> transports = replaceTransportInSite(); for (ControllerTransport transport : transports) { transport.failAfterFirstChunk = true; } startStateTransfer(); assertOnline(LON, NYC); assertEventuallyInSite(LON, cache -> extractComponent(cache, XSiteStateTransferManager.class).getRunningStateTransfers().isEmpty(), 1, TimeUnit.MINUTES); assertEquals(1, getStatus().size()); assertEquals(STATUS_ERROR, getStatus().get(NYC)); assertInSite(NYC, cache -> { //link is broken. NYC is still expecting state. assertTrue(extractComponent(cache, CommitManager.class).isTracking(Flag.PUT_FOR_X_SITE_STATE_TRANSFER)); assertEquals(LON, extractComponent(cache, XSiteAdminOperations.class).getSendingSiteName()); }); assertEquals(SUCCESS, extractComponent(cache(NYC, 0), XSiteAdminOperations.class).cancelReceiveState(LON)); assertInSite(NYC, cache -> { assertFalse(extractComponent(cache, CommitManager.class).isTracking(Flag.PUT_FOR_X_SITE_STATE_TRANSFER)); assertNull(extractComponent(cache, XSiteAdminOperations.class).getSendingSiteName()); }); assertEquals(SUCCESS, extractComponent(cache(LON, 0), XSiteAdminOperations.class).clearPushStateStatus()); } @Override protected ConfigurationBuilder getNycActiveConfig() { return createConfiguration(); } @Override protected ConfigurationBuilder getLonActiveConfig() { return createConfiguration(); } @Override protected void adaptLONConfiguration(BackupConfigurationBuilder builder) { builder.stateTransfer().chunkSize(2).timeout(2000).maxRetries(1); } private Map<String, String> getStatus() { return adminOperations().getPushStateStatus(); } private List<ControllerTransport> replaceTransportInSite() { List<ControllerTransport> transports = new ArrayList<>(site(LON).cacheManagers().size()); for (CacheContainer cacheContainer : site(LON).cacheManagers()) { transports.add(wrapGlobalComponent(cacheContainer, Transport.class, (wrapOn, current) -> new ControllerTransport(current), true)); } return transports; } static class ControllerTransport extends AbstractDelegatingTransport { private volatile boolean fail; private volatile boolean failAfterFirstChunk; ControllerTransport(Transport actual) { super(actual); } @Override public void start() { //no-op; avoid re-start the transport again... } @Override public BackupResponse backupRemotely(Collection<XSiteBackup> backups, XSiteReplicateCommand rpcCommand) { throw new UnsupportedOperationException(); } @Override public <O> XSiteResponse<O> backupRemotely(XSiteBackup backup, XSiteReplicateCommand<O> rpcCommand) { if (fail) { getLog().debugf("Inducing timeout for %s", rpcCommand); XSiteResponseImpl<O> rsp = new XSiteResponseImpl<>(TIME_SERVICE, backup); //completeExceptionally is ok since we don't care about the stats. rsp.completeExceptionally(new TimeoutException("induced timeout!")); return rsp; } else if (failAfterFirstChunk && rpcCommand instanceof XSiteStatePushCommand) { fail = true; } return super.backupRemotely(backup, rpcCommand); } } }
6,559
37.139535
118
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/OptDistBackupFailure2Test.java
package org.infinispan.xsite.backupfailure; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.backupfailure.OptDistBackupFailure2Test") public class OptDistBackupFailure2Test extends NonTxBackupFailureTest { public OptDistBackupFailure2Test() { lonBackupFailurePolicy = BackupFailurePolicy.FAIL; } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } }
869
29
84
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/OptDistBackupFailureTest.java
package org.infinispan.xsite.backupfailure; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.backupfailure.OptDistBackupFailureTest") public class OptDistBackupFailureTest extends NonTxBackupFailureTest { @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } }
701
28.25
83
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/BaseBackupFailureTest.java
package org.infinispan.xsite.backupfailure; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.tx.RollbackCommand; import org.infinispan.commands.write.ClearCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.xsite.AbstractTwoSitesTest; import org.testng.annotations.BeforeMethod; /** * @author Mircea Markus * @since 5.2 */ public abstract class BaseBackupFailureTest extends AbstractTwoSitesTest { protected FailureInterceptor failureInterceptor; @Override protected void createSites() { super.createSites(); failureInterceptor = new FailureInterceptor(); backup(LON).getAdvancedCache().getAsyncInterceptorChain().addInterceptor(failureInterceptor, 1); } @BeforeMethod void resetFailureInterceptor() { failureInterceptor.reset(); } public static class FailureInterceptor extends DDAsyncInterceptor { protected volatile boolean isFailing = false; protected volatile boolean rollbackFailed; protected volatile boolean commitFailed; protected volatile boolean prepareFailed; protected volatile boolean putFailed; protected volatile boolean removeFailed; protected volatile boolean clearFailed; protected volatile boolean writeOnlyManyEntriesFailed; public void reset() { rollbackFailed = false; commitFailed = false; prepareFailed = false; putFailed = false; removeFailed = false; clearFailed = false; writeOnlyManyEntriesFailed = false; isFailing = false; } private Object handle(InvocationContext ctx, VisitableCommand command, Runnable logFailure) throws Throwable { if (isFailing) { logFailure.run(); throw new CacheException("Induced failure"); } else { return invokeNext(ctx, command); } } @Override public Object visitRollbackCommand(TxInvocationContext ctx, RollbackCommand command) throws Throwable { return handle(ctx, command, () -> rollbackFailed = true); } @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { return handle(ctx, command, () -> commitFailed = true); } @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { return handle(ctx, command, () -> prepareFailed = true); } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { return handle(ctx, command, () -> putFailed = true); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { return handle(ctx, command, () -> removeFailed = true); } @Override public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { return handle(ctx, command, () -> clearFailed = true); } @Override public Object visitWriteOnlyManyEntriesCommand(InvocationContext ctx, WriteOnlyManyEntriesCommand command) throws Throwable { return handle(ctx, command, () -> writeOnlyManyEntriesFailed = true); } public void disable() { isFailing = false; } public void enable() { isFailing = true; } } protected boolean failOnBackupFailure(String site, int cacheIndex) { return cache(site, cacheIndex).getCacheConfiguration().sites().allBackups().get(0).backupFailurePolicy() == BackupFailurePolicy.FAIL; } }
4,195
34.260504
139
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/CustomFailurePolicyTest.java
package org.infinispan.xsite.backupfailure; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.xsite.CountingCustomFailurePolicy; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.backupfailure.CustomFailurePolicyTest") public class CustomFailurePolicyTest extends NonTxBackupFailureTest{ public CustomFailurePolicyTest() { lonBackupFailurePolicy = BackupFailurePolicy.CUSTOM; lonCustomFailurePolicyClass = CountingCustomFailurePolicy.class.getName(); } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } @Override public void testPutFailure() { assertFalse(CountingCustomFailurePolicy.PUT_INVOKED); super.testPutFailure(); assertTrue(CountingCustomFailurePolicy.PUT_INVOKED); } @Override public void testRemoveFailure() { assertFalse(CountingCustomFailurePolicy.REMOVE_INVOKED); super.testRemoveFailure(); assertTrue(CountingCustomFailurePolicy.REMOVE_INVOKED); } @Override public void testReplaceFailure() { assertFalse(CountingCustomFailurePolicy.REPLACE_INVOKED); super.testReplaceFailure(); assertTrue(CountingCustomFailurePolicy.REPLACE_INVOKED); } @Override public void testClearFailure() { assertFalse(CountingCustomFailurePolicy.CLEAR_INVOKED); super.testClearFailure(); assertTrue(CountingCustomFailurePolicy.CLEAR_INVOKED); } @Override public void testPutMapFailure() { assertFalse(CountingCustomFailurePolicy.PUT_ALL_INVOKED); super.testPutMapFailure(); assertTrue(CountingCustomFailurePolicy.PUT_ALL_INVOKED); } }
2,162
30.347826
82
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/OptReplBackupFailureTest.java
package org.infinispan.xsite.backupfailure; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.backupfailure.OptReplBackupFailureTest") public class OptReplBackupFailureTest extends NonTxBackupFailureTest { @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); } }
701
28.25
83
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/OptReplBackupFailure2Test.java
package org.infinispan.xsite.backupfailure; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "xsite", testName = "xsite.backupfailure.OptReplBackupFailure2Test") public class OptReplBackupFailure2Test extends NonTxBackupFailureTest { public OptReplBackupFailure2Test() { lonBackupFailurePolicy = BackupFailurePolicy.FAIL; } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); } }
868
28.965517
83
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/NonTxBackupFailureTest.java
package org.infinispan.xsite.backupfailure; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.HashMap; import java.util.Map; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.backupfailure.NonTxBackupFailureTest") public class NonTxBackupFailureTest extends BaseBackupFailureTest { @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } public void testPutFailure() { failureInterceptor.enable(); try { cache(LON, 0).put("k", "v"); checkFailOnBackupFailure(); } catch (CacheException e) { checkNonFailOnBackupFailure(); } finally { failureInterceptor.disable(); } //in triangle, if an exception is received, the originator doesn't wait for the ack from backup //it is possible to check the value before the backup handles the BackupWriteCommand. eventuallyEquals("v", () -> cache(LON, 1).get("k")); assertTrue(failureInterceptor.putFailed); assertNull(backup(LON).get("k")); } public void testRemoveFailure() { cache(LON, 0).put("k", "v"); assertEquals("v", cache(LON, 1).get("k")); assertEquals("v", backup(LON).get("k")); failureInterceptor.enable(); try { cache(LON, 0).remove("k"); checkFailOnBackupFailure(); } catch (CacheException e) { checkNonFailOnBackupFailure(); } finally { failureInterceptor.disable(); } eventuallyEquals(null, () -> cache(LON, 0).get("k")); eventuallyEquals(null, () -> cache(LON, 1).get("k")); assertTrue(failureInterceptor.removeFailed); assertEquals("v", backup(LON).get("k")); } public void testReplaceFailure() { failureInterceptor.disable(); cache(LON, 0).put("k", "v"); assertEquals("v", cache(LON, 1).get("k")); assertEquals("v", backup(LON).get("k")); failureInterceptor.enable(); try { cache(LON, 0).replace("k", "v2"); checkFailOnBackupFailure(); } catch (CacheException e) { checkNonFailOnBackupFailure(); } finally { failureInterceptor.disable(); } eventuallyEquals("v2", () -> cache(LON, 0).get("k")); eventuallyEquals("v2", () -> cache(LON, 1).get("k")); //the ReplaceCommand is transformed in a PutKeyValueCommand when it succeeds in the originator site! assertTrue(failureInterceptor.putFailed); assertEquals("v", backup(LON).get("k")); } public void testClearFailure() { cache(LON, 0).put("k1", "v1"); cache(LON, 0).put("k2", "v2"); cache(LON, 0).put("k3", "v3"); failureInterceptor.enable(); try { cache(LON, 1).clear(); checkFailOnBackupFailure(); } catch (CacheException e) { checkNonFailOnBackupFailure(); } finally { failureInterceptor.disable(); } eventuallyEquals(null, () -> cache(LON, 0).get("k1")); eventuallyEquals(null, () -> cache(LON, 0).get("k2")); eventuallyEquals(null, () -> cache(LON, 0).get("k3")); eventuallyEquals(null, () -> cache(LON, 1).get("k1")); eventuallyEquals(null, () -> cache(LON, 1).get("k2")); eventuallyEquals(null, () -> cache(LON, 1).get("k3")); assertTrue(failureInterceptor.clearFailed); assertEquals("v1", backup(LON).get("k1")); assertEquals("v2", backup(LON).get("k2")); assertEquals("v3", backup(LON).get("k3")); } public void testPutMapFailure() { Map<String, String> toAdd = new HashMap<>(); for (int i = 0; i < 100; i++) { toAdd.put("k" + i, "v" + i); } failureInterceptor.enable(); try { cache(LON, 0).putAll(toAdd); checkFailOnBackupFailure(); } catch (CacheException e) { checkNonFailOnBackupFailure(); } finally { failureInterceptor.disable(); } assertTrue(failureInterceptor.writeOnlyManyEntriesFailed); for (int i = 0; i < 100; i++) { final int keyIndex = i; // In the past, data was xsite-backed up from origin only after all entries were committed locally. // back to the origin and this causes the triangle's collector future to fail with exception. // Entries that are not owned locally are not committed then (as the failure comes in distribution interceptor) // which is below entry-wrapping, though those entries that could not be xsite-backed up are committed. if (lonBackupFailurePolicy != BackupFailurePolicy.FAIL) { eventuallyEquals("v" + keyIndex, () -> cache(LON, keyIndex % 2).get("k" + keyIndex)); } assertNull(backup(LON).get("k" + i)); } } private void checkNonFailOnBackupFailure() { if (!failOnBackupFailure(LON, 0)) throw new AssertionError("Should fail silently!"); } private void checkFailOnBackupFailure() { if (failOnBackupFailure(LON, 0)) throw new AssertionError("Exception expected!"); } }
5,620
33.484663
120
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/tx/ReplBackupTxFailureTest.java
package org.infinispan.xsite.backupfailure.tx; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.backupfailure.tx.ReplBackupTxFailureTest") public class ReplBackupTxFailureTest extends BaseBackupTxFailureTest { public ReplBackupTxFailureTest() { use2Pc = true; } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); } }
769
26.5
85
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/tx/DistLocalClusterTxBackupFailureTest.java
package org.infinispan.xsite.backupfailure.tx; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.backupfailure.tx.DistLocalClusterTxBackupFailureTest") public class DistLocalClusterTxBackupFailureTest extends BaseLocalClusterTxFailureTest { public DistLocalClusterTxBackupFailureTest() { isLonBackupTransactional = true; } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } }
829
28.642857
97
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/tx/SinglePhaseCommitFailureTest.java
package org.infinispan.xsite.backupfailure.tx; import static org.infinispan.commons.test.Exceptions.expectException; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.xsite.AbstractTwoSitesTest; import org.infinispan.xsite.backupfailure.BaseBackupFailureTest; import org.testng.annotations.Test; @Test(groups = "xsite", testName = "xsite.backupfailure.tx.SinglePhaseCommitFailureTest") public class SinglePhaseCommitFailureTest extends AbstractTwoSitesTest { private BaseBackupFailureTest.FailureInterceptor failureInterceptor; public SinglePhaseCommitFailureTest() { use2Pc = false; lonBackupFailurePolicy = BackupFailurePolicy.FAIL; } @Override protected void createSites() { super.createSites(); failureInterceptor = new BaseBackupFailureTest.FailureInterceptor(); backup(LON).getAdvancedCache().getAsyncInterceptorChain().addInterceptor(failureInterceptor, 1); } public void testPrepareFailure() { failureInterceptor.enable(); try { expectException(CacheException.class, () -> cache(LON, 0).put("k", "v")); } finally { failureInterceptor.disable(); } } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); } @Override protected ConfigurationBuilder getLonActiveConfig() { ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); dcc.transaction().useSynchronization(false);//this makes the TM throw an exception if the 2nd phase fails return dcc; } }
1,806
34.431373
111
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/tx/BaseLocalClusterTxFailureTest.java
package org.infinispan.xsite.backupfailure.tx; import static org.testng.AssertJUnit.assertNull; import jakarta.transaction.RollbackException; import org.infinispan.commons.CacheException; import org.infinispan.commons.test.Exceptions; import org.infinispan.xsite.AbstractTwoSitesTest; import org.infinispan.xsite.backupfailure.BaseBackupFailureTest; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "xsite") public abstract class BaseLocalClusterTxFailureTest extends AbstractTwoSitesTest { private BaseBackupFailureTest.FailureInterceptor failureInterceptor; @Override protected void createSites() { super.createSites(); failureInterceptor = new BaseBackupFailureTest.FailureInterceptor(); cache(LON, 1).getAdvancedCache().getAsyncInterceptorChain().addInterceptor(failureInterceptor, 1); } public void testPrepareFailure() { failureInterceptor.enable(); try { Exceptions.expectException(CacheException.class, RollbackException.class, () -> cache(LON, 0).put("k", "v")); } finally { failureInterceptor.disable(); } assertNull(cache(LON,0).get("k")); assertNull(cache(LON,1).get("k")); assertNull(backup(LON).get("k")); } }
1,276
30.146341
118
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/tx/ReplLocalClusterFailureTest.java
package org.infinispan.xsite.backupfailure.tx; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.backupfailure.tx.ReplLocalClusterFailureTest") public class ReplLocalClusterFailureTest extends BaseLocalClusterTxFailureTest { @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); } }
718
28.958333
89
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/tx/CustomFailurePolicyTxTest.java
package org.infinispan.xsite.backupfailure.tx; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.xsite.CountingCustomFailurePolicy; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.backupfailure.tx.CustomFailurePolicyTxTest") public class CustomFailurePolicyTxTest extends BaseBackupTxFailureTest { public CustomFailurePolicyTxTest() { lonBackupFailurePolicy = BackupFailurePolicy.CUSTOM; lonCustomFailurePolicyClass = CountingCustomFailurePolicy.class.getName(); } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } @Override public void testPrepareFailure() { assertFalse(CountingCustomFailurePolicy.PREPARE_INVOKED); super.testPrepareFailure(); assertTrue(CountingCustomFailurePolicy.PREPARE_INVOKED); } }
1,332
31.512195
87
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/tx/BaseBackupTxFailureTest.java
package org.infinispan.xsite.backupfailure.tx; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import jakarta.transaction.RollbackException; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.commons.test.Exceptions; import org.infinispan.xsite.AbstractTwoSitesTest; import org.infinispan.xsite.backupfailure.BaseBackupFailureTest; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "xsite") public abstract class BaseBackupTxFailureTest extends AbstractTwoSitesTest { private BaseBackupFailureTest.FailureInterceptor failureInterceptor; protected BaseBackupTxFailureTest() { isLonBackupTransactional = true; lonBackupFailurePolicy = BackupFailurePolicy.FAIL; use2Pc = true; } @Override protected void createSites() { super.createSites(); failureInterceptor = new BaseBackupFailureTest.FailureInterceptor(); backup(LON).getAdvancedCache().getAsyncInterceptorChain().addInterceptor(failureInterceptor, 1); } public void testPrepareFailure() { failureInterceptor.enable(); try { Exceptions.expectException(CacheException.class, RollbackException.class, () -> cache(LON, 0).put("k", "v")); } finally { failureInterceptor.disable(); } assertNull(cache(LON,0).get("k")); assertNull(cache(LON,1).get("k")); assertNull(backup(LON).get("k")); assertEquals(0, txTable(cache(LON, 0)).getLocalTransactions().size()); assertEquals(0, txTable(cache(LON, 1)).getLocalTransactions().size()); assertEquals(0, txTable(backup(LON)).getLocalTransactions().size()); } }
1,775
33.153846
118
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/tx/DistLocalClusterFailureTest.java
package org.infinispan.xsite.backupfailure.tx; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.backupfailure.tx.DistLocalClusterFailureTest") public class DistLocalClusterFailureTest extends BaseLocalClusterTxFailureTest { @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } }
718
28.958333
89
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/backupfailure/tx/DistBackupTxFailureTest.java
package org.infinispan.xsite.backupfailure.tx; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.backupfailure.tx.DistBackupTxFailureTest") public class DistBackupTxFailureTest extends BaseBackupTxFailureTest { @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } }
704
28.375
85
java
null
infinispan-main/core/src/test/java/org/infinispan/affinity/impl/KeyAffinityServiceTest.java
package org.infinispan.affinity.impl; import static org.testng.AssertJUnit.assertEquals; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import org.infinispan.Cache; import org.infinispan.affinity.KeyAffinityServiceFactory; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.Address; import org.testng.annotations.Test; /** * @author Mircea.Markus@jboss.com * @since 4.1 */ @Test(groups = "functional", testName = "affinity.KeyAffinityServiceTest") public class KeyAffinityServiceTest extends BaseKeyAffinityServiceTest { @Override protected void createCacheManagers() throws Throwable { super.INIT_CLUSTER_SIZE = 2; super.createCacheManagers(); assertEquals(2, topology(caches.get(0).getCacheManager()).size()); assertEquals(2, topology(caches.get(1).getCacheManager()).size()); cache(0, cacheName).put("k", "v"); assertEquals("v", cache(0, cacheName).get("k")); assertEquals("v", cache(1, cacheName).get("k")); keyAffinityService = (KeyAffinityServiceImpl<Object>) KeyAffinityServiceFactory.newKeyAffinityService(manager(0).getCache(cacheName), executor, new RndKeyGenerator(), 100); } public void testKeysAreCorrectlyCreated() throws Exception { assertEventualFullCapacity(); assertKeyAffinityCorrectness(); } @Test (dependsOnMethods = "testKeysAreCorrectlyCreated") public void testConcurrentConsumptionOfKeys() throws InterruptedException { List<KeyConsumer> consumers = new ArrayList<>(); int keysToConsume = 1000; CountDownLatch consumersStart = new CountDownLatch(1); for (int i = 0; i < 10; i++) { consumers.add(new KeyConsumer(keysToConsume, consumersStart)); } consumersStart.countDown(); for (KeyConsumer kc : consumers) { kc.join(); } for (KeyConsumer kc : consumers) { assertEquals(null, kc.exception); } assertCorrectCapacity(); } @Test (dependsOnMethods = "testConcurrentConsumptionOfKeys") public void testServerAdded() throws InterruptedException { EmbeddedCacheManager cm = addClusterEnabledCacheManager(); cm.defineConfiguration(cacheName, configuration.build()); Cache<Object, String> cache = cm.getCache(cacheName); caches.add(cache); waitForClusterToResize(); eventuallyEquals(3, () -> keyAffinityService.getAddress2KeysMapping().keySet().size()); assertEventualFullCapacity(); assertKeyAffinityCorrectness(); } @Test(dependsOnMethods = "testServerAdded") public void testServersDropped() throws InterruptedException { caches.get(2).getCacheManager().stop(); caches.remove(2); waitForClusterToResize(); eventuallyEquals(2, () -> keyAffinityService.getAddress2KeysMapping().keySet().size()); assertEventualFullCapacity(); assertKeyAffinityCorrectness(); } @Test (dependsOnMethods = "testServersDropped") public void testCollocatedKey() { LocalizedCacheTopology cacheTopology = manager(0).getCache(cacheName).getAdvancedCache().getDistributionManager().getCacheTopology(); for (int i = 0; i < 1000; i++) { List<Address> addresses = cacheTopology.getDistribution(i).writeOwners(); Object collocatedKey = keyAffinityService.getCollocatedKey(i); List<Address> addressList = cacheTopology.getDistribution(collocatedKey).writeOwners(); assertEquals(addresses, addressList); } } public class KeyConsumer extends Thread { volatile Exception exception; private final int keysToConsume; private CountDownLatch consumersStart; private final List<Address> topology = topology(); private final Random rnd = new Random(); public KeyConsumer(int keysToConsume, CountDownLatch consumersStart) { super("KeyConsumer"); this.keysToConsume = keysToConsume; this.consumersStart = consumersStart; start(); } @Override public void run() { try { consumersStart.await(); } catch (InterruptedException e) { log.debug("KeyConsumer thread interrupted"); return; } for (int i = 0; i < keysToConsume; i++) { Address whichAddr = topology.get(rnd.nextInt(topology.size())); try { Object keyForAddress = keyAffinityService.getKeyForAddress(whichAddr); assertMapsToAddress(keyForAddress, whichAddr); } catch (Exception e) { this.exception = e; break; } } } } }
4,805
33.57554
139
java
null
infinispan-main/core/src/test/java/org/infinispan/affinity/impl/BaseKeyAffinityServiceTest.java
package org.infinispan.affinity.impl; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.fail; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.infinispan.distribution.BaseDistFunctionalTest; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.manager.CacheContainer; import org.infinispan.remoting.transport.Address; import org.infinispan.test.TestingUtil; import org.testng.annotations.AfterClass; /** * @author Mircea.Markus@jboss.com * @since 4.1 */ public abstract class BaseKeyAffinityServiceTest extends BaseDistFunctionalTest<Object, String> { protected ThreadFactory threadFactory = getTestThreadFactory("KeyGeneratorThread"); protected ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory); protected KeyAffinityServiceImpl<Object> keyAffinityService; @AfterClass(alwaysRun = true) public void stopExecutorService() throws InterruptedException { if (keyAffinityService != null) keyAffinityService.stop(); if (executor != null) { executor.shutdown(); boolean terminatedGracefully = executor.awaitTermination(100, TimeUnit.MILLISECONDS); executor.shutdownNow(); if (!terminatedGracefully) { fail("KeyGenerator Executor not terminated in expected time"); } } } protected void assertMapsToAddress(Object o, Address addr) { LocalizedCacheTopology cacheTopology = caches.get(0).getAdvancedCache().getDistributionManager().getCacheTopology(); List<Address> addresses = cacheTopology.getDistribution(o).writeOwners(); assertEquals("Expected key " + o + " to map to address " + addr + ". List of addresses is" + addresses, true, addresses.contains(addr)); } protected List<Address> topology() { return topology(caches.get(0).getCacheManager()); } protected List<Address> topology(CacheContainer cm) { return cm.getCache(cacheName).getAdvancedCache().getRpcManager().getTransport().getMembers(); } protected void assertEventualFullCapacity() throws InterruptedException { List<Address> addresses = topology(); assertEventualFullCapacity(addresses); } protected void assertCorrectCapacity() throws InterruptedException { assertCorrectCapacity(topology()); } protected void assertEventualFullCapacity(List<Address> addresses) throws InterruptedException { int capacity = 100; eventuallyEquals(capacity * addresses.size(), keyAffinityService::getMaxNumberOfKeys); Map<Address, BlockingQueue<Object>> blockingQueueMap = keyAffinityService.getAddress2KeysMapping(); for (Address addr : addresses) { final BlockingQueue<Object> queue = blockingQueueMap.get(addr); //the queue will eventually get filled eventuallyEquals(capacity, queue::size); } eventuallyEquals(capacity * addresses.size(), () -> keyAffinityService.existingKeyCount.get()); // give the worker thread some time to shut down Thread.sleep(200); assertFalse(keyAffinityService.isKeyGeneratorThreadActive()); } protected void assertCorrectCapacity(List<Address> addresses) throws InterruptedException { Map<Address, BlockingQueue<Object>> blockingQueueMap = keyAffinityService.getAddress2KeysMapping(); long maxWaitTime = 5 * 60 * 1000; for (Address addr : addresses) { BlockingQueue<Object> queue = blockingQueueMap.get(addr); long giveupTime = System.currentTimeMillis() + maxWaitTime; while (queue.size() < KeyAffinityServiceImpl.THRESHOLD * 100 && System.currentTimeMillis() < giveupTime) Thread.sleep(100); assert queue.size() >= KeyAffinityServiceImpl.THRESHOLD * 100 : "Obtained " + queue.size(); } } protected void assertKeyAffinityCorrectness() { List<Address> addressList = topology(); assertKeyAffinityCorrectness(addressList); } protected void assertKeyAffinityCorrectness(Collection<Address> addressList) { Map<Address, BlockingQueue<Object>> blockingQueueMap = keyAffinityService.getAddress2KeysMapping(); for (Address addr : addressList) { BlockingQueue<Object> queue = blockingQueueMap.get(addr); assertEquals(100, queue.size()); for (Object o : queue) { assertMapsToAddress(o, addr); } } } protected void waitForClusterToResize() { TestingUtil.blockUntilViewsReceived(10000, false, caches); TestingUtil.waitForNoRebalance(caches); assertEquals(caches.size(), topology().size()); } }
4,899
40.176471
142
java
null
infinispan-main/core/src/test/java/org/infinispan/affinity/impl/BaseFilterKeyAffinityServiceTest.java
package org.infinispan.affinity.impl; import static org.testng.AssertJUnit.assertEquals; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import org.infinispan.Cache; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.Address; import org.infinispan.test.TestingUtil; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * @author Mircea.Markus@jboss.com * @since 4.1 */ public abstract class BaseFilterKeyAffinityServiceTest extends BaseKeyAffinityServiceTest { private static final Log log = LogFactory.getLog(BaseFilterKeyAffinityServiceTest.class); protected EmbeddedCacheManager cacheManager; @Override protected void createCacheManagers() throws Throwable { INIT_CLUSTER_SIZE = 2; super.createCacheManagers(); createService(); } protected abstract void createService(); protected abstract List<Address> getAddresses() ; protected void testSingleKey() throws InterruptedException { Map<Address, BlockingQueue<Object>> blockingQueueMap = keyAffinityService.getAddress2KeysMapping(); assertEquals(getAddresses().size(), blockingQueueMap.keySet().size()); assertEventualFullCapacity(getAddresses()); } protected void testAddNewServer() throws Exception { EmbeddedCacheManager cm = addClusterEnabledCacheManager(); cm.defineConfiguration(cacheName, configuration.build()); Cache<Object, String> cache = cm.getCache(cacheName); caches.add(cache); waitForClusterToResize(); assertUnaffected(); } protected void testRemoveServers() throws InterruptedException { log.info("** before calling stop"); caches.get(2).getCacheManager().stop(); caches.remove(2); waitForClusterToResize(); assertEquals(2, caches.size()); assertUnaffected(); } protected void testShutdownOwnManager() { log.info("**** here it starts"); caches.get(0).getCacheManager().stop(); caches.remove(0); assertEquals(1, caches.size()); TestingUtil.blockUntilViewsReceived(10000, false, caches.toArray(new Cache[0])); assertEquals(1, topology().size()); eventually(new Condition() { @Override public boolean isSatisfied() throws Exception { return !keyAffinityService.isStarted(); } }); } private void assertUnaffected() throws InterruptedException { eventually(new Condition() { @Override public boolean isSatisfied() throws Exception { return keyAffinityService.getAddress2KeysMapping().keySet().size() == getAddresses().size(); } }); assertEventualFullCapacity(getAddresses()); assertKeyAffinityCorrectness(getAddresses()); } }
2,840
30.566667
105
java
null
infinispan-main/core/src/test/java/org/infinispan/affinity/impl/KeyAffinityServiceShutdownTest.java
package org.infinispan.affinity.impl; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.affinity.KeyAffinityServiceFactory; import org.infinispan.affinity.ListenerRegistration; import org.infinispan.manager.EmbeddedCacheManager; import org.testng.annotations.Test; /** * @author Mircea.Markus@jboss.com * @since 4.1 */ @Test (groups = "functional", testName = "affinity.KeyAffinityServiceShutdownTest") public class KeyAffinityServiceShutdownTest extends BaseKeyAffinityServiceTest { private EmbeddedCacheManager cacheManager; @Override protected void createCacheManagers() throws Throwable { super.createCacheManagers(); cacheManager = manager(0); keyAffinityService = (KeyAffinityServiceImpl<Object>) KeyAffinityServiceFactory.newKeyAffinityService(cacheManager.getCache(cacheName), executor, new RndKeyGenerator(), 100); } public void testSimpleShutdown() throws Exception { assertListenerRegistered(true); assertEventualFullCapacity(); assert keyAffinityService.isKeyGeneratorThreadAlive(); keyAffinityService.stop(); for (int i = 0; i < 10; i++) { if (!keyAffinityService.isKeyGeneratorThreadAlive()) break; Thread.sleep(1000); } assert !keyAffinityService.isKeyGeneratorThreadAlive(); assert !executor.isShutdown(); } @Test(dependsOnMethods = "testSimpleShutdown") public void testServiceCannotBeUsedAfterShutdown() { try { keyAffinityService.getKeyForAddress(topology().get(0)); assert false : "Exception expected!"; } catch (IllegalStateException e) { //expected } try { keyAffinityService.getCollocatedKey("a"); assert false : "Exception expected!"; } catch (IllegalStateException e) { //expected } } @Test (dependsOnMethods = "testServiceCannotBeUsedAfterShutdown") public void testViewChaneListenerUnregistered() { assertListenerRegistered(false); } @Test (dependsOnMethods = "testViewChaneListenerUnregistered") public void testRestart() throws InterruptedException { keyAffinityService.start(); assertEventualFullCapacity(); } private void assertListenerRegistered(boolean registered) { boolean isRegistered = false; for (Object o : cacheManager.getListeners()) { if (o instanceof ListenerRegistration) { isRegistered = true; break; } } assertEquals(registered, isRegistered); } }
2,563
31.455696
141
java
null
infinispan-main/core/src/test/java/org/infinispan/affinity/impl/FilteredKeyAffinityServiceTest.java
package org.infinispan.affinity.impl; import java.util.ArrayList; import java.util.List; import org.infinispan.affinity.KeyAffinityServiceFactory; import org.infinispan.remoting.transport.Address; import org.testng.annotations.Test; /** * * This class just overrides the methods in the base class as TestNG behaves funny with depending methods and inheritance. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Test (groups = "functional", testName = "affinity.FilteredKeyAffinityServiceTest") public class FilteredKeyAffinityServiceTest extends BaseFilterKeyAffinityServiceTest { private List<Address> filter; @Override protected void createService() { filter = new ArrayList<Address>(); filter.add(caches.get(0).getAdvancedCache().getRpcManager().getTransport().getAddress()); filter.add(caches.get(1).getAdvancedCache().getRpcManager().getTransport().getAddress()); cacheManager = caches.get(0).getCacheManager(); keyAffinityService = (KeyAffinityServiceImpl<Object>) KeyAffinityServiceFactory. newKeyAffinityService(cacheManager.getCache(cacheName), filter, new RndKeyGenerator(), executor, 100); } @Override protected List<Address> getAddresses() { return filter; } @Override public void testSingleKey() throws InterruptedException { super.testSingleKey(); } @Test(dependsOnMethods = "testSingleKey") public void testAddNewServer() throws Exception { super.testAddNewServer(); } @Test(dependsOnMethods = "testAddNewServer") public void testRemoveServers() throws InterruptedException { super.testRemoveServers(); } @Test (dependsOnMethods = "testRemoveServers") public void testShutdownOwnManager() { super.testShutdownOwnManager(); } }
1,808
30.736842
123
java
null
infinispan-main/core/src/test/java/org/infinispan/affinity/impl/LocalKeyAffinityServiceTest.java
package org.infinispan.affinity.impl; import java.util.Collections; import java.util.List; import org.infinispan.affinity.KeyAffinityServiceFactory; import org.infinispan.remoting.transport.Address; import org.testng.annotations.Test; /** * This class just overrides the methods in the base class as TestNG behaves funny with depending methods and inheritance. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Test(groups = "functional", testName = "affinity.LocalKeyAffinityServiceTest") public class LocalKeyAffinityServiceTest extends BaseFilterKeyAffinityServiceTest { @Override protected void createService() { { cacheManager = caches.get(0).getCacheManager(); keyAffinityService = (KeyAffinityServiceImpl<Object>) KeyAffinityServiceFactory. newLocalKeyAffinityService(cacheManager.getCache(cacheName), new RndKeyGenerator(), executor, 100); } } @Override protected List<Address> getAddresses() { return Collections.singletonList(cacheManager.getAddress()); } public void testFilteredSingleKey() throws InterruptedException { super.testSingleKey(); } @Test(dependsOnMethods = "testFilteredSingleKey") public void testFilteredAddNewServer() throws Exception { super.testAddNewServer(); } @Test(dependsOnMethods = "testFilteredAddNewServer") public void testFilteredRemoveServers() throws InterruptedException { super.testRemoveServers(); } @Test (dependsOnMethods = "testFilteredRemoveServers") public void testShutdownOwnManager() { super.testShutdownOwnManager(); } }
1,639
29.943396
122
java
null
infinispan-main/core/src/test/java/org/infinispan/affinity/impl/ConcurrentStartupTest.java
package org.infinispan.affinity.impl; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.infinispan.AdvancedCache; import org.infinispan.affinity.KeyAffinityService; import org.infinispan.affinity.KeyAffinityServiceFactory; 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.testng.annotations.AfterClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author Mircea Markus */ @Test (groups = "functional", testName = "affinity.ConcurrentStartupTest") public class ConcurrentStartupTest extends AbstractCacheTest { public static final int KEY_QUEUE_SIZE = 100; EmbeddedCacheManager manager1 = null, manager2 = null; AdvancedCache<Object, Object> cache1 = null, cache2 = null; KeyAffinityService<Object> keyAffinityService1 = null, keyAffinityService2 = null; private ExecutorService ex1; private ExecutorService ex2; @BeforeMethod protected void setUp() throws Exception { ConfigurationBuilder configurationBuilder = TestCacheManagerFactory.getDefaultCacheConfiguration(true); configurationBuilder.transaction().invocationBatching().enable() .clustering().cacheMode(CacheMode.DIST_SYNC) .clustering().hash().numOwners(1) .clustering().stateTransfer().fetchInMemoryState(false); manager1 = TestCacheManagerFactory.createClusteredCacheManager(configurationBuilder); manager1.defineConfiguration("test", configurationBuilder.build()); cache1 = manager1.getCache("test").getAdvancedCache(); ex1 = Executors.newSingleThreadExecutor(getTestThreadFactory("KeyGenerator1")); keyAffinityService1 = KeyAffinityServiceFactory.newLocalKeyAffinityService(cache1, new RndKeyGenerator(), ex1, KEY_QUEUE_SIZE); log.trace("Address for manager1: " + manager1.getAddress()); manager2 = TestCacheManagerFactory.createClusteredCacheManager(configurationBuilder); manager2.defineConfiguration("test", configurationBuilder.build()); cache2 = manager2.getCache("test").getAdvancedCache(); ex2 = Executors.newSingleThreadExecutor(getTestThreadFactory("KeyGenerator2")); keyAffinityService2 = KeyAffinityServiceFactory.newLocalKeyAffinityService(cache2, new RndKeyGenerator(), ex2, KEY_QUEUE_SIZE); log.trace("Address for manager2: " + manager2.getAddress()); TestingUtil.blockUntilViewsReceived(60000, cache1, cache2); Thread.sleep(5000); } @AfterClass(alwaysRun = true) protected void tearDown() throws Exception { if (ex1 != null) ex1.shutdownNow(); if (ex2 != null) ex2.shutdownNow(); if (keyAffinityService1 != null) keyAffinityService1.stop(); if (keyAffinityService2 != null) keyAffinityService2.stop(); TestingUtil.killCacheManagers(manager1, manager2); } public void testKeyAffinityServiceFails() { log.trace("Test keys for cache2."); for (int i = 0; i < KEY_QUEUE_SIZE; i++) { Object keyForAddress = keyAffinityService2.getKeyForAddress(manager2.getAddress()); assertTrue(cache2.getDistributionManager().getCacheTopology().isWriteOwner(keyForAddress)); } log.trace("Test keys for cache1."); for (int i = 0; i < KEY_QUEUE_SIZE; i++) { Object keyForAddress = keyAffinityService1.getKeyForAddress(manager1.getAddress()); assertTrue(cache1.getDistributionManager().getCacheTopology().isWriteOwner(keyForAddress)); } } }
3,812
44.392857
133
java
null
infinispan-main/core/src/test/java/org/infinispan/invalidation/SyncInvalidationTest.java
package org.infinispan.invalidation; import org.testng.annotations.Test; @Test(groups = {"functional", "smoke"}, testName = "invalidation.SyncInvalidationTest") public class SyncInvalidationTest extends BaseInvalidationTest { public SyncInvalidationTest() { isSync = true; } }
291
25.545455
87
java
null
infinispan-main/core/src/test/java/org/infinispan/invalidation/TxInvalidationLockingTest.java
package org.infinispan.invalidation; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNull; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.CheckPoint; 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.util.concurrent.IsolationLevel; import org.testng.annotations.Test; /** * Test that global locks protect the shared store with pessimistic and optimistic locking. * * <p>See ISPN-10029</p> * * @author Dan Berindei */ @Test(groups = "functional", testName = "invalidation.TxInvalidationLockingTest") public class TxInvalidationLockingTest extends MultipleCacheManagersTest { private static final String KEY = "key"; private static final String VALUE1 = "value1"; private static final Object VALUE2 = "value2"; private static final String PESSIMISTIC_CACHE = "pessimistic"; private static final String OPTIMISTIC_CACHE = "optimistic"; @Override protected void createCacheManagers() throws Throwable { addClusterEnabledCacheManager(); addClusterEnabledCacheManager(); defineCache(PESSIMISTIC_CACHE, LockingMode.PESSIMISTIC); defineCache(OPTIMISTIC_CACHE, LockingMode.OPTIMISTIC); waitForClusterToForm(PESSIMISTIC_CACHE, OPTIMISTIC_CACHE); } private void defineCache(String cacheName, LockingMode lockingMode) { ConfigurationBuilder config = buildConfig(lockingMode); manager(0).defineConfiguration(cacheName, config.build()); manager(1).defineConfiguration(cacheName, config.build()); } private ConfigurationBuilder buildConfig(LockingMode lockingMode) { ConfigurationBuilder cacheConfig = new ConfigurationBuilder(); cacheConfig.clustering().cacheMode(CacheMode.INVALIDATION_SYNC) .stateTransfer().fetchInMemoryState(false) .transaction().transactionMode(TransactionMode.TRANSACTIONAL) .transactionManagerLookup(new EmbeddedTransactionManagerLookup()) .lockingMode(lockingMode) .locking().isolationLevel(IsolationLevel.REPEATABLE_READ) .persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(TxInvalidationLockingTest.class.getName()) .build(); return cacheConfig; } public void testPessimisticWriteAcquiresGlobalLock() throws Exception { Future<Void> tx2Future; Cache<Object, Object> cache1 = cache(0, PESSIMISTIC_CACHE); tm(cache1).begin(); try { Object initialValue = cache1.put(KEY, VALUE1); assertNull(initialValue); tx2Future = fork(() -> { AdvancedCache<Object, Object> cache2 = advancedCache(1, PESSIMISTIC_CACHE); tm(cache2).begin(); try { Object value = cache2.put(KEY, VALUE2); assertEquals(VALUE1, value); } finally { tm(cache2).commit(); } }); Thread.sleep(10); assertFalse(tx2Future.isDone()); } finally { tm(cache1).commit(); } tx2Future.get(); assertEquals(VALUE2, cache1.get(KEY)); } public void testPessimisticForceWriteLockAcquiresGlobalLock() throws Exception { Future<Void> tx2Future; AdvancedCache<Object, Object> cache1 = advancedCache(0, PESSIMISTIC_CACHE); tm(cache1).begin(); try { Object initialValue = cache1.withFlags(Flag.FORCE_WRITE_LOCK).get(KEY); assertNull(initialValue); tx2Future = fork(() -> { AdvancedCache<Object, Object> cache2 = advancedCache(1, PESSIMISTIC_CACHE); tm(cache2).begin(); try { Object value = cache2.withFlags(Flag.FORCE_WRITE_LOCK).get(KEY); assertEquals(VALUE1, value); cache2.withFlags(Flag.IGNORE_RETURN_VALUES).put(KEY, VALUE2); } finally { tm(cache2).commit(); } }); Thread.sleep(10); assertFalse(tx2Future.isDone()); cache1.put(KEY, VALUE1); } finally { tm(cache1).commit(); } tx2Future.get(); assertEquals(VALUE2, cache1.get(KEY)); } public void testOptimisticPrepareAcquiresGlobalLock() throws Exception { CheckPoint checkPoint = new CheckPoint(); Future<Void> tx2Future; Cache<Object, Object> cache1 = cache(0, OPTIMISTIC_CACHE); tm(cache1).begin(); EmbeddedTransaction tx1 = null; try { Object initialValue = cache1.put(KEY, VALUE1); assertNull(initialValue); tx1 = (EmbeddedTransaction) tm(cache1).getTransaction(); tx1.runPrepare(); tx2Future = fork(() -> { AdvancedCache<Object, Object> cache2 = advancedCache(1, OPTIMISTIC_CACHE); tm(cache2).begin(); try { assertNull(cache2.get(KEY)); checkPoint.trigger("tx2_read"); cache2.put(KEY, VALUE2); } finally { tm(cache2).commit(); } }); checkPoint.awaitStrict("tx2_read", 10, TimeUnit.SECONDS); Thread.sleep(10); assertFalse(tx2Future.isDone()); } finally { if (tx1 != null) { tx1.runCommit(false); } } // No WriteSkewException tx2Future.get(30, TimeUnit.SECONDS); assertEquals(VALUE2, cache1.get(KEY)); } public void testReadOnlyTransaction() throws Exception { // pessimistic - regular read AdvancedCache<Object, Object> pessimisticCache1 = advancedCache(0, PESSIMISTIC_CACHE); tm(pessimisticCache1).begin(); try { Object initialValue = pessimisticCache1.get(KEY); assertNull(initialValue); } finally { tm(pessimisticCache1).commit(); } // pessimistic - read with write lock tm(pessimisticCache1).begin(); try { Object initialValue = pessimisticCache1.withFlags(Flag.FORCE_WRITE_LOCK).get(KEY); assertNull(initialValue); } finally { tm(pessimisticCache1).commit(); } // optimistic AdvancedCache<Object, Object> optimisticCache1 = advancedCache(0, OPTIMISTIC_CACHE); tm(optimisticCache1).begin(); try { Object initialValue = optimisticCache1.get(KEY); assertNull(initialValue); } finally { tm(optimisticCache1).commit(); } } }
7,110
33.519417
92
java
null
infinispan-main/core/src/test/java/org/infinispan/invalidation/InvalidationPreloadTest.java
package org.infinispan.invalidation; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.DataContainer; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TransportFlags; import org.testng.annotations.Test; /** * Test preloading with an invalidation cache. * * @author Dan Berindei * @since 10.0 */ @Test(groups = "functional", testName = "invalidation.InvalidationPreloadTest") @CleanupAfterMethod public class InvalidationPreloadTest extends MultipleCacheManagersTest { private boolean shared; @Override public Object[] factory() { return new Object[]{ new InvalidationPreloadTest().shared(true).transactional(false), new InvalidationPreloadTest().shared(true).transactional(true), new InvalidationPreloadTest().shared(false).transactional(false), new InvalidationPreloadTest().shared(false).transactional(true), }; } @Override protected String[] parameterNames() { return new String[]{"tx", "shared"}; } @Override protected Object[] parameterValues() { return new Object[]{transactional, shared}; } @Override protected void createCacheManagers() throws Throwable { // The managers are created in the test method } public void testPreloadOnStart() throws PersistenceException { ConfigurationBuilder configuration = new ConfigurationBuilder(); configuration.clustering().cacheMode(CacheMode.INVALIDATION_SYNC); configuration.transaction().transactionMode(transactionMode()); DummyInMemoryStoreConfigurationBuilder dimsConfiguration = configuration.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); dimsConfiguration.storeName(getTestName()).preload(true).shared(shared); EmbeddedCacheManager cm1 = addClusterEnabledCacheManager(TestDataSCI.INSTANCE, configuration, new TransportFlags().withFD(false)); Cache<String, String> c1 = cm1.getCache(); c1.put("k" + 0, "v" + 0); assertKeys(c1); cm1.stop(); EmbeddedCacheManager cm2 = addClusterEnabledCacheManager(TestDataSCI.INSTANCE, configuration, new TransportFlags().withFD(false)); Cache<String, String> c2 = cm2.getCache(); assertKeys(c2); if (shared) { EmbeddedCacheManager cm3 = addClusterEnabledCacheManager(TestDataSCI.INSTANCE, configuration, new TransportFlags().withFD(false)); Cache<String, String> c3 = cm3.getCache(); assertKeys(c3); } } private void assertKeys(Cache<String, String> cache) { DataContainer<String, String> dc = cache.getAdvancedCache().getDataContainer(); assertEquals(1, dc.size()); DummyInMemoryStore cs = TestingUtil.getFirstStore(cache); assertEquals(1, cs.size()); } private InvalidationPreloadTest shared(boolean shared) { this.shared = shared; return this; } }
3,523
33.213592
118
java
null
infinispan-main/core/src/test/java/org/infinispan/invalidation/WriteStoreInvalidationTest.java
package org.infinispan.invalidation; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNull; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; /** * Tests to ensure that invalidation caches operate properly with a shared cache store with various operations. * * @author William Burns * @since 6.0 */ @Test(groups = "functional", testName = "invalidation.WriteStoreInvalidationTest") public class WriteStoreInvalidationTest extends MultipleCacheManagersTest { private static final String key = "key"; private static final String value = "value"; private static final String changedValue = "changed-value"; private static final String cacheName = "inval-write-cache-store"; private boolean transactional; public WriteStoreInvalidationTest transactional(boolean transactional) { this.transactional = transactional; return this; } @Override public Object[] factory() { return new Object[] { new WriteStoreInvalidationTest().transactional(true), new WriteStoreInvalidationTest().transactional(false), }; } @Override protected String[] parameterNames() { return concat(super.parameterNames(), "transactional"); } @Override protected Object[] parameterValues() { return concat(super.parameterValues(), transactional); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cb = getDefaultClusteredCacheConfig(CacheMode.INVALIDATION_SYNC, transactional); cb.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).shared(true) .storeName(getClass().getSimpleName()); createClusteredCaches(2, cacheName, cb); } @Test public void testSharedCacheStoreAfterInvalidation() { // Because the store is shared, statistics are also shared DummyInMemoryStore store0 = TestingUtil.getFirstStore(cache(0, cacheName)); store0.clearStats(); assertNull(cache(0, cacheName).get(key)); assertStoreStats(store0, 1, 0, 0); // Put either loads the previous value or doesn't based on whether the originator is the primary owner // So we use IGNORE_RETURN_VALUES to keep the number of loads stable advancedCache(0, cacheName).withFlags(Flag.IGNORE_RETURN_VALUES).put(key, value); assertStoreStats(store0, 1, 1, 0); assertEquals(value, cache(1, cacheName).get(key)); assertStoreStats(store0, 2, 1, 0); advancedCache(1, cacheName).withFlags(Flag.IGNORE_RETURN_VALUES).put(key, changedValue); assertStoreStats(store0, 2, 2, 0); assertFalse(cache(0, cacheName).getAdvancedCache().getDataContainer().containsKey(key)); assertEquals(changedValue, cache(0, cacheName).get(key)); assertStoreStats(store0, 3, 2, 0); } public void testWriteAndRemoveOnVariousNodes() { Cache<String, String> cache0 = cache(0, cacheName); Cache<String, String> cache1 = cache(0, cacheName); assertNull(cache0.put(key, "foo")); assertEquals("foo", cache1.get(key)); assertEquals("foo", cache1.put(key, "bar")); assertEquals("bar", cache0.get(key)); } private void assertStoreStats(DummyInMemoryStore store, int loads, int writes, int deletes) { assertEquals(loads, store.stats().get("load").intValue()); assertEquals(writes, store.stats().get("write").intValue()); assertEquals(deletes, store.stats().get("delete").intValue()); } }
3,961
35.018182
111
java
null
infinispan-main/core/src/test/java/org/infinispan/invalidation/BaseInvalidationTest.java
package org.infinispan.invalidation; import static org.infinispan.context.Flag.CACHE_MODE_LOCAL; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import jakarta.transaction.RollbackException; import jakarta.transaction.TransactionManager; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.api.mvcc.LockAssert; import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.write.ClearCommand; import org.infinispan.commands.write.InvalidateCommand; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.tx.TransactionImpl; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.remoting.responses.CacheNotFoundResponse; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.rpc.RpcManagerImpl; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.Transport; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.util.ControlledRpcManager; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.locks.LockManager; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @Test(groups = "functional") public abstract class BaseInvalidationTest extends MultipleCacheManagersTest { boolean isSync; protected BaseInvalidationTest() { cleanup = CleanupPhase.AFTER_METHOD; } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder c = getDefaultClusteredCacheConfig(isSync ? CacheMode.INVALIDATION_SYNC : CacheMode.INVALIDATION_ASYNC, false); c.clustering().stateTransfer().timeout(30000) .locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis()); createClusteredCaches(2, "invalidation", c); if (isSync) { c = getDefaultClusteredCacheConfig(CacheMode.INVALIDATION_SYNC, true); c.clustering().stateTransfer().timeout(30000) .transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup()) .transaction().lockingMode(LockingMode.OPTIMISTIC) .locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis()); defineConfigurationOnAllManagers("invalidationTx", c); waitForClusterToForm("invalidationTx"); } } public void testRemove() throws Exception { AdvancedCache<String, String> cache1 = advancedCache(0,"invalidation"); AdvancedCache<String, String> cache2 = advancedCache(1,"invalidation"); cache1.withFlags(CACHE_MODE_LOCAL).put("key", "value"); assertEquals("value", cache1.get("key")); cache2.withFlags(CACHE_MODE_LOCAL).put("key", "value"); assertEquals("value", cache2.get("key")); replListener(cache2).expectAny(); assertEquals("value", cache1.remove("key")); replListener(cache2).waitForRpc(); assertEquals(false, cache2.containsKey("key")); } public void testResurrectEntry() throws Exception { AdvancedCache<String, String> cache1 = advancedCache(0,"invalidation"); AdvancedCache<String, String> cache2 = advancedCache(1,"invalidation"); replListener(cache2).expect(InvalidateCommand.class); cache1.put("key", "value"); replListener(cache2).waitForRpc(); assertEquals("value", cache1.get("key")); assertEquals(null, cache2.get("key")); replListener(cache2).expect(InvalidateCommand.class); cache1.put("key", "newValue"); replListener(cache2).waitForRpc(); assertEquals("newValue", cache1.get("key")); assertEquals(null, cache2.get("key")); replListener(cache2).expect(InvalidateCommand.class); assertEquals("newValue", cache1.remove("key")); replListener(cache2).waitForRpc(); assertEquals(null, cache1.get("key")); assertEquals(null, cache2.get("key")); // Restore locally replListener(cache2).expect(InvalidateCommand.class); cache1.put("key", "value"); replListener(cache2).waitForRpc(); assertEquals("value", cache1.get("key")); assertEquals(null, cache2.get("key")); replListener(cache1).expect(InvalidateCommand.class); cache2.put("key", "value2"); replListener(cache1).waitForRpc(); assertEquals("value2", cache2.get("key")); assertEquals(null, cache1.get("key")); } public void testDeleteNonExistentEntry() throws Exception { if (!isSync) { return; } AdvancedCache<String, String> cache1 = advancedCache(0,"invalidationTx"); AdvancedCache<String, String> cache2 = advancedCache(1,"invalidationTx"); assertNull("Should be null", cache1.get("key")); assertNull("Should be null", cache2.get("key")); replListener(cache2).expect(InvalidateCommand.class); cache1.put("key", "value"); replListener(cache2).waitForRpc(); assertEquals("value", cache1.get("key")); assertNull("Should be null", cache2.get("key")); // OK, here's the real test TransactionManager tm = TestingUtil.getTransactionManager(cache2); tm.begin(); // Remove an entry that doesn't exist in cache2 cache2.remove("key"); replListener(cache1).expect(InvalidateCommand.class); // invalidates always happen outside of a tx tm.commit(); replListener(cache1).waitForRpc(); assertNull(cache1.get("key")); assertNull(cache2.get("key")); } public void testTxSyncUnableToInvalidate() throws Exception { if (!isSync) { return; } AdvancedCache<String, String> cache1 = advancedCache(0,"invalidationTx"); AdvancedCache<String, String> cache2 = advancedCache(1,"invalidationTx"); TransactionManager mgr1 = TestingUtil.getTransactionManager(cache1); TransactionManager mgr2 = TestingUtil.getTransactionManager(cache2); LockManager lm1 = TestingUtil.extractComponent(cache1, LockManager.class); LockManager lm2 = TestingUtil.extractComponent(cache2, LockManager.class); replListener(cache2).expect(InvalidateCommand.class); cache1.put("key", "value"); replListener(cache2).waitForRpc(); assertEquals("value", cache1.get("key")); assertNull(cache2.get("key")); TransactionImpl tx1 = null; mgr1.begin(); try { cache1.put("key", "value2"); tx1 = (TransactionImpl) mgr1.suspend(); // Acquire the key lock for tx1 and hold it replListener(cache2).expect(InvalidateCommand.class); tx1.runPrepare(); replListener(cache2).waitForRpc(); mgr2.begin(); cache2.put("key", "value3"); // tx2 prepare fails because tx1 is holding the key lock replListener(cache1).expect(InvalidateCommand.class); Exceptions.expectException(RollbackException.class, mgr2::commit); replListener(cache2).assertNoRpc(); } finally { if (tx1 != null) { tx1.runCommit(false); } } eventually(() -> !lm1.isLocked("key")); eventually(() -> !lm2.isLocked("key")); LockAssert.assertNoLocks(cache1); LockAssert.assertNoLocks(cache2); } public void testCacheMode() throws Exception { AdvancedCache<String, String> cache1 = advancedCache(0,"invalidation"); RpcManagerImpl rpcManager = (RpcManagerImpl) TestingUtil.extractComponent(cache1, RpcManager.class); Transport origTransport = TestingUtil.extractComponent(cache1, Transport.class); try { Transport mockTransport = mock(Transport.class); rpcManager.setTransport(mockTransport); Address addressOne = mock(Address.class); Address addressTwo = mock(Address.class); List<Address> members = new ArrayList<>(2); members.add(addressOne); members.add(addressTwo); when(mockTransport.getMembers()).thenReturn(members); when(mockTransport.getAddress()).thenReturn(addressOne); when(mockTransport.invokeCommandOnAll(any(), any(), any(), any(), anyLong(), any())) .thenReturn(CompletableFutures.completedNull()); cache1.put("k", "v"); } finally { if (rpcManager != null) rpcManager.setTransport(origTransport); } } public void testPutIfAbsent() { AdvancedCache<String, String> cache1 = advancedCache(0,"invalidation"); AdvancedCache<String, String> cache2 = advancedCache(1,"invalidation"); String putPrevious = cache2.withFlags(CACHE_MODE_LOCAL).put("key", "value"); assertNull(putPrevious); assertEquals("value", cache2.get("key")); assertNull(cache1.get("key")); replListener(cache2).expect(InvalidateCommand.class); String putIfAbsentPrevious = cache1.putIfAbsent("key", "value"); assertNull(putIfAbsentPrevious); replListener(cache2).waitForRpc(); assertEquals("value", cache1.get("key")); String value = cache2.get("key"); assertNull(value); assertNull(cache2.withFlags(CACHE_MODE_LOCAL).put("key", "value2")); assertEquals("value", cache1.get("key")); assertEquals("value2", cache2.get("key")); cache1.putIfAbsent("key", "value3"); assertEquals("value", cache1.get("key")); assertEquals("value2", cache2.get("key")); // should not invalidate cache2!! } public void testRemoveIfPresent() { AdvancedCache<String, String> cache1 = advancedCache(0,"invalidation"); AdvancedCache<String, String> cache2 = advancedCache(1,"invalidation"); cache1.withFlags(CACHE_MODE_LOCAL).put("key", "value1"); cache2.withFlags(CACHE_MODE_LOCAL).put("key", "value2"); assertEquals("value1", cache1.get("key")); assertEquals("value2", cache2.get("key")); assertFalse(cache1.remove("key", "value")); assertEquals("Should not remove", "value1", cache1.get("key")); assertEquals("Should not evict", "value2", cache2.get("key")); replListener(cache2).expect(InvalidateCommand.class); cache1.remove("key", "value1"); replListener(cache2).waitForRpc(); assertNull(cache1.get("key")); assertNull(cache2.get("key")); } public void testClear() { AdvancedCache<String, String> cache1 = advancedCache(0,"invalidation"); AdvancedCache<String, String> cache2 = advancedCache(1,"invalidation"); cache1.withFlags(CACHE_MODE_LOCAL).put("key", "value1"); cache2.withFlags(CACHE_MODE_LOCAL).put("key", "value2"); assertEquals("value1", cache1.get("key")); assertEquals("value2", cache2.get("key")); replListener(cache2).expect(ClearCommand.class); cache1.clear(); replListener(cache2).waitForRpc(); assertNull(cache1.get("key")); assertNull(cache2.get("key")); } public void testReplace() { AdvancedCache<String, String> cache1 = advancedCache(0,"invalidation"); AdvancedCache<String, String> cache2 = advancedCache(1,"invalidation"); cache2.withFlags(CACHE_MODE_LOCAL).put("key", "value2"); assertNull(cache1.get("key")); assertEquals("value2", cache2.get("key")); assertNull(cache1.replace("key", "value1")); // should do nothing since there is nothing to replace on cache1 assertNull(cache1.get("key")); assertEquals("value2", cache2.get("key")); assertNull(cache1.withFlags(CACHE_MODE_LOCAL).put("key", "valueN")); replListener(cache2).expect(InvalidateCommand.class); cache1.replace("key", "value1"); replListener(cache2).waitForRpc(); assertEquals("value1", cache1.get("key")); assertNull(cache2.get("key")); } public void testReplaceWithOldVal() { AdvancedCache<String, String> cache1 = advancedCache(0,"invalidation"); AdvancedCache<String, String> cache2 = advancedCache(1,"invalidation"); cache2.withFlags(CACHE_MODE_LOCAL).put("key", "value2"); assertNull(cache1.get("key")); assertEquals("value2", cache2.get("key")); assertFalse( cache1.replace("key", "valueOld", "value1")); // should do nothing since there is nothing to replace on cache1 assertNull(cache1.get("key")); assertEquals("value2", cache2.get("key")); assertNull(cache1.withFlags(CACHE_MODE_LOCAL).put("key", "valueN")); assertFalse( cache1.replace("key", "valueOld", "value1")); // should do nothing since there is nothing to replace on cache1 assertEquals("valueN", cache1.get("key")); assertEquals("value2", cache2.get("key")); replListener(cache2).expect(InvalidateCommand.class); assertTrue(cache1.replace("key", "valueN", "value1")); replListener(cache2).waitForRpc(); assertEquals("value1", cache1.get("key")); assertNull(cache2.get("key")); } public void testLocalOnlyClear() { AdvancedCache<String, String> cache1 = advancedCache(0,"invalidation"); AdvancedCache<String, String> cache2 = advancedCache(1,"invalidation"); cache1.withFlags(CACHE_MODE_LOCAL).put("key", "value1"); cache2.withFlags(CACHE_MODE_LOCAL).put("key", "value2"); assertEquals("value1", cache1.get("key")); assertEquals("value2", cache2.get("key")); cache1.withFlags(CACHE_MODE_LOCAL).clear(); assertNull(cache1.get("key")); assertNotNull(cache2.get("key")); assertEquals("value2", cache2.get("key")); } public void testPutForExternalRead() throws Exception { AdvancedCache<String, String> cache1 = advancedCache(0,"invalidation"); AdvancedCache<String, String> cache2 = advancedCache(1, "invalidation"); cache1.putForExternalRead("key", "value1"); Thread.sleep(500); // sleep so that async invalidation (result of PFER) is propagated cache2.putForExternalRead("key", "value2"); Thread.sleep(500); // sleep so that async invalidation (result of PFER) is propagated assertNotNull(cache1.get("key")); assertEquals("value1", cache1.get("key")); assertNotNull(cache2.get("key")); assertEquals("value2", cache2.get("key")); } @DataProvider(name = "tx") public Object[][] tx() { if (isSync) { return new Object[][]{{false}, {true}}; } else { return new Object[][]{{false}}; } } @Test(dataProvider = "tx") public void testLeaveDuringInvalidation(boolean tx) throws Exception { Cache<Object, Object> c0 = cache(0, tx ? "invalidationTx" : "invalidation"); ControlledRpcManager controlledRpcManager = ControlledRpcManager.replaceRpcManager(c0); TestingUtil.replaceComponent(c0, RpcManager.class, controlledRpcManager, true); Future<Object> future = fork(() -> c0.put("k1", "v1")); if (tx) { controlledRpcManager.expectCommand(PrepareCommand.class) .send() .expectResponse(address(1)).replace(CacheNotFoundResponse.INSTANCE) .finish(); controlledRpcManager.expectCommand(CommitCommand.class) .send() .expectResponse(address(1)).replace(CacheNotFoundResponse.INSTANCE) .finish(); controlledRpcManager.expectCommand(TxCompletionNotificationCommand.class) .send(); } else if (isSync) { controlledRpcManager.expectCommand(InvalidateCommand.class) .send() .expectResponse(address(1)).replace(CacheNotFoundResponse.INSTANCE) .finish(); } else { controlledRpcManager.expectCommand(InvalidateCommand.class) .send(); } future.get(10, TimeUnit.SECONDS); controlledRpcManager.stopBlocking(); } }
16,676
38.425532
138
java
null
infinispan-main/core/src/test/java/org/infinispan/invalidation/NonTxInvalidationLockingTest.java
package org.infinispan.invalidation; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.commands.write.InvalidateCommand; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.transaction.TransactionMode; import org.infinispan.util.ControlledRpcManager; import org.testng.annotations.Test; /** * Test that non-tx locking does not cause deadlocks in sync invalidation caches. * * <p>See ISPN-12489</p> * * @author Dan Berindei */ @Test(groups = "functional", testName = "invalidation.NonTxInvalidationLockingTest") public class NonTxInvalidationLockingTest extends MultipleCacheManagersTest { private static final String KEY = "key"; private static final String VALUE1 = "value1"; private static final Object VALUE2 = "value2"; private static final String CACHE = "nontx"; @Override protected void createCacheManagers() throws Throwable { addClusterEnabledCacheManager(); addClusterEnabledCacheManager(); defineCache(CACHE); waitForClusterToForm(CACHE); } private void defineCache(String cacheName) { ConfigurationBuilder config = buildConfig(); manager(0).defineConfiguration(cacheName, config.build()); manager(1).defineConfiguration(cacheName, config.build()); } private ConfigurationBuilder buildConfig() { ConfigurationBuilder cacheConfig = new ConfigurationBuilder(); cacheConfig.clustering().cacheMode(CacheMode.INVALIDATION_SYNC) .stateTransfer().fetchInMemoryState(false) .transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL) .persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(NonTxInvalidationLockingTest.class.getName()) .build(); return cacheConfig; } public void testConcurrentWritesFromDifferentNodes() throws Exception { Cache<Object, Object> cache1 = cache(0, CACHE); ControlledRpcManager rpc1 = ControlledRpcManager.replaceRpcManager(cache1); Cache<Object, Object> cache2 = cache(1, CACHE); ControlledRpcManager rpc2 = ControlledRpcManager.replaceRpcManager(cache2); CompletableFuture<ControlledRpcManager.BlockedRequest<InvalidateCommand>> invalidate1 = rpc1.expectCommandAsync(InvalidateCommand.class); CompletableFuture<Object> put1 = cache1.putAsync(KEY, VALUE1); CompletableFuture<ControlledRpcManager.BlockedRequest<InvalidateCommand>> invalidate2 = rpc2.expectCommandAsync(InvalidateCommand.class); CompletableFuture<Object> put2 = cache2.putAsync(KEY, VALUE2); ControlledRpcManager.SentRequest sentInvalidate1 = invalidate1.join().send(); ControlledRpcManager.SentRequest sentInvalidate2 = invalidate2.join().send(); sentInvalidate1.expectAllResponses().receive(); sentInvalidate2.expectAllResponses().receive(); put1.get(10, TimeUnit.SECONDS); put2.get(10, TimeUnit.SECONDS); assertEquals(VALUE1, cache1.get(KEY)); assertEquals(VALUE2, cache2.get(KEY)); } }
3,407
38.172414
93
java
null
infinispan-main/core/src/test/java/org/infinispan/invalidation/AsyncInvalidationTest.java
package org.infinispan.invalidation; import org.testng.annotations.Test; @Test(groups = {"functional"}, testName = "invalidation.AsyncInvalidationTest") public class AsyncInvalidationTest extends BaseInvalidationTest { public AsyncInvalidationTest() { isSync = false; } }
286
25.090909
79
java
null
infinispan-main/core/src/test/java/org/infinispan/invalidation/ClusteredCacheLoaderInvalidationTest.java
package org.infinispan.invalidation; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNull; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ClusterLoaderConfigurationBuilder; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * Tests to ensure that invalidation caches with a cluster cache loader properly retrieve the value from the remote * cache * * @author William burns * @since 6.0 */ @Test(groups = "functional", testName = "invalidation.ClusteredCacheLoaderInvalidationTest") public class ClusteredCacheLoaderInvalidationTest extends MultipleCacheManagersTest { private static final String key = "key"; private static final String value = "value"; private static final String changedValue = "changed-value"; private static final String cacheName = "inval-write-cache-store"; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cb = getDefaultClusteredCacheConfig(CacheMode.INVALIDATION_SYNC, false); cb.persistence().addStore(ClusterLoaderConfigurationBuilder.class) .segmented(false); createClusteredCaches(2, cacheName, cb); } @Test public void testCacheLoaderBeforeAfterInvalidation() { assertNull(cache(0, cacheName).get(key)); cache(0, cacheName).put(key, value); assertFalse("Invalidation should not contain the value in memory", cache(1, cacheName).getAdvancedCache().getDataContainer().containsKey(key)); assertEquals(value, cache(1, cacheName).get(key)); cache(1, cacheName).put(key, changedValue); assertFalse("Invalidation should not contain the value in memory after other node put", cache(0, cacheName).getAdvancedCache().getDataContainer().containsKey(key)); assertEquals(changedValue, cache(0, cacheName).get(key)); } }
2,083
36.890909
115
java
null
infinispan-main/core/src/test/java/org/infinispan/invalidation/InvalidationExceptionTest.java
package org.infinispan.invalidation; import org.infinispan.AdvancedCache; import org.infinispan.commons.marshall.MarshallingException; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.replication.ReplicationExceptionTest; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * Test to verify how the invalidation works under exceptional circumstances. * * @author Galder Zamarreño * @since 4.2 */ @Test(groups = "functional", testName = "invalidation.InvalidationExceptionTest") public class InvalidationExceptionTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder invalidAsync = getDefaultClusteredCacheConfig( CacheMode.INVALIDATION_ASYNC, false); createClusteredCaches(2, "invalidAsync", invalidAsync); } @Test(expectedExceptions = MarshallingException.class) public void testNonSerializableAsyncInvalid() { String cacheName = "invalidAsync"; AdvancedCache cache1 = cache(0, cacheName).getAdvancedCache(); cache1.put(new ReplicationExceptionTest.ContainerData(), "test-" + cacheName); } }
1,268
36.323529
84
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/PreloadWithAsyncStoreTest.java
package org.infinispan.persistence; import static org.infinispan.transaction.TransactionMode.NON_TRANSACTIONAL; import static org.infinispan.transaction.TransactionMode.TRANSACTIONAL; 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.concurrent.atomic.AtomicInteger; import org.infinispan.Cache; import org.infinispan.commands.VisitableCommand; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.InternalCacheValue; import org.infinispan.context.InvocationContext; import org.infinispan.interceptors.BaseAsyncInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.persistence.support.WaitNonBlockingStore; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.Test; /** * @author Pedro Ruivo * @since 5.2 */ @Test(groups = "functional", testName = "persistence.PreloadWithAsyncStoreTest") public class PreloadWithAsyncStoreTest extends SingleCacheManagerTest { private static final Object[] KEYS = new Object[]{"key_1", "key_2", "key_3", "key_4"}; private static final Object[] VALUES = new Object[]{"value_1", "value_2", "value_3", "value_4"}; public void testtPreloadWithNonTransactionalCache() throws Exception { doTest(CacheType.NO_TRANSACTIONAL); } public void testtPreloadWithTransactionalUsingSynchronizationCache() throws Exception { doTest(CacheType.TRANSACTIONAL_SYNCHRONIZATION); } public void testPreloadWithTransactionalUsingXACache() throws Exception { doTest(CacheType.TRANSACTIONAL_XA); } public void testPreloadWithTransactionalUsingXAAndRecoveryCache() throws Exception { doTest(CacheType.TRANSACTIONAL_XA_RECOVERY); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(); for (CacheType cacheType : CacheType.values()) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .preload(true) .storeName(this.getClass().getName()).async().enable(); builder.transaction().transactionMode(cacheType.transactionMode).useSynchronization(cacheType.useSynchronization) .recovery().enabled(cacheType.useRecovery); builder.customInterceptors().addInterceptor().index(0).interceptor(new ExceptionTrackerInterceptor()); cm.defineConfiguration(cacheType.cacheName, builder.build()); } return cm; } protected void doTest(CacheType cacheType) throws Exception { final Cache<Object, Object> cache = cacheManager.getCache(cacheType.cacheName); ExceptionTrackerInterceptor interceptor = getInterceptor(cache); assertTrue("Preload should be enabled.", cache.getCacheConfiguration().persistence().preload()); assertTrue("Async Store should be enabled.", cache.getCacheConfiguration().persistence().usingAsyncStore()); WaitNonBlockingStore<Object, Object> store = TestingUtil.getFirstStoreWait(cache); assertNotInCacheAndStore(cache, store, KEYS); for (int i = 0; i < KEYS.length; ++i) { cache.put(KEYS[i], VALUES[i]); } for (int i = 1; i < KEYS.length; i++) { assertInCacheAndStore(cache, store, KEYS[i], VALUES[i]); } DataContainer<Object, Object> dataContainer = cache.getAdvancedCache().getDataContainer(); assertEquals("Wrong number of keys in data container after puts.", KEYS.length, dataContainer.size()); assertEquals("Some exceptions has been caught during the puts.", 0, interceptor.exceptionsCaught.get()); cache.stop(); assertEquals("Expected empty data container after stop.", 0, dataContainer.size()); assertEquals("Some exceptions has been caught during the stop.", 0, interceptor.exceptionsCaught.get()); cache.start(); assertTrue("Preload should be enabled after restart.", cache.getCacheConfiguration().persistence().preload()); assertTrue("Async Store should be enabled after restart.", cache.getCacheConfiguration().persistence().usingAsyncStore()); dataContainer = cache.getAdvancedCache().getDataContainer(); assertEquals("Wrong number of keys in data container after preload.", KEYS.length, dataContainer.size()); assertEquals("Some exceptions has been caught during the preload.", 0, interceptor.exceptionsCaught.get()); // Re-retrieve since the old reference might not be usable store = TestingUtil.getStoreWait(cache, 0, false); for (int i = 1; i < KEYS.length; i++) { assertInCacheAndStore(cache, store, KEYS[i], VALUES[i]); } } private void assertInCacheAndStore(Cache<Object, Object> cache, WaitNonBlockingStore<Object, Object> loader, Object key, Object value) throws PersistenceException { InternalCacheValue<Object> se = cache.getAdvancedCache().getDataContainer().get(key).toInternalCacheValue(); assertStoredEntry(se.getValue(), value, "Cache", key); MarshallableEntry<Object, Object> me = loader.loadEntry(key); assertStoredEntry(me.getValue(), value, "Store", key); } private void assertStoredEntry(Object value, Object expectedValue, String src, Object key) { assertNotNull(src + " entry for key " + key + " should NOT be null", value); assertEquals(src + " should contain value " + expectedValue + " under key " + key + " but was " + value, expectedValue, value); } private <T> void assertNotInCacheAndStore(Cache<Object, Object> cache, WaitNonBlockingStore<Object, Object> store, T... keys) throws PersistenceException { for (Object key : keys) { assertFalse("Cache should not contain key " + key, cache.getAdvancedCache().getDataContainer().containsKey(key)); assertFalse("Store should not contain key " + key, store.contains(key)); } } private ExceptionTrackerInterceptor getInterceptor(Cache<Object, Object> cache) { return cache.getAdvancedCache().getAsyncInterceptorChain() .findInterceptorWithClass(ExceptionTrackerInterceptor.class); } private enum CacheType { NO_TRANSACTIONAL("NO_TX"), TRANSACTIONAL_SYNCHRONIZATION(TRANSACTIONAL, "TX_SYNC", true, false), TRANSACTIONAL_XA(TRANSACTIONAL, "TX_XA", false, false), TRANSACTIONAL_XA_RECOVERY(TRANSACTIONAL, "TX_XA_RECOVERY", false, true); final TransactionMode transactionMode; final String cacheName; final boolean useSynchronization; final boolean useRecovery; CacheType(TransactionMode transactionMode, String cacheName, boolean useSynchronization, boolean useRecovery) { this.transactionMode = transactionMode; this.cacheName = cacheName; this.useSynchronization = useSynchronization; this.useRecovery = useRecovery; } CacheType(String cacheName) { //no tx cache. the boolean parameters are ignored. this(NON_TRANSACTIONAL, cacheName, false, false); } } static class ExceptionTrackerInterceptor extends BaseAsyncInterceptor { private AtomicInteger exceptionsCaught = new AtomicInteger(); @Override public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable { return invokeNextAndExceptionally(ctx, command, (rCtx, rCommand, throwable) -> { exceptionsCaught.incrementAndGet(); throw throwable; }); } } }
8,138
44.724719
167
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/IgnoreModificationsStoreTest.java
package org.infinispan.persistence; import java.io.IOException; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.commons.time.ControlledTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.AssertJUnit; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * Test read only store, * i.e. test proper functionality of setting ignoreModifications(true) for cache store. * * @author Tomas Sykora */ @Test(testName = "persistence.IgnoreModificationsStoreTest", groups = "functional", sequential = true) @CleanupAfterMethod public class IgnoreModificationsStoreTest extends SingleCacheManagerTest { private static final long EXPIRATION_TIME = 1_000_000; DummyInMemoryStore store; ControlledTimeService timeService = new ControlledTimeService(); boolean expiration; IgnoreModificationsStoreTest expiration(boolean expiration) { this.expiration = expiration; return this; } @Factory public Object[] factory() { return new Object[]{ new IgnoreModificationsStoreTest().expiration(false), new IgnoreModificationsStoreTest().expiration(true) }; } @Override protected String parameters() { return "[" + expiration + "]"; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(false); if (expiration) { cfg.expiration().lifespan(EXPIRATION_TIME, TimeUnit.MILLISECONDS); } cfg .persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) // Disable segmentation so we can more easily add/remove entries manually .segmented(false) // This way we can write to the store still .storeName(IgnoreModificationsStoreTest.class.getName()) .ignoreModifications(true); EmbeddedCacheManager ecm = TestCacheManagerFactory.createCacheManager(cfg); TestingUtil.replaceComponent(ecm, TimeService.class, timeService, true); return ecm; } @Override protected void setup() throws Exception { super.setup(); store = TestingUtil.getFirstStore(cache); } public void testReadOnlyCacheStore() throws PersistenceException, IOException, InterruptedException { String storeDataName = IgnoreModificationsStoreTest.class.getName() + "_" + cache.getName(); Map<Object, byte[]> storeMap = DummyInMemoryStore.getStoreDataForName(storeDataName).get(0); DummyInMemoryStore dummyInMemoryStore = (DummyInMemoryStore) TestingUtil.getFirstStoreWait(cache).delegate(); byte[] storedBytes = dummyInMemoryStore.valueToStoredBytes("v1"); storeMap.put("k1", storedBytes); AssertJUnit.assertEquals("v1", cache.get("k1")); TestingUtil.writeToAllStores("k2", "v2", cache); AssertJUnit.assertTrue(store.contains("k1")); AssertJUnit.assertFalse(store.contains("k2")); // put into cache but not into read only store cache.put("k2", "v2"); AssertJUnit.assertEquals("v2", cache.get("k2")); AssertJUnit.assertTrue(store.contains("k1")); AssertJUnit.assertFalse(store.contains("k2")); AssertJUnit.assertFalse(TestingUtil.deleteFromAllStores("k1", cache)); AssertJUnit.assertFalse(TestingUtil.deleteFromAllStores("k2", cache)); AssertJUnit.assertFalse(TestingUtil.deleteFromAllStores("k3", cache)); AssertJUnit.assertEquals("v1", cache.get("k1")); AssertJUnit.assertEquals("v2", cache.get("k2")); cache.remove("k1"); cache.remove("k2"); AssertJUnit.assertNotNull(cache.get("k1")); AssertJUnit.assertNull(cache.get("k2")); // lastly check what happens if entry is expired but load is called if (expiration) { dummyInMemoryStore = (DummyInMemoryStore) TestingUtil.getFirstStoreWait(cache).delegate(); storedBytes = dummyInMemoryStore.valueToStoredBytes("v1-new"); storeMap.put("k1", storedBytes); AssertJUnit.assertEquals("v1", cache.get("k1")); timeService.advance(EXPIRATION_TIME + 1); AssertJUnit.assertEquals("v1-new", cache.get("k1")); } } }
4,771
36.28125
115
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/ClusteredTxConditionalCommandPassivationTest.java
package org.infinispan.persistence; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.distribution.Ownership; import org.infinispan.test.fwk.InCacheMode; import org.testng.annotations.Test; /** * Tests if the conditional commands correctly fetch the value from cache loader even with the skip cache load/store * flags. * <p/> * The configuration used is a tx distributed cache with passivation. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "functional", testName = "persistence.ClusteredTxConditionalCommandPassivationTest") @InCacheMode({CacheMode.DIST_SYNC}) public class ClusteredTxConditionalCommandPassivationTest extends ClusteredConditionalCommandTest { public ClusteredTxConditionalCommandPassivationTest() { super(true, true); } @Override protected <K, V> void assertLoadAfterOperation(CacheHelper<K, V> cacheHelper, ConditionalOperation operation, Ownership ownership, boolean skipLoad) { switch (ownership) { case PRIMARY: assertLoad(cacheHelper, skipLoad ? 0 : 1, 0, 0); break; case BACKUP: assertLoad(cacheHelper, 0, skipLoad ? 0 : 1, 0); break; case NON_OWNER: if (skipLoad) { assertLoad(cacheHelper, 0, 0, 0); } else { // The entry is loaded into DC upon the initial value retrieval (ClusteredGetCommand). // It is loaded on primary, but if the response to the retrieval does not // come soon enough, staggered logic sends second retrieval to backup owner, so it's possible // that both owners load once. // It is also possible that the primary does not get the request while backup handles the read // - then we won't see any load on primary owner. long primaryLoads = cacheHelper.loads(Ownership.PRIMARY); assertTrue("primary owner load: " + primaryLoads, primaryLoads <= 1); long backupLoads = cacheHelper.loads(Ownership.BACKUP); assertTrue("backup owner load: " + backupLoads, backupLoads <= 1); assertTrue("loads: primary=" + primaryLoads + ", backup=" + backupLoads, primaryLoads + backupLoads >= 1); assertEquals("non owner load", 0, cacheHelper.loads(Ownership.NON_OWNER)); } break; } } }
2,513
41.610169
153
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/WriteBehindFaultToleranceTest.java
package org.infinispan.persistence; import static org.infinispan.util.concurrent.CompletionStages.join; 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.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.infinispan.Cache; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.persistence.manager.PersistenceManagerImpl; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.NonBlockingStore; import org.infinispan.persistence.spi.StoreUnavailableException; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @CleanupAfterMethod @Test(testName = "persistence.WriteBehindFaultToleranceTest", groups = "functional") public class WriteBehindFaultToleranceTest extends SingleCacheManagerTest { private static final int AVAILABILITY_INTERVAL = 10; private Cache<Object, Object> createManagerAndGetCache(boolean failSilently, int queueSize) { GlobalConfigurationBuilder globalConfiguration = new GlobalConfigurationBuilder(); ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(false); config.persistence().availabilityInterval(AVAILABILITY_INTERVAL) .addStore(DummyInMemoryStoreConfigurationBuilder.class) .async().enable().modificationQueueSize(queueSize).failSilently(failSilently); cacheManager = TestCacheManagerFactory.createCacheManager(globalConfiguration, config); return cacheManager.getCache(); } public void testBlockingOnStoreAvailabilityChange() throws InterruptedException, ExecutionException, TimeoutException { Cache<Object, Object> cache = createManagerAndGetCache(false, 1); PollingPersistenceManager pm = new PollingPersistenceManager(); PersistenceManager oldPersistenceManager = TestingUtil.replaceComponent(cache, PersistenceManager.class, pm, true); oldPersistenceManager.stop(); NonBlockingStore<?, ?> asyncStore = TestingUtil.getStore(cache, 0, false); DummyInMemoryStore dims = TestingUtil.getStore(cache, 0, true); dims.setAvailable(true); cache.put(1, 1); eventually(() -> dims.loadEntry(1) != null); assertEquals(1, dims.size()); dims.setAvailable(false); assertFalse(dims.checkAvailable()); int pollCount = pm.pollCount.get(); // Wait until the store's availability has been checked before asserting that the pm is still available eventually(() -> pm.pollCount.get() > pollCount); // PM & AsyncWriter should still be available as the async modification queue is not full assertTrue(join(asyncStore.isAvailable())); assertNotNull(TestingUtil.extractField((asyncStore), "delegateAvailableFuture")); assertTrue(pm.isAvailable()); Future<Void> f = fork(() -> { // Add entries >= modification queue size so that store is no longer available // The async store creates 2 batches: // 1. modification 1 returns immediately, but stays in the queue until DIMS becomes available again // 2. modifications 2-5 block in the async store because the modification queue is full // The async store waits for the DIMS to become available before completing the 1st batch // After PersistenceManagerImpl sees the store is unavailable, it becomes unavailable itself // and later writes never reach the async store (until PMI becomes available again). cache.putAll(intMap(0, 5)); }); assertEquals(1, dims.size()); eventually(() -> !pm.isAvailable()); // PM and writer should not be available as the async modification queue is now oversubscribed and the delegate is still unavailable Exceptions.expectException(StoreUnavailableException.class, () -> cache.putAll(intMap(10, 20))); assertEquals(1, dims.size()); // Make the delegate available and ensure that the initially queued modifications exist in the store dims.setAvailable(true); assertTrue(join(asyncStore.isAvailable())); eventually(pm::isAvailable); f.get(10, TimeUnit.SECONDS); // Now that PMI is available again, a new write will succeed cache.putAll(intMap(5, 10)); // Ensure that the putAll(10..20) operation truly failed eventuallyEquals(IntSets.immutableRangeSet(10), dims::keySet); } private Map<Integer, Integer> intMap(int start, int end) { return IntStream.range(start, end).boxed().collect(Collectors.toMap(Function.identity(), Function.identity())); } public void testWritesFailSilentlyWhenConfigured() { Cache<Object, Object> cache = createManagerAndGetCache(true, 1); DummyInMemoryStore dims = TestingUtil.getStore(cache, 0, true); assertTrue(dims.checkAvailable()); cache.put(1, 1); eventually(() -> dims.loadEntry(1) != null); assertEquals(1, dims.size()); dims.setAvailable(false); assertFalse(dims.checkAvailable()); cache.put(1, 2); // Should fail on the store, but complete in-memory TestingUtil.sleepThread(1000); // Sleep to ensure async write is attempted dims.setAvailable(true); MarshallableEntry<?, ?> entry = dims.loadEntry(1); assertNotNull(entry); assertEquals(1, entry.getValue()); assertEquals(2, cache.get(1)); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { // Manager is created later return null; } @Override protected void setup() throws Exception { // Manager is created later } static class PollingPersistenceManager extends PersistenceManagerImpl { final AtomicInteger pollCount = new AtomicInteger(); @Override protected CompletionStage<Void> pollStoreAvailability() { pollCount.incrementAndGet(); return super.pollStoreAvailability(); } } }
6,942
45.286667
138
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/ParallelIterationTest.java
package org.infinispan.persistence; 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.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.metadata.Metadata; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.support.WaitNonBlockingStore; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.WithinThreadExecutor; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.subscribers.TestSubscriber; /** * @author Mircea Markus * @since 6.0 */ @Test (groups = "functional", testName = "persistence.ParallelIterationTest") public abstract class ParallelIterationTest extends SingleCacheManagerTest { private static final int NUM_THREADS = 10; private static final int NUM_ENTRIES = 200; protected WaitNonBlockingStore<Object, Object> store; protected ExecutorService executor; protected IntSet allSegments; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cb = getDefaultStandaloneCacheConfig(false); configurePersistence(cb); GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); global.globalState().persistentLocation(CommonsTestingUtil.tmpDirectory(this.getClass())); global.serialization().addContextInitializer(getSerializationContextInitializer()); EmbeddedCacheManager manager = TestCacheManagerFactory.createCacheManager(global, cb); store = TestingUtil.getFirstStoreWait(manager.getCache()); executor = testExecutor(); allSegments = IntSets.immutableRangeSet(manager.getCache().getCacheConfiguration().clustering().hash().numSegments()); return manager; } protected abstract void configurePersistence(ConfigurationBuilder cb); protected SerializationContextInitializer getSerializationContextInitializer() { return TestDataSCI.INSTANCE; } public void testParallelIterationWithValue() { runIterationTest(executor, true); } public void testSequentialIterationWithValue() { runIterationTest(new WithinThreadExecutor(), true); } public void testParallelIterationWithoutValue() { runIterationTest(executor, false); } public void testSequentialIterationWithoutValue() { runIterationTest(new WithinThreadExecutor(), false); } private void runIterationTest(Executor executor, final boolean fetchValues) { final ConcurrentMap<Integer, Integer> entries = new ConcurrentHashMap<>(); final ConcurrentMap<Integer, Metadata> metadata = new ConcurrentHashMap<>(); final AtomicBoolean sameKeyMultipleTimes = new AtomicBoolean(); assertEquals(store.sizeWait(allSegments), 0); insertData(); Flowable<MarshallableEntry<Object, Object>> flowable = Flowable.fromPublisher( store.publishEntries(allSegments, null, fetchValues)); flowable = flowable.doOnNext(me -> { Integer key = unwrapKey(me.getKey()); if (fetchValues) { // Note: MarshalledEntryImpl.getValue() fails with NPE when it's got null valueBytes, // that's why we must not call this when values are not retrieved Integer existing = entries.put(key, unwrapValue(me.getValue())); if (existing != null) { log.warnf("Already a value present for key %s: %s", key, existing); sameKeyMultipleTimes.set(true); } } if (me.getMetadata() != null) { log.tracef("For key %d found metadata %s", key, me.getMetadata()); Metadata prevMetadata = metadata.put(key, me.getMetadata()); if (prevMetadata != null) { log.warnf("Already a metadata present for key %s: %s", key, prevMetadata); sameKeyMultipleTimes.set(true); } } else { log.tracef("No metadata found for key %d", key); } }); TestSubscriber<MarshallableEntry<Object, Object>> subscriber = TestSubscriber.create(0); flowable.subscribe(subscriber); int batchsize = 10; // Request all elements except the last 10 - do this across different threads for (int i = 0; i < NUM_ENTRIES / batchsize - 1; i++) { // Now request all the entries on different threads - just to see if the publisher can handle it executor.execute(() -> subscriber.request(batchsize)); } // We should receive all of those elements now subscriber.awaitCount(NUM_ENTRIES - batchsize); // Now request on the main thread - which should guarantee requests from different threads // We only have 10 elements left, but request 1 more just because and we can verify we only got 10 subscriber.request(batchsize + 1); subscriber.awaitDone(10, TimeUnit.SECONDS); subscriber.assertNoErrors(); assertEquals(NUM_ENTRIES, subscriber.values().size()); assertFalse(sameKeyMultipleTimes.get()); for (int i = 0; i < NUM_ENTRIES; i++) { if (fetchValues) { assertEquals(entries.get(i), (Integer) i, "For key " + i); } else { assertNull(entries.get(i), "For key " + i); } if (hasMetadata(fetchValues, i)) { assertNotNull(metadata.get(i), "For key " + i); assertEquals(metadata.get(i).lifespan(), lifespan(i), "For key " + i); assertEquals(metadata.get(i).maxIdle(), maxIdle(i), "For key " + i); } else { assertMetadataEmpty(metadata.get(i), i); } } } private void insertData() { for (int i = 0; i < NUM_ENTRIES; i++) { long now = System.currentTimeMillis(); Metadata metadata = insertMetadata(i) ? TestingUtil.metadata(lifespan(i), maxIdle(i)) : null; MarshallableEntry me = MarshalledEntryUtil.create(wrapKey(i), wrapValue(i, i), metadata, now, now, cache); store.write(me); } } protected void assertMetadataEmpty(Metadata metadata, Object key) { assertNull(metadata, "For key " + key); } protected boolean insertMetadata(int i) { return i % 2 == 0; } protected boolean hasMetadata(boolean fetchValues, int i) { return insertMetadata(i); } protected long lifespan(int i) { return 1000L * (i + 1000); } protected long maxIdle(int i) { return 10000L * (i + 1000); } protected Object wrapKey(int key) { return key; } protected Integer unwrapKey(Object key) { return (Integer) key; } protected Object wrapValue(int key, int value) { return value; } protected Integer unwrapValue(Object value) { return (Integer) value; } }
7,705
36.77451
124
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/LocalModePassivationTest.java
package org.infinispan.persistence; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.infinispan.AdvancedCache; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.context.Flag; import org.infinispan.encoding.DataConversion; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.TransactionMode; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; /** * Test if keys are properly passivated and reloaded in local mode (to ensure fix for ISPN-2712 did no break local mode). * * @author anistor@redhat.com * @since 5.2 */ @Test(groups = "functional", testName = "persistence.LocalModePassivationTest") @CleanupAfterMethod public class LocalModePassivationTest extends SingleCacheManagerTest { private final boolean passivationEnabled; protected LocalModePassivationTest() { passivationEnabled = true; } protected LocalModePassivationTest(boolean passivationEnabled) { this.passivationEnabled = passivationEnabled; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.LOCAL, true, true); builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL).lockingMode(LockingMode.PESSIMISTIC) .transactionManagerLookup(new EmbeddedTransactionManagerLookup()) .memory().storageType(StorageType.BINARY).size(150) .locking().useLockStriping(false).isolationLevel(IsolationLevel.READ_COMMITTED) .persistence() .passivation(passivationEnabled) .addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(getClass().getName()) .fetchPersistentState(true) .ignoreModifications(false) .preload(false) .purgeOnStartup(false); return TestCacheManagerFactory.createCacheManager(builder); } public void testStoreAndLoad() throws Exception { final int numKeys = 300; for (int i = 0; i < numKeys; i++) { cache().put(i, i); } int keysInDataContainer = cache().getAdvancedCache().getDataContainer().size(); assertTrue(keysInDataContainer != numKeys); // some keys got evicted DummyInMemoryStore store = TestingUtil.getFirstStore(cache()); long keysInCacheStore = store.size(); if (passivationEnabled) { assertEquals(numKeys, keysInDataContainer + keysInCacheStore); } else { assertEquals(numKeys, keysInCacheStore); } // check if keys survive restart cache().stop(); cache().start(); store = TestingUtil.getFirstStore(cache()); assertEquals(numKeys, store.size()); for (int i = 0; i < numKeys; i++) { assertEquals(i, cache().get(i)); } } public void testSizeWithEvictedEntries() { final int numKeys = 300; for (int i = 0; i < numKeys; i++) { cache.put(i, i); } assertFalse("Data Container should not have all keys", numKeys == cache.getAdvancedCache().getDataContainer().size()); assertEquals(numKeys, cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).size()); } public void testSizeWithEvictedEntriesAndFlags() { final int numKeys = 300; for (int i = 0; i < numKeys; i++) { cache.put(i, i); } assertFalse("Data Container should not have all keys", numKeys == cache.getAdvancedCache().getDataContainer().size()); assertEquals(cache.getAdvancedCache().getDataContainer().size(), cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD).size()); // Skip cache store only prevents writes not reads assertEquals(300, cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_STORE).size()); } public void testKeySetWithEvictedEntries() { final int numKeys = 300; for (int i = 0; i < numKeys; i++) { cache.put(i, i); } assertFalse("Data Container should not have all keys", numKeys == cache.getAdvancedCache().getDataContainer().size()); Set<Object> keySet = cache.keySet(); for (int i = 0; i < numKeys; i++) { assertTrue("Key: " + i + " was not found!", keySet.contains(i)); } } public void testKeySetWithEvictedEntriesAndFlags() { final int numKeys = 300; for (int i = 0; i < numKeys; i++) { cache.put(i, i); } AdvancedCache<Object, Object> flagCache = cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD); DataContainer<Object, Object> dc = flagCache.getDataContainer(); assertFalse("Data Container should not have all keys", numKeys == dc.size()); Set<Object> keySet = flagCache.keySet(); assertEquals(dc.size(), keySet.size()); DataConversion conversion = flagCache.getValueDataConversion(); for (InternalCacheEntry<Object, Object> entry : dc) { Object key = entry.getKey(); assertTrue("Key: " + key + " was not found!", keySet.contains(conversion.fromStorage(key))); } } public void testEntrySetWithEvictedEntries() { final int numKeys = 300; for (int i = 0; i < numKeys; i++) { cache.put(i, i); } assertFalse("Data Container should not have all keys", numKeys == cache.getAdvancedCache().getDataContainer().size()); Set<Map.Entry<Object, Object>> entrySet = cache.entrySet(); assertEquals(numKeys, entrySet.size()); Map<Object, Object> map = new HashMap<>(entrySet.size()); for (Map.Entry<Object, Object> entry : entrySet) { map.put(entry.getKey(), entry.getValue()); } for (int i = 0; i < numKeys; i++) { assertEquals("Key/Value mismatch!", i, map.get(i)); } } public void testEntrySetWithEvictedEntriesAndFlags() { final int numKeys = 300; for (int i = 0; i < numKeys; i++) { cache.put(i, i); } AdvancedCache<Object, Object> flagCache = cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD); DataContainer<Object, Object> dc = flagCache.getDataContainer(); assertFalse("Data Container should not have all keys", numKeys == dc.size()); Set<Map.Entry<Object, Object>> entrySet = flagCache.entrySet(); assertEquals(dc.size(), entrySet.size()); DataConversion keyDataConversion = flagCache.getAdvancedCache().getKeyDataConversion(); DataConversion valueDataConversion = flagCache.getAdvancedCache().getValueDataConversion(); Map<WrappedByteArray, WrappedByteArray> map = new HashMap<>(entrySet.size()); for (Map.Entry<Object, Object> entry : entrySet) { WrappedByteArray storedKey = (WrappedByteArray) keyDataConversion.toStorage(entry.getKey()); WrappedByteArray storedValue = (WrappedByteArray) valueDataConversion.toStorage(entry.getValue()); map.put(storedKey, storedValue); } for (InternalCacheEntry entry : dc) { assertEquals("Key/Value mismatch!", entry.getValue(), map.get(entry.getKey())); } } public void testValuesWithEvictedEntries() { final int numKeys = 300; for (int i = 0; i < numKeys; i++) { cache.put(i, i); } assertFalse("Data Container should not have all keys", numKeys == cache.getAdvancedCache().getDataContainer().size()); Collection<Object> values = cache.values(); for (int i = 0; i < numKeys; i++) { assertTrue("Value: " + i + " was not found!", values.contains(i)); } } public void testValuesWithEvictedEntriesAndFlags() { final int numKeys = 300; for (int i = 0; i < numKeys; i++) { cache.put(i, i); } AdvancedCache<Object, Object> flagCache = cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD); DataContainer<Object, Object> dc = flagCache.getDataContainer(); assertFalse("Data Container should not have all keys", numKeys == dc.size()); Collection<Object> values = flagCache.values(); assertEquals(dc.size(), values.size()); for (InternalCacheEntry<Object, Object> entry : dc) { Object dcValue = entry.getValue(); DataConversion valueDataConversion = flagCache.getValueDataConversion(); assertTrue("Value: " + dcValue + " was not found!", values.contains(valueDataConversion.fromStorage(dcValue))); } } public void testStoreAndLoadWithGetEntry() { final int numKeys = 300; for (int i = 0; i < numKeys; i++) { cache().put(i, i); } int keysInDataContainer = cache().getAdvancedCache().getDataContainer().size(); assertTrue(keysInDataContainer != numKeys); // some keys got evicted DummyInMemoryStore dims = TestingUtil.getFirstStore(cache()); long keysInCacheStore = dims.size(); if (passivationEnabled) { assertEquals(numKeys, keysInDataContainer + keysInCacheStore); } else { assertEquals(numKeys, keysInCacheStore); } // check if keys survive restart cache().stop(); cache().start(); dims = TestingUtil.getFirstStore(cache()); assertEquals(numKeys, dims.size()); for (int i = 0; i < numKeys; i++) { assertEquals(i, cache.getAdvancedCache().getCacheEntry(i).getValue()); } } }
10,281
37.94697
136
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/IdentityKeyValueWrapper.java
package org.infinispan.persistence; /** * @author Pedro Ruivo * @since 11.0 */ public class IdentityKeyValueWrapper<K, V> implements KeyValueWrapper<K, V, V> { private static final IdentityKeyValueWrapper<?, ?> INSTANCE = new IdentityKeyValueWrapper<>(); private IdentityKeyValueWrapper() { } public static <K1, V1> KeyValueWrapper<K1, V1, V1> instance() { //noinspection unchecked return (KeyValueWrapper<K1, V1, V1>) INSTANCE; } @Override public V wrap(K key, V value) { return value; } @Override public V unwrap(V value) { return value; } }
610
20.068966
97
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/ConcurrentLoadAndEvictTest.java
package org.infinispan.persistence; import static org.infinispan.context.Flag.SKIP_CACHE_STORE; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.commands.read.GetKeyValueCommand; import org.infinispan.commands.write.EvictCommand; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.context.InvocationContext; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.interceptors.impl.InvocationContextInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.PersistenceException; 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 a thread going past the cache loader interceptor and the interceptor deciding that loading is not necessary, * then another thread rushing ahead and evicting the entry from memory. * * @author Manik Surtani */ @Test(groups = "functional", testName = "persistence.ConcurrentLoadAndEvictTest") public class ConcurrentLoadAndEvictTest extends SingleCacheManagerTest { SlowDownInterceptor sdi; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { sdi = new SlowDownInterceptor(); // we need a loader and a custom interceptor to intercept get() calls // after the CLI, to slow it down so an evict goes through first ConfigurationBuilder config = new ConfigurationBuilder(); config .persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .customInterceptors() .addInterceptor() .interceptor(sdi).after(InvocationContextInterceptor.class) .transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL); return TestCacheManagerFactory.createCacheManager(config); } public void testEvictBeforeRead() throws PersistenceException, ExecutionException, InterruptedException { cache = cacheManager.getCache(); cache.put("a", "b"); assert cache.get("a").equals("b"); DummyInMemoryStore cl = TestingUtil.getFirstStore(cache); MarshallableEntry se = cl.loadEntry("a"); assert se != null; assert se.getValue().equals("b"); // clear the cache cache.getAdvancedCache().withFlags(SKIP_CACHE_STORE).clear(); se = cl.loadEntry("a"); assert se != null; assert se.getValue().equals("b"); // now attempt a concurrent get and evict. sdi.enabled = true; log.info("test::doing the get"); // call the get Future<String> future = fork(new Callable<String>() { @Override public String call() throws Exception { return (String) cache.get("a"); } }); // now run the evict. log.info("test::before the evict"); cache.evict("a"); log.info("test::after the evict"); // make sure the get call, which would have gone past the cache loader interceptor first, gets the correct value. assert future.get().equals("b"); // disable the SlowDownInterceptor sdi.enabled = false; // and check that the key actually has been evicted assert !TestingUtil.extractComponent(cache, InternalDataContainer.class).containsKey("a"); } public static class SlowDownInterceptor extends DDAsyncInterceptor { private static final Log log = LogFactory.getLog(SlowDownInterceptor.class); volatile boolean enabled = false; transient CountDownLatch getLatch = new CountDownLatch(1); transient CountDownLatch evictLatch = new CountDownLatch(1); @Override public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { if (enabled) { log.trace("Wait for evict to give go ahead..."); if (!evictLatch.await(60000, TimeUnit.MILLISECONDS)) throw new TimeoutException("Didn't see get after 60 seconds!"); } return invokeNextAndFinally(ctx, command, (rCtx, rCommand, rv, throwable) -> { log.trace("After get, now let evict go through"); if (enabled) getLatch.countDown(); }); } @Override public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable { if (enabled) { evictLatch.countDown(); log.trace("Wait for get to finish..."); if (!getLatch.await(60000, TimeUnit.MILLISECONDS)) throw new TimeoutException("Didn't see evict after 60 seconds!"); } return invokeNext(ctx, command); } } }
5,324
38.444444
119
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/UnnecessaryLoadingTest.java
package org.infinispan.persistence; import static org.testng.Assert.assertEquals; import java.util.concurrent.Executor; import java.util.function.Predicate; import org.infinispan.Cache; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.ConfigurationFor; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.IntSet; import org.infinispan.configuration.cache.AbstractStoreConfiguration; import org.infinispan.configuration.cache.AbstractStoreConfigurationBuilder; import org.infinispan.configuration.cache.AsyncStoreConfiguration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.context.InvocationContext; import org.infinispan.context.InvocationContextFactory; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.TestObjectStreamMarshaller; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.dummy.Element; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.persistence.manager.PersistenceManagerImpl; import org.infinispan.persistence.spi.InitializationContext; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.persistence.spi.SegmentedAdvancedLoadWriteStore; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.concurrent.IsolationLevel; import org.reactivestreams.Publisher; import org.testng.annotations.Test; /** * A test to ensure stuff from a cache store is not loaded unnecessarily if it already exists in memory, or if the * Flag.SKIP_CACHE_LOAD is applied. * * @author Manik Surtani * @author Sanne Grinovero * @version 4.1 */ @Test(testName = "persistence.UnnecessaryLoadingTest", groups = "functional", singleThreaded = true) @CleanupAfterMethod public class UnnecessaryLoadingTest extends SingleCacheManagerTest { DummyInMemoryStore store; private PersistenceManagerImpl persistenceManager; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .invocationBatching().enable() .persistence() .addStore(CountingStoreConfigurationBuilder.class) .persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .locking().isolationLevel(IsolationLevel.READ_COMMITTED); //avoid versioning since we are storing directly in CacheStore return TestCacheManagerFactory.createCacheManager(cfg); } @Override protected void setup() throws Exception { super.setup(); persistenceManager = (PersistenceManagerImpl) TestingUtil.extractComponent(cache, PersistenceManager.class); store = TestingUtil.getStore(cache, 1, false); } public void testRepeatedLoads() throws PersistenceException { CountingStore countingCS = getCountingCacheStore(); store.write(MarshalledEntryUtil.create("k1", "v1", cache)); assert countingCS.numLoads == 0; assert countingCS.numContains == 0; assert "v1".equals(cache.get("k1")); assert countingCS.numLoads == 1 : "Expected 1, was " + countingCS.numLoads; assert countingCS.numContains == 0 : "Expected 0, was " + countingCS.numContains; assert "v1".equals(cache.get("k1")); assert countingCS.numLoads == 1 : "Expected 1, was " + countingCS.numLoads; assert countingCS.numContains == 0 : "Expected 0, was " + countingCS.numContains; } public void testSkipCacheFlagUsage() throws PersistenceException { CountingStore countingCS = getCountingCacheStore(); store.write(MarshalledEntryUtil.create("k1", "v1", cache)); assert countingCS.numLoads == 0; assert countingCS.numContains == 0; //load using SKIP_CACHE_LOAD should not find the object in the store assert cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD).get("k1") == null; assert countingCS.numLoads == 0; assert countingCS.numContains == 0; // counter-verify that the object was actually in the store: assert "v1".equals(cache.get("k1")); assert countingCS.numLoads == 1 : "Expected 1, was " + countingCS.numLoads; assert countingCS.numContains == 0 : "Expected 0, was " + countingCS.numContains; // now check that put won't return the stored value store.write(MarshalledEntryUtil.create("k2", "v2", cache)); Object putReturn = cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD).put("k2", "v2-second"); assert putReturn == null; assert countingCS.numLoads == 1 : "Expected 1, was " + countingCS.numLoads; assert countingCS.numContains == 0 : "Expected 0, was " + countingCS.numContains; // but it inserted it in the cache: assert "v2-second".equals(cache.get("k2")); // perform the put in the cache & store, using same value: putReturn = cache.put("k2", "v2-second"); //returned value from the cache: assert "v2-second".equals(putReturn); //and verify that the put operation updated the store too: InvocationContextFactory icf = TestingUtil.extractComponent(cache, InvocationContextFactory.class); InvocationContext context = icf.createSingleKeyNonTxInvocationContext(); assert "v2-second".equals(CompletionStages.join(persistenceManager.loadFromAllStores("k2", context.isOriginLocal(), true)).getValue()); assertEquals(countingCS.numLoads,2, "Expected 2, was " + countingCS.numLoads); assert countingCS.numContains == 0 : "Expected 0, was " + countingCS.numContains; cache.containsKey("k1"); assert countingCS.numContains == 0 : "Expected 0, was " + countingCS.numContains; assert !cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD).containsKey("k3"); assert countingCS.numContains == 0 : "Expected 0, was " + countingCS.numContains; assert countingCS.numLoads == 2 : "Expected 2, was " + countingCS.numLoads; //now with batching: boolean batchStarted = cache.getAdvancedCache().startBatch(); assert batchStarted; assert null == cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD).get("k1batch"); assert countingCS.numLoads == 2 : "Expected 2, was " + countingCS.numLoads; assert null == cache.getAdvancedCache().get("k2batch"); assert countingCS.numLoads == 3 : "Expected 3, was " + countingCS.numLoads; cache.endBatch(true); } private CountingStore getCountingCacheStore() { CountingStore countingCS = TestingUtil.getFirstLoader(cache); reset(cache, countingCS); return countingCS; } public void testSkipCacheLoadFlagUsage() throws PersistenceException { CountingStore countingCS = getCountingCacheStore(); TestObjectStreamMarshaller sm = new TestObjectStreamMarshaller(); try { store.write(MarshalledEntryUtil.create("home", "Vermezzo", sm)); store.write(MarshalledEntryUtil.create("home-second", "Newcastle Upon Tyne", sm)); assert countingCS.numLoads == 0; //load using SKIP_CACHE_LOAD should not find the object in the store assert cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD).get("home") == null; assert countingCS.numLoads == 0; assert cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD).put("home", "Newcastle") == null; assert countingCS.numLoads == 0; final Object put = cache.getAdvancedCache().put("home-second", "Newcastle Upon Tyne, second"); assertEquals(put, "Newcastle Upon Tyne"); assert countingCS.numLoads == 1; } finally { sm.stop(); } } private void reset(Cache<?, ?> cache, CountingStore countingCS) { cache.clear(); countingCS.numLoads = 0; countingCS.numContains = 0; } public static class CountingStore implements SegmentedAdvancedLoadWriteStore { public int numLoads, numContains; @Override public int size() { return 0; } @Override public void clear() { } @Override public void purge(Executor threadPool, PurgeListener task) { } @Override public void init(InitializationContext ctx) { } @Override public void write(MarshallableEntry entry) { } @Override public boolean delete(Object key) { return false; } @Override public MarshallableEntry loadEntry(Object key) throws PersistenceException { incrementLoads(); return null; } @Override public Publisher<MarshallableEntry> entryPublisher(Predicate filter, boolean fetchValue, boolean fetchMetadata) { return null; } @Override public MarshallableEntry get(int segment, Object key) { return loadEntry(key); } @Override public boolean contains(int segment, Object key) { return contains(key); } @Override public void write(int segment, MarshallableEntry entry) { } @Override public boolean delete(int segment, Object key) { return false; } @Override public Publisher<MarshallableEntry> entryPublisher(IntSet segments, Predicate filter, boolean fetchValue, boolean fetchMetadata) { return null; } @Override public void start() { } @Override public void stop() { } @Override public boolean contains(Object key) throws PersistenceException { numContains++; return false; } private void incrementLoads() { numLoads++; } @Override public int size(IntSet segments) { return 0; } @Override public Publisher publishKeys(IntSet segments, Predicate filter) { return null; } @Override public void clear(IntSet segments) { } } @BuiltBy(CountingStoreConfigurationBuilder.class) @ConfigurationFor(CountingStore.class) public static class CountingStoreConfiguration extends AbstractStoreConfiguration<CountingStoreConfiguration> { public CountingStoreConfiguration(AttributeSet attributes, AsyncStoreConfiguration async) { super(Element.DUMMY_STORE, attributes, async); } } public static class CountingStoreConfigurationBuilder extends AbstractStoreConfigurationBuilder<CountingStoreConfiguration, CountingStoreConfigurationBuilder> { public CountingStoreConfigurationBuilder(PersistenceConfigurationBuilder builder) { super(builder, CountingStoreConfiguration.attributeDefinitionSet()); } @Override public CountingStoreConfiguration create() { return new CountingStoreConfiguration(attributes.protect(), async.create()); } @Override public CountingStoreConfigurationBuilder self() { return this; } } }
11,528
35.484177
163
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/DummyInitializationContext.java
package org.infinispan.persistence; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import org.infinispan.Cache; import org.infinispan.commons.io.ByteBufferFactory; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.StoreConfiguration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.marshall.persistence.PersistenceMarshaller; import org.infinispan.persistence.spi.InitializationContext; import org.infinispan.persistence.spi.MarshallableEntryFactory; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.util.concurrent.NonBlockingManager; /** * @author Mircea Markus * @since 6.0 */ public class DummyInitializationContext implements InitializationContext { StoreConfiguration clc; Cache cache; PersistenceMarshaller marshaller; ByteBufferFactory byteBufferFactory; MarshallableEntryFactory marshalledEntryFactory; ExecutorService executorService; GlobalConfiguration globalConfiguration; BlockingManager manager; NonBlockingManager nonBlockingManager; TimeService timeService; public DummyInitializationContext() { } public DummyInitializationContext(StoreConfiguration clc, Cache cache, PersistenceMarshaller marshaller, ByteBufferFactory byteBufferFactory, MarshallableEntryFactory marshalledEntryFactory, ExecutorService executorService, GlobalConfiguration globalConfiguration, BlockingManager manager, NonBlockingManager nonBlockingManager, TimeService timeService) { this.clc = clc; this.cache = cache; this.marshaller = marshaller; this.byteBufferFactory = byteBufferFactory; this.marshalledEntryFactory = marshalledEntryFactory; this.executorService = executorService; this.globalConfiguration = globalConfiguration; this.manager = manager; this.nonBlockingManager = nonBlockingManager; this.timeService = timeService; } @Override public StoreConfiguration getConfiguration() { return clc; } @Override public Cache getCache() { return cache; } @Override public KeyPartitioner getKeyPartitioner() { return cache.getAdvancedCache().getComponentRegistry().getComponent(KeyPartitioner.class); } @Override public TimeService getTimeService() { return timeService; } @Override public ByteBufferFactory getByteBufferFactory() { return byteBufferFactory; } @Override public <K,V> MarshallableEntryFactory<K,V> getMarshallableEntryFactory() { //noinspection unchecked return marshalledEntryFactory; } @Override public ExecutorService getExecutor() { return executorService; } @Override public Executor getNonBlockingExecutor() { return executorService; } @Override public BlockingManager getBlockingManager() { return manager; } @Override public NonBlockingManager getNonBlockingManager() { return nonBlockingManager; } @Override public PersistenceMarshaller getPersistenceMarshaller() { return marshaller; } @Override public GlobalConfiguration getGlobalConfiguration() { return globalConfiguration; } }
3,419
28.482759
127
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/CacheLoaderRepeatableReadFunctionalTest.java
package org.infinispan.persistence; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * Tests the cache loader when used in a repeatable read isolation level * * @author William Burns * @since 6.0 */ @Test(groups = "functional", testName = "persistence.CacheLoaderRepeatableReadFunctionalTest") public class CacheLoaderRepeatableReadFunctionalTest extends CacheLoaderFunctionalTest { @Override protected void configure(ConfigurationBuilder cb) { cb.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); } @Factory @Override public Object[] factory() { return new Object[] { new CacheLoaderRepeatableReadFunctionalTest().segmented(true), new CacheLoaderRepeatableReadFunctionalTest().segmented(false), }; } }
930
30.033333
94
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/SharedStoreTest.java
package org.infinispan.persistence; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.InCacheMode; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; @Test (testName = "persistence.SharedStoreTest", groups = "functional") @CleanupAfterMethod @InCacheMode({CacheMode.DIST_SYNC, CacheMode.REPL_SYNC}) public class SharedStoreTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg .persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(SharedStoreTest.class.getName()) .purgeOnStartup(false).shared(true) .clustering() .cacheMode(cacheMode) .build(); createCluster(cfg, 3); // don't create the caches here, we want them to join the cluster one by one } @AfterMethod @Override protected void clearContent() throws Throwable { List<DummyInMemoryStore> cachestores = TestingUtil.cachestores(caches()); super.clearContent(); // Because the store is shared, the stats are not cleared between methods // In particular, the clear between methods is added to the statistics clearStoreStats(cachestores); } private void clearStoreStats(List<DummyInMemoryStore> cachestores) { cachestores.forEach(DummyInMemoryStore::clearStats); } public void testUnnecessaryWrites() throws PersistenceException { // The first cache is created here. cache(0).put("key", "value"); // the second and third cache are only started here // so state transfer will copy the key to the other caches // however is should not write it to the cache store again for (Cache<Object, Object> c: caches()) { assertEquals("value", c.get("key")); } List<DummyInMemoryStore> cacheStores = TestingUtil.cachestores(caches()); for (DummyInMemoryStore dimcs: cacheStores) { assertTrue(dimcs.contains("key")); assertEquals(0, dimcs.stats().get("clear").intValue()); assertEquals(0, dimcs.stats().get("clear").intValue()); assertEquals(1, dimcs.stats().get("write").intValue()); } cache(0).remove("key"); for (Cache<Object, Object> c: caches()) { assertNull(c.get("key")); } for (DummyInMemoryStore dimcs: cacheStores) { assert !dimcs.contains("key"); assertEquals("Entry should have been removed from the cache store just once", Integer.valueOf(1), dimcs.stats().get("delete")); } } public void testSkipSharedCacheStoreFlagUsage() throws PersistenceException { cache(0).getAdvancedCache().withFlags(Flag.SKIP_SHARED_CACHE_STORE).put("key", "value"); assert cache(0).get("key").equals("value"); List<DummyInMemoryStore> cacheStores = TestingUtil.cachestores(caches()); for (DummyInMemoryStore dimcs: cacheStores) { assert !dimcs.contains("key"); assert dimcs.stats().get("write") == 0 : "Cache store should NOT contain any entry. Put was with SKIP_SHARED_CACHE_STORE flag."; } } public void testSize() { // Force all the caches up List<Cache<String, String>> caches = caches(); Cache<String, String> cache0 = caches.get(0); cache0.put("key", "value"); clearStoreStats(TestingUtil.cachestores(caches())); assertEquals(1, cache0.size()); // Stats are shared between nodes - so it shouldn't matter which, but there should only be 1 size invocation // and no other invocations assertStoreDistinctInvocationAmount(cache0, 1); assertStoreStatInvocationEquals(cache0, "size", 1); } private void assertStoreStatInvocationEquals(Cache<?, ?> cache, String invocationName, int invocationCount) { DummyInMemoryStore dims = TestingUtil.getFirstStore(cache); assertEquals(invocationCount, dims.stats().get(invocationName).intValue()); } private void assertStoreDistinctInvocationAmount(Cache<?, ?> cache, int distinctInvocations) { DummyInMemoryStore dims = TestingUtil.getFirstStore(cache); assertEquals(distinctInvocations, dims.stats().values().stream().filter(i -> i > 0).count()); } }
4,982
39.185484
137
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/CacheLoaderFunctionalTest.java
package org.infinispan.persistence; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.infinispan.api.mvcc.LockAssert.assertNoLocks; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.v; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.commons.configuration.Combine; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.Configurations; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.context.Flag; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.infinispan.util.concurrent.IsolationLevel; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; import jakarta.transaction.NotSupportedException; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; /** * Tests the interceptor chain and surrounding logic * * @author Manik Surtani */ @Test(groups = "functional", testName = "persistence.CacheLoaderFunctionalTest") public class CacheLoaderFunctionalTest extends AbstractInfinispanTest { private static final Log log = LogFactory.getLog(CacheLoaderFunctionalTest.class); private boolean segmented; Cache<String, String> cache; DummyInMemoryStore store; DummyInMemoryStore writer; TransactionManager tm; ConfigurationBuilder cfg; EmbeddedCacheManager cm; long lifespan = 60000000; // very large lifespan so nothing actually expires @BeforeMethod(alwaysRun = true) public void setUp() { cfg = getConfiguration(); configure(cfg); cm = TestCacheManagerFactory.createCacheManager(cfg); cache = getCache(cm); store = TestingUtil.getFirstStore(cache); writer = TestingUtil.getFirstStore(cache); tm = TestingUtil.getTransactionManager(cache); } public CacheLoaderFunctionalTest segmented(boolean segmented) { this.segmented = segmented; return this; } @Override protected String parameters() { return "[" + segmented + "]"; } @Factory public Object[] factory() { return new Object[]{ new CacheLoaderFunctionalTest().segmented(true), new CacheLoaderFunctionalTest().segmented(false), }; } protected ConfigurationBuilder getConfiguration() { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .segmented(segmented) .storeName(this.getClass().getName()) // in order to use the same store .transaction().transactionMode(TransactionMode.TRANSACTIONAL); return cfg; } protected Cache<String, String> getCache(EmbeddedCacheManager cm) { return cm.getCache(); } protected Cache<String, String> getCache(EmbeddedCacheManager cm, String name) { return cm.getCache(name); } protected void configure(ConfigurationBuilder cb) { } @AfterMethod(alwaysRun = true) public void tearDown() throws PersistenceException { if (writer != null) { writer.clear(); } TestingUtil.killCacheManagers(cm); cache = null; cm = null; cfg = null; tm = null; store = null; } private void assertInCacheAndStore(String key, Object value) throws PersistenceException { assertInCacheAndStore(key, value, -1); } private void assertInCacheAndStore(String key, Object value, long lifespanMillis) throws PersistenceException { assertInCacheAndStore(cache, store, key, value, lifespanMillis); } private <K> void assertInCacheAndStore(Cache<? super K, ?> cache, DummyInMemoryStore store, K key, Object value) throws PersistenceException { assertInCacheAndStore(cache, store, key, value, -1); } private <K> void assertInCacheAndStore(Cache<? super K, ?> cache, DummyInMemoryStore loader, K key, Object value, long lifespanMillis) throws PersistenceException { InternalCacheEntry se = cache.getAdvancedCache().getDataContainer().get(key); testStoredEntry(se.getValue(), value, se.getLifespan(), lifespanMillis, "Cache", key); MarshallableEntry load = loader.loadEntry(key); testStoredEntry(load.getValue(), value, load.getMetadata() == null ? -1 : load.getMetadata().lifespan(), lifespanMillis, "Store", key); } private void testStoredEntry(Object value, Object expectedValue, long lifespan, long expectedLifespan, String src, Object key) { assertEquals("Wrong value on " + src, expectedValue, value); assertEquals("Wrong lifespan on " + src, expectedLifespan, lifespan); } private static <K> void assertNotInCacheAndStore(Cache<? super K, ?> cache, DummyInMemoryStore store, K... keys) throws PersistenceException { for (K key : keys) { assertFalse("Cache should not contain key " + key, cache.getAdvancedCache().getDataContainer().containsKey(key)); assertFalse("Store should not contain key " + key, store.contains(key)); } } private void assertNotInCacheAndStore(String... keys) throws PersistenceException { assertNotInCacheAndStore(cache, store, keys); } private void assertInStoreNotInCache(String... keys) throws PersistenceException { assertInStoreNotInCache(cache, store, keys); } private static <K> void assertInStoreNotInCache(Cache<? super K, ?> cache, DummyInMemoryStore store, K... keys) throws PersistenceException { for (K key : keys) { assertFalse("Cache should not contain key " + key, cache.getAdvancedCache().getDataContainer().containsKey(key)); assertTrue("Store should contain key " + key, store.contains(key)); } } private void assertInCacheAndNotInStore(String... keys) throws PersistenceException { assertInCacheAndNotInStore(cache, store, keys); } private static <K> void assertInCacheAndNotInStore(Cache<? super K, ?> cache, DummyInMemoryStore store, K... keys) throws PersistenceException { for (K key : keys) { assert cache.getAdvancedCache().getDataContainer().containsKey(key) : "Cache should not contain key " + key; assertFalse("Store should contain key " + key, store.contains(key)); } } public void testStoreAndRetrieve() throws PersistenceException { assertNotInCacheAndStore("k1", "k2", "k3", "k4", "k5", "k6", "k7"); cache.put("k1", "v1"); cache.put("k2", "v2", lifespan, MILLISECONDS); cache.putAll(Collections.singletonMap("k3", "v3")); cache.putAll(Collections.singletonMap("k4", "v4"), lifespan, MILLISECONDS); cache.putIfAbsent("k5", "v5"); cache.putIfAbsent("k6", "v6", lifespan, MILLISECONDS); cache.putIfAbsent("k5", "v5-SHOULD-NOT-PUT"); cache.putIfAbsent("k6", "v6-SHOULD-NOT-PUT", lifespan, MILLISECONDS); cache.putForExternalRead("k7", "v7"); cache.putForExternalRead("k7", "v7-SHOULD-NOT-PUT"); for (int i = 1; i < 8; i++) { // even numbers have lifespans if (i % 2 == 1) assertInCacheAndStore("k" + i, "v" + i); else assertInCacheAndStore("k" + i, "v" + i, lifespan); } assert !cache.remove("k1", "some rubbish"); for (int i = 1; i < 8; i++) { // even numbers have lifespans if (i % 2 == 1) assertInCacheAndStore("k" + i, "v" + i); else assertInCacheAndStore("k" + i, "v" + i, lifespan); } log.debugf("cache.get(\"k1\") = %s", cache.get("k1")); boolean removed = cache.remove("k1", "v1"); assertTrue(removed); log.debugf("cache.get(\"k1\") = %s", cache.get("k1")); assertEquals("v2", cache.remove("k2")); assertNotInCacheAndStore("k1", "k2"); for (int i = 3; i < 8; i++) { // even numbers have lifespans if (i % 2 == 1) assertInCacheAndStore("k" + i, "v" + i); else assertInCacheAndStore("k" + i, "v" + i, lifespan); } cache.clear(); assertNotInCacheAndStore("k1", "k2", "k3", "k4", "k5", "k6", "k7"); } public void testReplaceMethods() throws PersistenceException { assertNotInCacheAndStore("k1", "k2", "k3", "k4"); cache.replace("k1", "v1-SHOULD-NOT-STORE"); assertNoLocks(cache); cache.replace("k2", "v2-SHOULD-NOT-STORE", lifespan, MILLISECONDS); assertNoLocks(cache); assertNotInCacheAndStore("k1", "k2", "k3", "k4"); cache.put("k1", "v1"); assertNoLocks(cache); cache.put("k2", "v2"); assertNoLocks(cache); cache.put("k3", "v3"); assertNoLocks(cache); cache.put("k4", "v4"); assertNoLocks(cache); for (int i = 1; i < 5; i++) assertInCacheAndStore("k" + i, "v" + i); cache.replace("k1", "v1-SHOULD-NOT-STORE", "v1-STILL-SHOULD-NOT-STORE"); assertNoLocks(cache); cache.replace("k2", "v2-SHOULD-NOT-STORE", "v2-STILL-SHOULD-NOT-STORE", lifespan, MILLISECONDS); assertNoLocks(cache); for (int i = 1; i < 5; i++) assertInCacheAndStore("k" + i, "v" + i); cache.replace("k1", "v1-REPLACED"); assertNoLocks(cache); cache.replace("k2", "v2-REPLACED", lifespan, MILLISECONDS); assertInCacheAndStore("k2", "v2-REPLACED", lifespan); assertNoLocks(cache); cache.replace("k3", "v3", "v3-REPLACED"); assertNoLocks(cache); cache.replace("k4", "v4", "v4-REPLACED", lifespan, MILLISECONDS); assertNoLocks(cache); for (int i = 1; i < 5; i++) { // even numbers have lifespans if (i % 2 == 1) assertInCacheAndStore("k" + i, "v" + i + "-REPLACED"); else assertInCacheAndStore("k" + i, "v" + i + "-REPLACED", lifespan); } assertNoLocks(cache); } public void testLoading() throws PersistenceException { assertNotInCacheAndStore("k1", "k2", "k3", "k4"); if (Configurations.isTxVersioned(cache.getCacheConfiguration())) { for (int i = 1; i < 5; i++) writer.write(MarshalledEntryUtil.createWithVersion("k" + i, "v" + i, cache)); } else { for (int i = 1; i < 5; i++) writer.write(MarshalledEntryUtil.create("k" + i, "v" + i, cache)); } for (int i = 1; i < 5; i++) assertEquals("v" + i, cache.get("k" + i)); // make sure we have no stale locks!! assertNoLocks(cache); for (int i = 1; i < 5; i++) cache.evict("k" + i); // make sure we have no stale locks!! assertNoLocks(cache); assertEquals("v1", cache.putIfAbsent("k1", "v1-SHOULD-NOT-STORE")); assertEquals("v2", cache.remove("k2")); assertEquals("v3", cache.replace("k3", "v3-REPLACED")); assertTrue(cache.replace("k4", "v4", "v4-REPLACED")); // make sure we have no stale locks!! assertNoLocks(cache); int size = cache.size(); assertEquals("Expected the cache to contain 3 elements but contained " + cache.entrySet(), 3, size); for (int i = 1; i < 5; i++) cache.evict("k" + i); // make sure we have no stale locks!! assertNoLocks(cache); assertEquals(0, cache.getAdvancedCache().getDataContainer().size()); // cache size ops will not trigger a load cache.clear(); // this should propagate to the loader though assertNotInCacheAndStore("k1", "k2", "k3", "k4"); // make sure we have no stale locks!! assertNoLocks(cache); } public void testPreloading() throws Exception { ConfigurationBuilder preloadingCfg = newPreloadConfiguration(cfg.build(), this.getClass().getName() + "preloadingCache"); doPreloadingTest(preloadingCfg.build(), "preloadingCache"); } public void testPreloadingWithoutAutoCommit() throws Exception { ConfigurationBuilder preloadingCfg = newPreloadConfiguration(cfg.build(), this.getClass().getName() + "preloadingCache_2"); preloadingCfg.transaction().autoCommit(false); doPreloadingTest(preloadingCfg.build(), "preloadingCache_2"); } public void testPreloadingWithEvictionAndOneMaxEntry() throws Exception { ConfigurationBuilder preloadingCfg = newPreloadConfiguration(cfg.build(), this.getClass().getName() + "preloadingCache_3"); preloadingCfg.memory().size(1); doPreloadingTestWithEviction(preloadingCfg.build(), "preloadingCache_3"); } public void testPreloadingWithEviction() throws Exception { ConfigurationBuilder preloadingCfg = newPreloadConfiguration(cfg.build(), this.getClass().getName() + "preloadingCache_4"); preloadingCfg.memory().size(3); doPreloadingTestWithEviction(preloadingCfg.build(), "preloadingCache_4"); } ConfigurationBuilder newPreloadConfiguration(Configuration configuration, String storeName) { ConfigurationBuilder preloadingCfg = new ConfigurationBuilder(); preloadingCfg.read(configuration, Combine.DEFAULT); preloadingCfg.persistence() .clearStores() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .segmented(segmented) .preload(true) .storeName(storeName); return preloadingCfg; } @Test(groups = "unstable") public void testPurgeOnStartup() throws PersistenceException { ConfigurationBuilder purgingCfg = new ConfigurationBuilder(); purgingCfg.read(cfg.build(), Combine.DEFAULT); purgingCfg.persistence().clearStores().addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName("purgingCache").purgeOnStartup(true); cm.defineConfiguration("purgingCache", purgingCfg.build()); Cache<String, String> purgingCache = getCache(cm, "purgingCache"); DummyInMemoryStore purgingLoader = TestingUtil.getFirstStore(purgingCache); assertNotInCacheAndStore(purgingCache, purgingLoader, "k1", "k2", "k3", "k4"); purgingCache.put("k1", "v1"); purgingCache.put("k2", "v2", lifespan, MILLISECONDS); purgingCache.put("k3", "v3"); purgingCache.put("k4", "v4", lifespan, MILLISECONDS); for (int i = 1; i < 5; i++) { if (i % 2 == 1) assertInCacheAndStore(purgingCache, purgingLoader, "k" + i, "v" + i); else assertInCacheAndStore(purgingCache, purgingLoader, "k" + i, "v" + i, lifespan); } DataContainer c = purgingCache.getAdvancedCache().getDataContainer(); assertEquals(4, c.size()); purgingCache.stop(); assertEquals(0, c.size()); purgingCache.start(); purgingLoader = TestingUtil.getFirstStore(purgingCache); c = purgingCache.getAdvancedCache().getDataContainer(); assertEquals(0, c.size()); assertNotInCacheAndStore(purgingCache, purgingLoader, "k1", "k2", "k3", "k4"); } public void testTransactionalWrites() throws Exception { assertEquals(ComponentStatus.RUNNING, cache.getStatus()); assertNotInCacheAndStore("k1", "k2"); tm.begin(); cache.put("k1", "v1"); cache.put("k2", "v2", lifespan, MILLISECONDS); Transaction t = tm.suspend(); assertNotInCacheAndStore("k1", "k2"); tm.resume(t); tm.commit(); assertInCacheAndStore("k1", "v1"); assertInCacheAndStore("k2", "v2", lifespan); tm.begin(); cache.remove("k1"); cache.remove("k2"); t = tm.suspend(); assertInCacheAndStore("k1", "v1"); assertInCacheAndStore("k2", "v2", lifespan); tm.resume(t); tm.commit(); assertNotInCacheAndStore("k1", "k2"); tm.begin(); cache.put("k1", "v1"); cache.put("k2", "v2", lifespan, MILLISECONDS); t = tm.suspend(); assertNotInCacheAndStore("k1", "k2"); tm.resume(t); tm.rollback(); assertNotInCacheAndStore("k1", "k2"); cache.put("k1", "v1"); cache.put("k2", "v2", lifespan, MILLISECONDS); assertInCacheAndStore("k1", "v1"); assertInCacheAndStore("k2", "v2", lifespan); tm.begin(); cache.remove("k1"); cache.remove("k2"); t = tm.suspend(); assertInCacheAndStore("k1", "v1"); assertInCacheAndStore("k2", "v2", lifespan); tm.resume(t); tm.rollback(); assertInCacheAndStore("k1", "v1"); assertInCacheAndStore("k2", "v2", lifespan); } public void testTransactionalReplace(Method m) throws Exception { assertEquals(ComponentStatus.RUNNING, cache.getStatus()); assertNotInCacheAndStore(k(m, 1)); assertNotInCacheAndStore(k(m, 2)); cache.put(k(m, 2), v(m)); tm.begin(); cache.put(k(m, 1), v(m, 1)); cache.replace(k(m, 2), v(m, 1)); Transaction t = tm.suspend(); assertNotInCacheAndStore(k(m, 1)); assertInCacheAndStore(k(m, 2), v(m)); tm.resume(t); tm.commit(); assertInCacheAndStore(k(m, 1), v(m, 1)); assertInCacheAndStore(k(m, 2), v(m, 1)); } public void testEvictAndRemove() throws PersistenceException { assertNotInCacheAndStore("k1", "k2"); cache.put("k1", "v1"); cache.put("k2", "v2", lifespan, MILLISECONDS); cache.evict("k1"); cache.evict("k2"); assertEquals("v1", cache.remove("k1")); assertEquals("v2", cache.remove("k2")); } public void testLoadingToMemory() throws PersistenceException { assertNotInCacheAndStore("k1", "k2"); store.write(MarshalledEntryUtil.create("k1", "v1", cache)); store.write(MarshalledEntryUtil.create("k2", "v2", cache)); assertInStoreNotInCache("k1", "k2"); assertEquals("v1", cache.get("k1")); assertEquals("v2", cache.get("k2")); assertInCacheAndStore("k1", "v1"); assertInCacheAndStore("k2", "v2"); store.delete("k1"); store.delete("k2"); assertInCacheAndNotInStore("k1", "k2"); assertEquals("v1", cache.get("k1")); assertEquals("v2", cache.get("k2")); } public void testSkipLocking(Method m) { String name = m.getName(); AdvancedCache<String, String> advancedCache = cache.getAdvancedCache(); advancedCache.put("k-" + name, "v-" + name); advancedCache.withFlags(Flag.SKIP_LOCKING).put("k-" + name, "v2-" + name); } public void testDuplicatePersistence(Method m) throws Exception { String key = "k-" + m.getName(); String value = "v-" + m.getName(); cache.put(key, value); assertEquals(value, cache.get(key)); cache.stop(); cache.start(); // A new writer is created after restart writer = TestingUtil.getFirstStore(cache); tm.begin(); cache.containsKey(key); // Necessary call to force locks being acquired in advance cache.getAdvancedCache().withFlags(Flag.FORCE_WRITE_LOCK).get(key); cache.put(key, value); tm.commit(); assertEquals(value, cache.get(key)); } public void testNullFoundButLoaderReceivedValueLaterInTransaction() throws SystemException, NotSupportedException { assertNotInCacheAndStore("k1"); tm.begin(); try { assertNull(cache.get("k1")); // Now simulate that someone else wrote to the store while during our tx store.write(MarshalledEntryUtil.create("k1", "v1", cache)); IsolationLevel level = cache.getCacheConfiguration().locking().isolationLevel(); switch(level) { case READ_COMMITTED: assertEquals("v1", cache.get("k1")); break; case REPEATABLE_READ: assertNull(cache.get("k1")); break; default: fail("Unsupported isolation " + level + " - please change test to add desired outcome for isolation level"); } } finally { tm.rollback(); } } public void testValuesForCacheLoader() { cache.putIfAbsent("k1", "v1"); Set<String> copy1 = copyValues(cache); assertEquals(TestingUtil.setOf("v1"), copy1); cache.putIfAbsent("k2", "v2"); Set<String> copy2 = copyValues(cache); assertEquals(TestingUtil.setOf("v1", "v2"), copy2); } private Set<String> copyValues(Cache<?, String> cache) { return new HashSet<>(cache.values()); } protected void doPreloadingTest(Configuration preloadingCfg, String cacheName) throws Exception { assertTrue("Preload not enabled for preload test", preloadingCfg.persistence().preload()); cm.defineConfiguration(cacheName, preloadingCfg); Cache<String, String> preloadingCache = getCache(cm, cacheName); DummyInMemoryStore preloadingCacheLoader = TestingUtil.getFirstStore(preloadingCache); assert preloadingCache.getCacheConfiguration().persistence().preload(); assertNotInCacheAndStore(preloadingCache, preloadingCacheLoader, "k1", "k2", "k3", "k4"); preloadingCache.getAdvancedCache().getTransactionManager().begin(); preloadingCache.put("k1", "v1"); preloadingCache.put("k2", "v2", lifespan, MILLISECONDS); preloadingCache.put("k3", "v3"); preloadingCache.put("k4", "v4", lifespan, MILLISECONDS); preloadingCache.getAdvancedCache().getTransactionManager().commit(); for (int i = 1; i < 5; i++) { if (i % 2 == 1) assertInCacheAndStore(preloadingCache, preloadingCacheLoader, "k" + i, "v" + i); else assertInCacheAndStore(preloadingCache, preloadingCacheLoader, "k" + i, "v" + i, lifespan); } DataContainer c = preloadingCache.getAdvancedCache().getDataContainer(); assertEquals(4, c.size()); preloadingCache.stop(); assertEquals(0, c.size()); preloadingCache.start(); // The old store's marshaller is not working any more preloadingCacheLoader = TestingUtil.getFirstStore(preloadingCache); assert preloadingCache.getCacheConfiguration().persistence().preload(); c = preloadingCache.getAdvancedCache().getDataContainer(); assertEquals(4, c.size()); for (int i = 1; i < 5; i++) { if (i % 2 == 1) assertInCacheAndStore(preloadingCache, preloadingCacheLoader, "k" + i, "v" + i); else assertInCacheAndStore(preloadingCache, preloadingCacheLoader, "k" + i, "v" + i, lifespan); } } protected void doPreloadingTestWithEviction(Configuration preloadingCfg, String cacheName) throws Exception { assertTrue("Preload not enabled for preload with eviction test", preloadingCfg.persistence().preload()); assertTrue("Eviction not enabled for preload with eviction test", preloadingCfg.memory().isEvictionEnabled()); cm.defineConfiguration(cacheName, preloadingCfg); final Cache<String, String> preloadingCache = getCache(cm, cacheName); final long expectedEntriesInContainer = Math.min(4L, preloadingCfg.memory().size()); DummyInMemoryStore preloadingCacheLoader = TestingUtil.getFirstStore(preloadingCache); assertTrue("Preload not enabled in cache configuration", preloadingCache.getCacheConfiguration().persistence().preload()); assertNotInCacheAndStore(preloadingCache, preloadingCacheLoader, "k1", "k2", "k3", "k4"); preloadingCache.getAdvancedCache().getTransactionManager().begin(); preloadingCache.put("k1", "v1"); preloadingCache.put("k2", "v2", lifespan, MILLISECONDS); preloadingCache.put("k3", "v3"); preloadingCache.put("k4", "v4", lifespan, MILLISECONDS); preloadingCache.getAdvancedCache().getTransactionManager().commit(); DataContainer c = preloadingCache.getAdvancedCache().getDataContainer(); assertEquals("Wrong number of entries in data container", expectedEntriesInContainer, c.size()); for (int i = 1; i < 5; i++) { final String key = "k" + i; final Object value = "v" + i; final long lifespan = i % 2 == 1 ? -1 : this.lifespan; boolean found = false; InternalCacheEntry se = preloadingCache.getAdvancedCache().getDataContainer().get(key); MarshallableEntry load = preloadingCacheLoader.loadEntry(key); if (se != null) { testStoredEntry(se.getValue(), value, se.getLifespan(), lifespan, "Cache", key); found = true; } if (load != null) { testStoredEntry(load.getValue(), value, load.getMetadata() == null ? -1 : load.getMetadata().lifespan(), lifespan, "Store", key); found = true; } assertTrue("Key not found.", found); } preloadingCache.stop(); assertEquals("DataContainer still has entries after stop", 0, c.size()); preloadingCache.start(); // The old store's marshaller is not working any more preloadingCacheLoader = TestingUtil.getFirstStore(preloadingCache); assertTrue("Preload not enabled in cache configuration", preloadingCache.getCacheConfiguration().persistence().preload()); c = preloadingCache.getAdvancedCache().getDataContainer(); assertEquals("Wrong number of entries in data container", expectedEntriesInContainer, c.size()); for (int i = 1; i < 5; i++) { final String key = "k" + i; final Object value = "v" + i; final long lifespan = i % 2 == 1 ? -1 : this.lifespan; boolean found = false; InternalCacheEntry se = preloadingCache.getAdvancedCache().getDataContainer().get(key); MarshallableEntry load = preloadingCacheLoader.loadEntry(key); if (se != null) { testStoredEntry(se.getValue(), value, se.getLifespan(), lifespan, "Cache", key); found = true; } if (load != null) { testStoredEntry(load.getValue(), value, load.getMetadata() == null ? -1 : load.getMetadata().lifespan(), lifespan, "Store", key); found = true; } assertTrue("Key not found.", found); } } }
27,028
37.502849
167
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/DummyStoreParallelIterationTest.java
package org.infinispan.persistence; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.metadata.Metadata; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 6.0 */ @Test(groups = "functional", testName = "persistence.DummyStoreParallelIterationTest") public class DummyStoreParallelIterationTest extends ParallelIterationTest { @Override protected void configurePersistence(ConfigurationBuilder cb) { cb.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); } @Override protected void assertMetadataEmpty(Metadata metadata, Object key) { // Do nothing for now as keys require metadata - this can be fixed later } }
805
31.24
86
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/ClassLoaderManagerDisablingTest.java
package org.infinispan.persistence; 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.Set; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; import org.infinispan.interceptors.AsyncInterceptor; import org.infinispan.interceptors.impl.CacheLoaderInterceptor; import org.infinispan.interceptors.impl.CacheWriterInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * ClassLoaderManagerDisablingTest. * * @author Tristan Tarrant * @since 5.2 */ @Test(groups = "functional", testName = "persistence.ClassLoaderManagerDisablingTest") public class ClassLoaderManagerDisablingTest extends AbstractInfinispanTest { public void testStoreDisabling() { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); disableWithConfiguration(builder); } public void testAsyncStoreDisabling() { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).async().enable(); disableWithConfiguration(builder); } public void testChainingStoreDisabling() { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).async().enable(); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(builder); try { checkAndDisableStore(cm, 2); } finally { TestingUtil.killCacheManagers(cm); } } public void testDisablingWithPassivation() { //test: PassivationInterceptor/ActivationInterceptor ConfigurationBuilder builder = createPersistenceConfiguration(); enablePassivation(builder); disableWithConfiguration(builder); } public void testDisablingWithClusteredPassivation() { //test: PassivationInterceptor/ClustererActivationInterceptor ConfigurationBuilder builder = createClusterConfiguration(CacheMode.DIST_SYNC); enablePassivation(builder); disableWithClusteredConfiguration(builder); } public void testClusteredDisabling() { //test: ClusteredCacheLoaderInterceptor/DistCacheWriterInterceptor ConfigurationBuilder builder = createClusterConfiguration(CacheMode.DIST_SYNC); disableWithClusteredConfiguration(builder); } public void testDisableWithMultipleStores() { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); PersistenceConfigurationBuilder p = builder.persistence(); p.addStore(DummyInMemoryStoreConfigurationBuilder.class).fetchPersistentState(true); // Just add this one as it is simple and we need different types p.addStore(UnnecessaryLoadingTest.CountingStoreConfigurationBuilder.class); EmbeddedCacheManager cacheManager = null; try { cacheManager = TestCacheManagerFactory.createCacheManager(builder); Cache<Object, Object> cache = cacheManager.getCache(); PersistenceManager pm = TestingUtil.extractComponent(cache, PersistenceManager.class); // Get all types of stores Set<Object> stores = pm.getStores(Object.class); // Should have 2 before we disable assertEquals(2, stores.size()); pm.disableStore(UnnecessaryLoadingTest.CountingStore.class.getName()); stores = pm.getStores(Object.class); assertEquals(1, stores.size()); DummyInMemoryStore store = (DummyInMemoryStore) stores.iterator().next(); } finally { TestingUtil.killCacheManagers(cacheManager); } } private void checkAndDisableStore(EmbeddedCacheManager cm) { checkAndDisableStore(cm, 1); } private void checkAndDisableStore(EmbeddedCacheManager cm, int count) { Cache<Object, Object> cache = cm.getCache(); PersistenceManager clm = TestingUtil.extractComponent(cache, PersistenceManager.class); Set<DummyInMemoryStore> stores = clm.getStores(DummyInMemoryStore.class); assertEquals(count, stores.size()); stores.forEach(store -> assertTrue(store.isRunning())); clm.disableStore(DummyInMemoryStore.class.getName()); stores.forEach(store -> assertFalse(store.isRunning())); AsyncInterceptor interceptor = cache.getAdvancedCache().getAsyncInterceptorChain() .findInterceptorExtending(CacheLoaderInterceptor.class); assertNull(interceptor); interceptor = cache.getAdvancedCache().getAsyncInterceptorChain() .findInterceptorExtending(CacheWriterInterceptor.class); assertNull(interceptor); } private ConfigurationBuilder createClusterConfiguration(CacheMode cacheMode) { ConfigurationBuilder builder = createPersistenceConfiguration(); builder.clustering().cacheMode(cacheMode); return builder; } private ConfigurationBuilder createPersistenceConfiguration() { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); builder.persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class); return builder; } private void enablePassivation(ConfigurationBuilder builder) { builder.persistence().passivation(true); builder.memory().size(1); } private void disableWithConfiguration(ConfigurationBuilder builder) { EmbeddedCacheManager cacheManager = null; try { cacheManager = TestCacheManagerFactory.createCacheManager(builder); checkAndDisableStore(cacheManager); } finally { TestingUtil.killCacheManagers(cacheManager); } } private void disableWithClusteredConfiguration(ConfigurationBuilder builder) { EmbeddedCacheManager cacheManager = null; try { cacheManager = TestCacheManagerFactory.createClusteredCacheManager(builder); checkAndDisableStore(cacheManager); } finally { TestingUtil.killCacheManagers(cacheManager); } } }
6,896
40.8
169
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/PassivationFunctionalTest.java
package org.infinispan.persistence; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.testng.AssertJUnit.assertEquals; import java.util.HashMap; import java.util.Map; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.InternalCacheValue; import org.infinispan.manager.CacheContainer; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests the interceptor chain and surrounding logic * * @author Manik Surtani */ @Test(groups = "functional", testName = "persistence.PassivationFunctionalTest") public class PassivationFunctionalTest extends AbstractInfinispanTest { Cache<String, String> cache; DummyInMemoryStore store; TransactionManager tm; ConfigurationBuilder cfg; CacheContainer cm; long lifespan = 6000000; // very large lifespan so nothing actually expires @BeforeClass public void setUp() { cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfg .persistence() .passivation(true) .addStore(DummyInMemoryStoreConfigurationBuilder.class); cm = TestCacheManagerFactory.createCacheManager(cfg); cache = cm.getCache(); store = TestingUtil.getFirstStore(cache); tm = TestingUtil.getTransactionManager(cache); } @AfterClass public void tearDown() { TestingUtil.killCacheManagers(cm); } @AfterMethod public void afterMethod() throws PersistenceException { if (cache != null) cache.clear(); if (store != null) store.clear(); } private void assertInCacheNotInStore(Object key, Object value) throws PersistenceException { assertInCacheNotInStore(key, value, -1); } private void assertInCacheNotInStore(Object key, Object value, long lifespanMillis) throws PersistenceException { InternalCacheValue se = cache.getAdvancedCache().getDataContainer().get(key).toInternalCacheValue(); testStoredEntry(se, value, lifespanMillis, "Cache", key); eventually(() -> !store.contains(key)); } private void assertInStoreNotInCache(Object key, Object value) throws PersistenceException { assertInStoreNotInCache(key, value, -1); } private void assertInStoreNotInCache(Object key, Object value, long lifespanMillis) throws PersistenceException { MarshallableEntry se = store.loadEntry(key); testStoredEntry(se, value, lifespanMillis, "Store", key); assert !cache.getAdvancedCache().getDataContainer().containsKey(key) : "Key " + key + " should not be in cache!"; } private void testStoredEntry(InternalCacheValue entry, Object expectedValue, long expectedLifespan, String src, Object key) { assert entry != null : src + " entry for key " + key + " should NOT be null"; assert entry.getValue().equals(expectedValue) : src + " should contain value " + expectedValue + " under key " + key + " but was " + entry.getValue() + ". Entry is " + entry; assert entry.getLifespan() == expectedLifespan : src + " expected lifespan for key " + key + " to be " + expectedLifespan + " but was " + entry.getLifespan() + ". Entry is " + entry; } private void testStoredEntry(MarshallableEntry entry, Object expectedValue, long expectedLifespan, String src, Object key) { assert entry != null : src + " entry for key " + key + " should NOT be null"; assert entry.getValue().equals(expectedValue) : src + " should contain value " + expectedValue + " under key " + key + " but was " + entry.getValue() + ". Entry is " + entry; if (expectedLifespan > -1) assert entry.getMetadata().lifespan() == expectedLifespan : src + " expected lifespan for key " + key + " to be " + expectedLifespan + " but was " + entry.getMetadata().lifespan() + ". Entry is " + entry; } private void assertNotInCacheAndStore(Object... keys) throws PersistenceException { for (Object key : keys) { assert !cache.getAdvancedCache().getDataContainer().containsKey(key) : "Cache should not contain key " + key; assert !store.contains(key) : "Store should not contain key " + key; } } public void testPassivate() throws PersistenceException { assertNotInCacheAndStore("k1", "k2"); cache.put("k1", "v1"); cache.put("k2", "v2", lifespan, MILLISECONDS); assertInCacheNotInStore("k1", "v1"); assertInCacheNotInStore("k2", "v2", lifespan); cache.evict("k1"); cache.evict("k2"); assertInStoreNotInCache("k1", "v1"); assertInStoreNotInCache("k2", "v2", lifespan); // now activate assert cache.get("k1").equals("v1"); assert cache.get("k2").equals("v2"); assertInCacheNotInStore("k1", "v1"); assertInCacheNotInStore("k2", "v2", lifespan); cache.evict("k1"); cache.evict("k2"); assertInStoreNotInCache("k1", "v1"); assertInStoreNotInCache("k2", "v2", lifespan); } public void testRemoveAndReplace() throws PersistenceException { assertNotInCacheAndStore("k1", "k2"); cache.put("k1", "v1"); cache.put("k2", "v2", lifespan, MILLISECONDS); assertInCacheNotInStore("k1", "v1"); assertInCacheNotInStore("k2", "v2", lifespan); cache.evict("k1"); cache.evict("k2"); assertInStoreNotInCache("k1", "v1"); assertInStoreNotInCache("k2", "v2", lifespan); assert cache.remove("k1").equals("v1"); assertNotInCacheAndStore("k1"); assert cache.put("k2", "v2-NEW").equals("v2"); assertInCacheNotInStore("k2", "v2-NEW"); cache.evict("k2"); assertInStoreNotInCache("k2", "v2-NEW"); assert cache.replace("k2", "v2-REPLACED").equals("v2-NEW"); assertInCacheNotInStore("k2", "v2-REPLACED"); cache.evict("k2"); assertInStoreNotInCache("k2", "v2-REPLACED"); assert !cache.replace("k2", "some-rubbish", "v2-SHOULDNT-STORE"); // but should activate assertInCacheNotInStore("k2", "v2-REPLACED"); cache.evict("k2"); assertInStoreNotInCache("k2", "v2-REPLACED"); assert cache.replace("k2", "v2-REPLACED", "v2-REPLACED-AGAIN"); assertInCacheNotInStore("k2", "v2-REPLACED-AGAIN"); cache.evict("k2"); assertInStoreNotInCache("k2", "v2-REPLACED-AGAIN"); assert cache.putIfAbsent("k2", "should-not-appear").equals("v2-REPLACED-AGAIN"); assertInCacheNotInStore("k2", "v2-REPLACED-AGAIN"); assert cache.putIfAbsent("k1", "v1-if-absent") == null; assertInCacheNotInStore("k1", "v1-if-absent"); } public void testTransactions() throws Exception { assertNotInCacheAndStore("k1", "k2"); tm.begin(); cache.put("k1", "v1"); cache.put("k2", "v2", lifespan, MILLISECONDS); Transaction t = tm.suspend(); assertNotInCacheAndStore("k1", "k2"); tm.resume(t); tm.commit(); assertInCacheNotInStore("k1", "v1"); assertInCacheNotInStore("k2", "v2", lifespan); tm.begin(); cache.remove("k1"); cache.remove("k2"); t = tm.suspend(); assertInCacheNotInStore("k1", "v1"); assertInCacheNotInStore("k2", "v2", lifespan); tm.resume(t); tm.commit(); assertNotInCacheAndStore("k1", "k2"); tm.begin(); cache.put("k1", "v1"); cache.put("k2", "v2", lifespan, MILLISECONDS); t = tm.suspend(); assertNotInCacheAndStore("k1", "k2"); tm.resume(t); tm.rollback(); assertNotInCacheAndStore("k1", "k2"); cache.put("k1", "v1"); cache.put("k2", "v2", lifespan, MILLISECONDS); assertInCacheNotInStore("k1", "v1"); assertInCacheNotInStore("k2", "v2", lifespan); cache.evict("k1"); cache.evict("k2"); assertInStoreNotInCache("k1", "v1"); assertInStoreNotInCache("k2", "v2", lifespan); } public void testPutMap() throws PersistenceException { assertNotInCacheAndStore("k1", "k2", "k3"); cache.put("k1", "v1"); cache.put("k2", "v2"); cache.evict("k2"); assertInCacheNotInStore("k1", "v1"); assertInStoreNotInCache("k2", "v2"); Map<String, String> m = new HashMap<>(); m.put("k1", "v1-NEW"); m.put("k2", "v2-NEW"); m.put("k3", "v3-NEW"); cache.putAll(m); assertInCacheNotInStore("k1", "v1-NEW"); assertInCacheNotInStore("k2", "v2-NEW"); assertInCacheNotInStore("k3", "v3-NEW"); } public void testClear() { assertNotInCacheAndStore("k1", "k2", "k3"); cache.put("k1", "v1"); cache.put("k2", "v2"); cache.evict("k2"); assertInCacheNotInStore("k1", "v1"); assertInStoreNotInCache("k2", "v2"); cache.clear(); assertEquals(0, cache.size()); } }
9,350
33.003636
210
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/ClusterCacheLoaderTest.java
package org.infinispan.persistence; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.InCacheMode; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Tester for {@link org.infinispan.persistence.cluster.ClusterLoader} * * @author Mircea.Markus@jboss.com */ @Test(groups = "functional", testName = "persistence.ClusterCacheLoaderTest") @InCacheMode({ CacheMode.INVALIDATION_SYNC, CacheMode.DIST_SYNC, CacheMode.REPL_SYNC }) public class ClusterCacheLoaderTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { EmbeddedCacheManager cacheManager1 = TestCacheManagerFactory.createClusteredCacheManager(); EmbeddedCacheManager cacheManager2 = TestCacheManagerFactory.createClusteredCacheManager(); registerCacheManager(cacheManager1, cacheManager2); ConfigurationBuilder config1 = getDefaultClusteredCacheConfig(cacheMode, false); config1.persistence().addClusterLoader() .segmented(false); ConfigurationBuilder config2 = getDefaultClusteredCacheConfig(cacheMode, false); config2.persistence().addClusterLoader() .segmented(false); config2.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); cacheManager1.defineConfiguration("clusteredCl", config1.build()); cacheManager2.defineConfiguration("clusteredCl", config2.build()); waitForClusterToForm("clusteredCl"); } public void testRemoteLoad() { Cache<String, String> cache1 = cache(0, "clusteredCl"); Cache<String, String> cache2 = cache(1, "clusteredCl"); assertNull(cache1.get("key")); assertNull(cache1.get("key")); cache2.put("key", "value"); assertEquals(cache1.get("key"), "value"); } public void testRemoteLoadFromCacheLoader() throws Exception { Cache<String, String> cache1 = cache(0, "clusteredCl"); Cache<String, String> cache2 = cache(1, "clusteredCl"); DummyInMemoryStore writer = TestingUtil.getStore(cache2, 1, false); assertNull(cache1.get("key")); assertNull(cache2.get("key")); writer.write(MarshalledEntryUtil.create("key", "value", cache2)); assertEquals(writer.loadEntry("key").getValue(), "value"); assertEquals(cache1.get("key"), "value"); } }
2,912
40.614286
97
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/WriteSkewCacheLoaderFunctionalTest.java
package org.infinispan.persistence; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.infinispan.test.TestingUtil.withTx; 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.Arrays; import java.util.Collection; import java.util.concurrent.Callable; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.InternalCacheValue; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.PersistenceException; 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.concurrent.IsolationLevel; import org.testng.annotations.Test; /** * Tests write skew functionality when interacting with a cache loader. * * @author Pedro Ruivo * @author Galder Zamarreño * @since 5.3 */ @Test(groups = "functional", testName = "persistence.WriteSkewCacheLoaderFunctionalTest") public class WriteSkewCacheLoaderFunctionalTest extends SingleCacheManagerTest { DummyInMemoryStore loader; static final long LIFESPAN = 60000000; // very large lifespan so nothing actually expires @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = defineConfiguration(); EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(builder); loader = TestingUtil.getFirstStore(cm.getCache()); return cm; } private ConfigurationBuilder defineConfiguration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL) .locking().isolationLevel(IsolationLevel.REPEATABLE_READ) .clustering().cacheMode(CacheMode.REPL_SYNC) .persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(this.getClass().getName()).preload(true); return builder; } private void assertInCacheAndStore(Cache cache, DummyInMemoryStore loader, Object key, Object value) throws PersistenceException { assertInCacheAndStore(cache, loader, key, value, -1); } private void assertInCacheAndStore(Cache cache, DummyInMemoryStore store, Object key, Object value, long lifespanMillis) throws PersistenceException { InternalCacheValue icv = cache.getAdvancedCache().getDataContainer().peek(key).toInternalCacheValue(); assertStoredEntry(icv.getValue(), value, icv.getLifespan(), lifespanMillis, "Cache", key); assertNotNull("For :" + icv, icv.getInternalMetadata().entryVersion()); MarshallableEntry<?, ?> load = store.loadEntry(key); assertStoredEntry(load.getValue(), value, load.getMetadata() == null ? -1 : load.getMetadata().lifespan(), lifespanMillis, "Store", key); assertNotNull("For :" + load, load.getInternalMetadata().entryVersion()); } private void assertStoredEntry(Object value, Object expectedValue, long lifespanMillis, long expectedLifespan, String src, Object key) { assertNotNull(src + " entry for key " + key + " should NOT be null", value); assertEquals(src + " should contain value " + expectedValue + " under key " + key + " but was " + value, expectedValue, value); assertEquals(src + " expected lifespan for key " + key + " to be " + expectedLifespan + " but was " + lifespanMillis, expectedLifespan, lifespanMillis); } private <T> void assertNotInCacheAndStore(Cache cache, DummyInMemoryStore store, Collection<T> keys) throws PersistenceException { for (Object key : keys) { assertFalse("Cache should not contain key " + key, cache.getAdvancedCache().getDataContainer().containsKey(key)); assertFalse("Store should not contain key " + key, store.contains(key)); } } public void testPreloadingInTransactionalCache() throws Exception { assertTrue(cache.getCacheConfiguration().persistence().preload()); assertNotInCacheAndStore(cache, loader, Arrays.asList("k1", "k2", "k3", "k4")); cache.put("k1", "v1"); cache.put("k2", "v2", LIFESPAN, MILLISECONDS); cache.put("k3", "v3"); cache.put("k4", "v4", LIFESPAN, MILLISECONDS); for (int i = 1; i < 5; i++) { if (i % 2 == 1) assertInCacheAndStore(cache, loader, "k" + i, "v" + i); else assertInCacheAndStore(cache, loader, "k" + i, "v" + i, LIFESPAN); } DataContainer<?, ?> c = cache.getAdvancedCache().getDataContainer(); assertEquals(4, c.size()); cache.stop(); assertEquals(0, c.size()); cache.start(); assertTrue(cache.getCacheConfiguration().persistence().preload()); c = cache.getAdvancedCache().getDataContainer(); assertEquals(4, c.size()); // Re-retrieve since the old reference might not be usable loader = TestingUtil.getFirstStore(cache); for (int i = 1; i < 5; i++) { if (i % 2 == 1) assertInCacheAndStore(cache, loader, "k" + i, "v" + i); else assertInCacheAndStore(cache, loader, "k" + i, "v" + i, LIFESPAN); } withTx(cache.getAdvancedCache().getTransactionManager(), (Callable<Void>) () -> { assertEquals("v1", cache.get("k1")); cache.put("k1", "new-v1"); return null; }); } }
5,921
43.19403
158
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/ActivationDuringEvictTest.java
package org.infinispan.persistence; 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 java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.commands.write.EvictCommand; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.DataContainer; import org.infinispan.context.InvocationContext; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.interceptors.impl.PassivationCacheLoaderInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.MarshallableEntry; 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 an evict command going past the entry wrapping interceptor while the entry is in the store, * then another thread rushing ahead and activating the entry in memory before the evict command commits. * * @author Dan Berindei */ @Test(groups = "functional", testName = "persistence.ActivationDuringEvictTest") public class ActivationDuringEvictTest extends SingleCacheManagerTest { public static final String KEY = "a"; public static final String VALUE = "b"; SlowDownInterceptor sdi; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { sdi = new SlowDownInterceptor(); ConfigurationBuilder config = new ConfigurationBuilder(); config .persistence() .passivation(true) .addStore(DummyInMemoryStoreConfigurationBuilder.class) .customInterceptors() .addInterceptor() .interceptor(sdi).after(PassivationCacheLoaderInterceptor.class) .transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL); return TestCacheManagerFactory.createCacheManager(config); } public void testActivationDuringEvict() throws Exception { DataContainer dc = cache.getAdvancedCache().getDataContainer(); DummyInMemoryStore cl = TestingUtil.getFirstStore(cache); cache.put(KEY, VALUE); assertEquals(VALUE, cache.get(KEY)); MarshallableEntry se = cl.loadEntry(KEY); assertNull(se); // passivate the entry cache.evict(KEY); assertPassivated(dc, cl, KEY, VALUE); // start blocking evict commands sdi.enabled = true; // call the evict() Future<?> future = fork(() -> { log.info("before the evict"); cache.evict(KEY); log.info("after the evict"); }); // wait for the SlowDownInterceptor to intercept the evict if (!sdi.evictLatch.await(10, TimeUnit.SECONDS)) throw new org.infinispan.util.concurrent.TimeoutException(); log.info("doing the get"); Object value = cache.get(KEY); // make sure the get call, which would have gone past the cache loader interceptor first, gets the correct value. assertEquals(VALUE, value); sdi.getLatch.countDown(); future.get(10, TimeUnit.SECONDS); // disable the SlowDownInterceptor sdi.enabled = false; // and check that the key actually has been evicted assertPassivated(dc, cl, KEY, VALUE); } private void assertPassivated(DataContainer dc, DummyInMemoryStore cl, String key, String expected) { MarshallableEntry se; assertFalse(dc.containsKey(key)); se = cl.loadEntry(key); assertNotNull(se); assertEquals(expected, se.getValue()); } static class SlowDownInterceptor extends DDAsyncInterceptor { private static final Log log = LogFactory.getLog(SlowDownInterceptor.class); volatile boolean enabled = false; CountDownLatch getLatch = new CountDownLatch(1); CountDownLatch evictLatch = new CountDownLatch(1); @Override public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable { if (enabled) { evictLatch.countDown(); log.trace("Wait for get to finish..."); if (!getLatch.await(10, TimeUnit.SECONDS)) throw new TimeoutException("Didn't see evict!"); } return invokeNext(ctx, command); } } }
4,789
35.846154
119
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/PassivatePersistentTest.java
package org.infinispan.persistence; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.CacheContainer; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(testName = "persistence.PassivatePersistentTest", groups = "functional") public class PassivatePersistentTest extends AbstractInfinispanTest { Cache<String, String> cache; DummyInMemoryStore store; TransactionManager tm; ConfigurationBuilder cfg; CacheContainer cm; @BeforeMethod public void setUp() { cfg = new ConfigurationBuilder(); cfg .persistence() .passivation(true) .addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(this.getClass().getName()) .purgeOnStartup(false); cm = TestCacheManagerFactory.createCacheManager(cfg); cache = cm.getCache(); store = TestingUtil.getFirstStore(cache); tm = TestingUtil.getTransactionManager(cache); } @AfterMethod public void tearDown() throws PersistenceException { store.clear(); TestingUtil.killCacheManagers(cm); } public void testPersistence() throws PersistenceException { cache.put("k", "v"); assert "v".equals(cache.get("k")); cache.evict("k"); assert store.contains("k"); assert "v".equals(cache.get("k")); eventually(() -> !store.contains("k")); cache.stop(); cache.start(); // The old store's marshaller is not working any more store = TestingUtil.getFirstStore(cache); assert store.contains("k"); assert "v".equals(cache.get("k")); eventually(() -> !store.contains("k")); } }
2,183
31.597015
79
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/SoftIndexFileStoreParallelIterationTest.java
package org.infinispan.persistence; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.metadata.Metadata; import org.testng.annotations.Test; /** * @author William Burns * @since 13.0 */ @Test(groups = "functional", testName = "persistence.SoftIndexFileStoreParallelIterationTest") public class SoftIndexFileStoreParallelIterationTest extends ParallelIterationTest { protected String dataLocation; protected String indexLocation; @Override protected void configurePersistence(ConfigurationBuilder cb) { dataLocation = CommonsTestingUtil.tmpDirectory(this.getClass().getSimpleName(), "data"); indexLocation = CommonsTestingUtil.tmpDirectory(this.getClass().getSimpleName(), "index"); cb.persistence().addSoftIndexFileStore() .dataLocation(dataLocation) .indexLocation(indexLocation); } @Override protected void teardown() { super.teardown(); Util.recursiveFileRemove(dataLocation); Util.recursiveFileRemove(indexLocation); } @Override protected boolean hasMetadata(boolean fetchValues, int i) { return fetchValues && super.hasMetadata(fetchValues, i); } @Override protected void assertMetadataEmpty(Metadata metadata, Object key) { // SoftIndexFileStore may return metadata even when not requested as it may already be in memory and there is // no real reason to skip it } }
1,535
32.391304
115
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/LocalConditionalCommandPassivationTest.java
package org.infinispan.persistence; import org.testng.annotations.Test; /** * Tests if the conditional commands correctly fetch the value from cache loader even with the skip cache load/store * flags. * <p/> * The configuration used is a non-tx non-clustered cache with passivation. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "functional", testName = "persistence.LocalConditionalCommandPassivationTest") public class LocalConditionalCommandPassivationTest extends LocalConditionalCommandTest { public LocalConditionalCommandPassivationTest() { super(false, true); } }
605
26.545455
116
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/ConcurrentLoadAndEvictTxTest.java
package org.infinispan.persistence; import static org.infinispan.test.TestingUtil.getTransactionManager; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import jakarta.transaction.TransactionManager; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "persistence.ConcurrentLoadAndEvictTxTest") public class ConcurrentLoadAndEvictTxTest extends SingleCacheManagerTest { TransactionManager tm; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder config = getDefaultStandaloneCacheConfig(true); config .memory().size(10) .expiration().wakeUpInterval(10L) .persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class) .build(); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(config); cache = cm.getCache(); tm = getTransactionManager(cache); return cm; } public void testEvictAndTx() throws SystemException, NotSupportedException, RollbackException, HeuristicRollbackException, HeuristicMixedException { for (int i=0; i<10; i++) { tm.begin(); for (int j=0; j<10; j++) cache.put(String.format("key-%s-%s", i, j), "value"); tm.commit(); for (int j=0; j<10; j++) assert "value".equals(cache.get(String.format("key-%s-%s", i, j))) : "Data loss on key " + String.format("key-%s-%s", i, j); } } }
1,941
39.458333
158
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/SingleFileStoreParallelIterationTest.java
package org.infinispan.persistence; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.SingleFileStoreConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 6.0 */ @Test(groups = "functional", testName = "persistence.SingleFileStoreParallelIterationTest") public class SingleFileStoreParallelIterationTest extends ParallelIterationTest { protected String location; @Override protected void configurePersistence(ConfigurationBuilder cb) { location = CommonsTestingUtil.tmpDirectory(this.getClass()); cb.persistence().addStore(SingleFileStoreConfigurationBuilder.class).location(location); } @Override protected void teardown() { super.teardown(); Util.recursiveFileRemove(location); } }
931
29.064516
94
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/BaseStoreTest.java
package org.infinispan.persistence; import static org.infinispan.test.TestingUtil.allEntries; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.marshall.WrappedBytes; import org.infinispan.configuration.cache.Configuration; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.entries.InternalCacheValue; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.container.impl.InternalEntryFactoryImpl; import org.infinispan.marshall.TestObjectStreamMarshaller; import org.infinispan.marshall.persistence.PersistenceMarshaller; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.spi.AdvancedCacheExpirationWriter; import org.infinispan.persistence.spi.AdvancedLoadWriteStore; import org.infinispan.persistence.spi.InitializationContext; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.data.Key; import org.infinispan.test.data.Person; import org.infinispan.test.fwk.TestInternalCacheEntryFactory; import org.infinispan.util.ControlledTimeService; import org.infinispan.util.PersistenceMockUtil; import org.infinispan.util.concurrent.WithinThreadExecutor; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; /** * This is a base class containing various unit tests for each and every different CacheStore implementations. If you * need to add Cache/CacheManager tests that need to be run for each cache store/loader implementation, then use * BaseStoreFunctionalTest. */ // this needs to be here for the test to run in an IDE @Test(groups = "unit", testName = "persistence.BaseStoreTest") public abstract class BaseStoreTest extends AbstractInfinispanTest { protected static final int WRITE_DELETE_BATCH_MIN_ENTRIES = 80; protected static final int WRITE_DELETE_BATCH_MAX_ENTRIES = 120; protected TestObjectStreamMarshaller marshaller; protected abstract AdvancedLoadWriteStore createStore() throws Exception; protected AdvancedLoadWriteStore<Object, Object> cl; protected ControlledTimeService timeService; private InternalEntryFactory factory; //alwaysRun = true otherwise, when we run unstable tests, this method is not invoked (because it belongs to the unit group) @BeforeMethod(alwaysRun = true) public void setUp() throws Exception { marshaller = new TestObjectStreamMarshaller(getSerializationContextInitializer()); timeService = getTimeService(); factory = new InternalEntryFactoryImpl(); TestingUtil.inject(factory, timeService); try { //noinspection unchecked cl = createStore(); cl.start(); } catch (Exception e) { log.error("Error creating store", e); throw e; } } //alwaysRun = true otherwise, when we run unstable tests, this method is not invoked (because it belongs to the unit group) @AfterMethod(alwaysRun = true) public void tearDown() throws PersistenceException { try { if (cl != null) { cl.clear(); cl.destroy(); } if (marshaller != null) { marshaller.stop(); } } finally { cl = null; } } /** * @return a mock marshaller for use with the cache store impls */ protected PersistenceMarshaller getMarshaller() { return marshaller; } /** * @return the {@link SerializationContextInitializer} used to initiate the user marshaller */ protected SerializationContextInitializer getSerializationContextInitializer() { return TestDataSCI.INSTANCE; } /** * To be overridden if the store requires special time handling */ protected ControlledTimeService getTimeService() { return new ControlledTimeService(); } /** * Overridden in stores which accept only certain value types */ protected Object wrap(String key, String value) { return value; } /** * Overridden in stores which accept only certain value types */ protected String unwrap(Object wrapped) { return (String) wrapped; } public void testLoadAndStoreImmortal() throws PersistenceException { assertIsEmpty(); cl.write(marshalledEntry("k", "v")); MarshallableEntry entry = cl.loadEntry("k"); assertEquals("v", unwrap(entry.getValue())); assertTrue("Expected an immortalEntry", entry.getMetadata() == null || entry.expiryTime() == -1 || entry.getMetadata().maxIdle() == -1); assertContains("k", true); assertFalse(cl.delete("k2")); } public void testLoadAndStoreWithLifespan() throws Exception { assertIsEmpty(); long lifespan = 120000; InternalCacheEntry se = internalCacheEntry("k", "v", lifespan); assertExpired(se, false); cl.write(marshalledEntry(se)); assertContains("k", true); assertCorrectExpiry(cl.loadEntry("k"), "v", lifespan, -1, false); assertCorrectExpiry(TestingUtil.allEntries(cl).iterator().next(), "v", lifespan, -1, false); timeService.advance(lifespan + 1); lifespan = 2000; se = internalCacheEntry("k", "v", lifespan); assertExpired(se, false); cl.write(marshalledEntry(se)); timeService.advance(lifespan + 1); purgeExpired("k"); assertExpired(se, true); assertEventuallyExpires("k"); assertContains("k", false); assertIsEmpty(); } private void assertCorrectExpiry(MarshallableEntry me, String value, long lifespan, long maxIdle, boolean expired) { assertNotNull(String.valueOf(me), me); assertEquals(me + ".getValue()", value, unwrap(me.getValue())); if (lifespan > -1) { assertNotNull(me + ".getMetadata()", me.getMetadata()); assertEquals(me + ".getMetadata().lifespan()", lifespan, me.getMetadata().lifespan()); assertTrue(me + ".created() > -1", me.created() > -1); } if (maxIdle > -1) { assertNotNull(me + ".getMetadata()", me.getMetadata()); assertEquals(me + ".getMetadata().maxIdle()", maxIdle, me.getMetadata().maxIdle()); assertTrue(me + ".lastUsed() > -1", me.lastUsed() > -1); } if (me.getMetadata() != null) { assertEquals(me + ".isExpired() ", expired, me.isExpired(timeService.wallClockTime())); } } public void testLoadAndStoreWithIdle() throws Exception { assertIsEmpty(); long idle = 120000; InternalCacheEntry se = internalCacheEntry("k", "v", -1, idle); assertExpired(se, false); cl.write(marshalledEntry(se)); assertContains("k", true); assertCorrectExpiry(cl.loadEntry("k"), "v", -1, idle, false); assertCorrectExpiry(TestingUtil.allEntries(cl).iterator().next(), "v", -1, idle, false); timeService.advance(idle + 1); idle = 1000; se = internalCacheEntry("k", "v", -1, idle); assertExpired(se, false); cl.write(marshalledEntry(se)); timeService.advance(idle + 1); purgeExpired("k"); assertExpired(se, true); assertEventuallyExpires("k"); assertContains("k", false); assertIsEmpty(); } private void assertIsEmpty() { assertEmpty(TestingUtil.allEntries(cl), true); } protected void assertEventuallyExpires(final String key) throws Exception { eventually(() -> cl.loadEntry(key) == null); } /* Override if the store cannot purge all expired entries upon request */ protected boolean storePurgesAllExpired() { return true; } protected void purgeExpired(String... expiredKeys) throws Exception { final Set<String> expired = new HashSet<>(Arrays.asList(expiredKeys)); final Set<Object> incorrect = new HashSet<>(); if (cl instanceof AdvancedCacheExpirationWriter) { final AdvancedCacheExpirationWriter.ExpirationPurgeListener purgeListener = new AdvancedCacheExpirationWriter.ExpirationPurgeListener() { @Override public void marshalledEntryPurged(MarshallableEntry entry) { Object key = entry.getKey(); if (!expired.remove(key)) { incorrect.add(key); } } @Override public void entryPurged(Object key) { if (!expired.remove(key)) { incorrect.add(key); } } }; ((AdvancedCacheExpirationWriter) cl).purge(new WithinThreadExecutor(), purgeListener); } else { //noinspection unchecked cl.purge(new WithinThreadExecutor(), key -> { if (!expired.remove(key)) incorrect.add(key); }); } assertEmpty(incorrect, true); assertTrue(expired.isEmpty() || !storePurgesAllExpired()); assertEquals(Collections.emptySet(), incorrect); } public void testLoadAndStoreWithLifespanAndIdle() throws Exception { assertIsEmpty(); long lifespan = 200000; long idle = 120000; InternalCacheEntry se = internalCacheEntry("k", "v", lifespan, idle); InternalCacheValue icv = se.toInternalCacheValue(); assertEquals(se.getCreated(), icv.getCreated()); assertEquals(se.getLastUsed(), icv.getLastUsed()); assertExpired(se, false); cl.write(marshalledEntry(se)); assertContains("k", true); assertCorrectExpiry(cl.loadEntry("k"), "v", lifespan, idle, false); assertCorrectExpiry(TestingUtil.allEntries(cl).iterator().next(), "v", lifespan, idle, false); timeService.advance(idle + 1); idle = 1000; lifespan = 4000; se = internalCacheEntry("k", "v", lifespan, idle); assertExpired(se, false); cl.write(marshalledEntry(se)); timeService.advance(idle + 1); purgeExpired("k"); assertExpired(se, true); //expired by idle assertEventuallyExpires("k"); assertContains("k", false); assertIsEmpty(); } public void testLoadAndStoreWithLifespanAndIdle2() throws Exception { assertContains("k", false); long lifespan = 2000; long idle = 2000; InternalCacheEntry se = internalCacheEntry("k", "v", lifespan, idle); InternalCacheValue icv = se.toInternalCacheValue(); assertEquals(se.getCreated(), icv.getCreated()); assertEquals(se.getLastUsed(), icv.getLastUsed()); assertExpired(se, false); cl.write(marshalledEntry(se)); assertContains("k", true); assertCorrectExpiry(cl.loadEntry("k"), "v", lifespan, idle, false); assertCorrectExpiry(TestingUtil.allEntries(cl).iterator().next(), "v", lifespan, idle, false); idle = 4000; lifespan = 2000; se = internalCacheEntry("k", "v", lifespan, idle); assertExpired(se, false); cl.write(marshalledEntry(se)); timeService.advance(lifespan + 1); assertExpired(se, true); //expired by lifespan purgeExpired("k"); assertEventuallyExpires("k"); assertContains("k", false); assertIsEmpty(); } public void testStopStartDoesNotNukeValues() throws InterruptedException, PersistenceException { assertIsEmpty(); long lifespan = 1000; long idle = 1000; InternalCacheEntry se1 = internalCacheEntry("k1", "v1", lifespan); InternalCacheEntry se2 = internalCacheEntry("k2", "v2", -1); InternalCacheEntry se3 = internalCacheEntry("k3", "v3", -1, idle); InternalCacheEntry se4 = internalCacheEntry("k4", "v4", lifespan, idle); assertExpired(se1, false); assertExpired(se2, false); assertExpired(se3, false); assertExpired(se4, false); cl.write(marshalledEntry(se1)); cl.write(marshalledEntry(se2)); cl.write(marshalledEntry(se3)); cl.write(marshalledEntry(se4)); timeService.advance(lifespan + 1); assertExpired(se1, true); assertExpired(se2, false); assertExpired(se3, true); assertExpired(se4, true); cl.stop(); cl.start(); assertExpired(se1, true); assertNull(cl.loadEntry("k1")); assertContains("k1", false); assertExpired(se2, false); assertNotNull(cl.loadEntry("k2")); assertContains("k2", true); assertEquals("v2", unwrap(cl.loadEntry("k2").getValue())); assertExpired(se3, true); assertNull(cl.loadEntry("k3")); assertContains("k3", false); assertExpired(se4, true); assertNull(cl.loadEntry("k4")); assertContains("k4", false); } public void testPreload() throws Exception { assertIsEmpty(); cl.write(marshalledEntry("k1", "v1")); cl.write(marshalledEntry("k2", "v2")); cl.write(marshalledEntry("k3", "v3")); Set<MarshallableEntry<Object, Object>> set = TestingUtil.allEntries(cl); assertSize(set, 3); Set<String> expected = new HashSet<>(Arrays.asList("k1", "k2", "k3")); for (MarshallableEntry se : set) { assertTrue(expected.remove(se.getKey())); } assertEmpty(expected, true); } public void testStoreAndRemove() throws PersistenceException { assertIsEmpty(); cl.write(marshalledEntry("k1", "v1")); cl.write(marshalledEntry("k2", "v2")); cl.write(marshalledEntry("k3", "v3")); cl.write(marshalledEntry("k4", "v4")); Set<MarshallableEntry<Object, Object>> set = TestingUtil.allEntries(cl); assertSize(set, 4); Set<String> expected = new HashSet<>(Arrays.asList("k1", "k2", "k3", "k4")); for (MarshallableEntry se : set) { assertTrue(expected.remove(se.getKey())); } assertEmpty(expected, true); cl.delete("k1"); cl.delete("k2"); cl.delete("k3"); set = TestingUtil.allEntries(cl); assertSize(set, 1); assertEquals("k4", set.iterator().next().getKey()); assertEquals(1, PersistenceUtil.toKeySet(cl, null).size()); assertEquals(1, Flowable.fromPublisher(cl.publishKeys(null)).count().blockingGet().intValue()); } public void testPurgeExpired() throws Exception { assertIsEmpty(); // Increased lifespan and idle timeouts to accommodate slower cache stores // checking if cache store contains the entry right after inserting because // some slower cache stores (seen on DB2) don't manage to entry all the entries // before running out of lifespan making this test unpredictably fail on them. long lifespan = 7000; long idle = 2000; InternalCacheEntry ice1 = internalCacheEntry("k1", "v1", lifespan); cl.write(marshalledEntry(ice1)); assertContains("k1", true); InternalCacheEntry ice2 = internalCacheEntry("k2", "v2", -1, idle); cl.write(marshalledEntry(ice2)); assertContains("k2", true); InternalCacheEntry ice3 = internalCacheEntry("k3", "v3", lifespan, idle); cl.write(marshalledEntry(ice3)); assertContains("k3", true); InternalCacheEntry ice4 = internalCacheEntry("k4", "v4", -1, -1); cl.write(marshalledEntry(ice4)); // immortal entry assertContains("k4", true); InternalCacheEntry ice5 = internalCacheEntry("k5", "v5", lifespan * 1000, idle * 1000); cl.write(marshalledEntry(ice5)); // long life mortal entry assertContains("k5", true); timeService.advance(lifespan + 1); // Make sure we don't report that we contain these values assertContains("k1", false); assertContains("k2", false); assertContains("k3", false); assertContains("k4", true); assertContains("k5", true); purgeExpired("k1", "k2", "k3"); assertContains("k1", false); assertContains("k2", false); assertContains("k3", false); assertContains("k4", true); assertContains("k5", true); } public void testLoadAll() throws PersistenceException { assertIsEmpty(); cl.write(marshalledEntry("k1", "v1")); cl.write(marshalledEntry("k2", "v2")); cl.write(marshalledEntry("k3", "v3")); cl.write(marshalledEntry("k4", "v4")); cl.write(marshalledEntry("k5", "v5")); Set<MarshallableEntry<Object, Object>> s = TestingUtil.allEntries(cl); assertSize(s, 5); s = allEntries(cl, k -> true); assertSize(s, 5); s = allEntries(cl, k -> !"k3".equals(k)); assertSize(s, 4); for (MarshallableEntry me : s) { assertFalse(me.getKey().equals("k3")); } } public void testReplaceEntry() { assertIsEmpty(); InternalCacheEntry ice = internalCacheEntry("k1", "v1", -1); cl.write(marshalledEntry(ice)); assertEquals("v1", unwrap(cl.loadEntry("k1").getValue())); InternalCacheEntry ice2 = internalCacheEntry("k1", "v2", -1); cl.write(marshalledEntry(ice2)); assertEquals("v2", unwrap(cl.loadEntry("k1").getValue())); } public void testReplaceExpiredEntry() throws Exception { assertIsEmpty(); final long lifespan = 3000; InternalCacheEntry ice = internalCacheEntry("k1", "v1", lifespan); assertExpired(ice, false); cl.write(marshalledEntry(ice)); assertEquals("v1", unwrap(cl.loadEntry("k1").getValue())); timeService.advance(lifespan + 1); assertExpired(ice, true); assertNull(cl.loadEntry("k1")); InternalCacheEntry ice2 = internalCacheEntry("k1", "v2", lifespan); assertExpired(ice2, false); cl.write(marshalledEntry(ice2)); assertEquals("v2", unwrap(cl.loadEntry("k1").getValue())); timeService.advance(lifespan + 1); assertExpired(ice2, true); assertNull(cl.loadEntry("k1")); } public void testLoadAndStoreBytesValues() throws PersistenceException, IOException, InterruptedException { assertIsEmpty(); SerializationContext ctx = ProtobufUtil.newSerializationContext(); SerializationContextInitializer sci = TestDataSCI.INSTANCE; sci.registerSchema(ctx); sci.registerMarshallers(ctx); Marshaller userMarshaller = new ProtoStreamMarshaller(ctx); WrappedBytes key = new WrappedByteArray(userMarshaller.objectToByteBuffer(new Key("key"))); WrappedBytes key2 = new WrappedByteArray(userMarshaller.objectToByteBuffer(new Key("key2"))); WrappedBytes value = new WrappedByteArray(userMarshaller.objectToByteBuffer(new Person())); assertFalse(cl.contains(key)); PersistenceMarshaller persistenceMarshaller = getMarshaller(); cl.write(MarshalledEntryUtil.create(key, value, persistenceMarshaller)); assertEquals(value, cl.loadEntry(key).getValue()); MarshallableEntry entry = cl.loadEntry(key); assertTrue("Expected an immortalEntry", entry.getMetadata() == null || entry.expiryTime() == -1 || entry.getMetadata().maxIdle() == -1); assertContains(key, true); assertFalse(cl.delete(key2)); assertTrue(cl.delete(key)); } public void testWriteAndDeleteBatch() { // Number of entries is randomized to even numbers between 80 and 120 int numberOfEntries = 2 * ThreadLocalRandom.current().nextInt(WRITE_DELETE_BATCH_MIN_ENTRIES / 2, WRITE_DELETE_BATCH_MAX_ENTRIES / 2 + 1); testBatch(numberOfEntries, () -> cl.bulkUpdate(Flowable.range(0, numberOfEntries).map(i -> marshalledEntry(i.toString(), "Val" + i)))); } public void testWriteAndDeleteBatchIterable() { // Number of entries is randomized to even numbers between 80 and 120 int numberOfEntries = 2 * ThreadLocalRandom.current().nextInt(WRITE_DELETE_BATCH_MIN_ENTRIES / 2, WRITE_DELETE_BATCH_MAX_ENTRIES / 2 + 1); testBatch(numberOfEntries, () -> cl.bulkUpdate(Flowable.range(0, numberOfEntries).map(i -> marshalledEntry(i.toString(), "Val" + i)))); } public void testEmptyWriteAndDeleteBatchIterable() { assertIsEmpty(); assertNull("should not be present in the store", cl.loadEntry(0)); cl.bulkUpdate(Flowable.empty()); assertEquals(0, cl.size()); cl.deleteBatch(Collections.emptyList()); assertEquals(0, cl.size()); } private <R> void testBatch(int numberOfEntries, Runnable createBatch) { assertIsEmpty(); assertNull("should not be present in the store", cl.loadEntry(0)); createBatch.run(); Set<MarshallableEntry<Object, Object>> set = TestingUtil.allEntries(cl); assertSize(set, numberOfEntries); assertNotNull(cl.loadEntry("56")); int batchSize = numberOfEntries / 2; List<Object> keys = IntStream.range(0, batchSize).mapToObj(Integer::toString).collect(Collectors.toList()); cl.deleteBatch(keys); set = TestingUtil.allEntries(cl); assertSize(set, batchSize); assertNull(cl.loadEntry("20")); } public void testIsAvailable() { assertTrue(cl.isAvailable()); } protected final InitializationContext createContext(Configuration configuration) { return PersistenceMockUtil.createContext(getClass(), configuration, getMarshaller(), timeService); } protected final void assertContains(Object k, boolean expected) { assertEquals("contains(" + k + ")", expected, cl.contains(k)); } protected final InternalCacheEntry<Object, Object> internalCacheEntry(String key, String value, long lifespan) { return TestInternalCacheEntryFactory.create(factory, key, wrap(key, value), lifespan); } private InternalCacheEntry<Object, Object> internalCacheEntry(String key, String value, long lifespan, long idle) { return TestInternalCacheEntryFactory.create(factory, key, wrap(key, value), lifespan, idle); } private MarshallableEntry<Object, Object> marshalledEntry(String key, String value) { return MarshalledEntryUtil.create(key, wrap(key, value), getMarshaller()); } protected final MarshallableEntry<Object, Object> marshalledEntry(InternalCacheEntry entry) { //noinspection unchecked return MarshalledEntryUtil.create(entry, getMarshaller()); } private void assertSize(Collection<?> collection, int expected) { assertEquals(collection + ".size()", expected, collection.size()); } private void assertExpired(InternalCacheEntry entry, boolean expected) { assertEquals(entry + ".isExpired() ", expected, entry.isExpired(timeService.wallClockTime())); } private void assertEmpty(Collection<?> collection, boolean expected) { assertEquals(collection + ".isEmpty()", expected, collection.isEmpty()); } }
23,537
35.549689
146
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/MultiStoresFunctionalTest.java
package org.infinispan.persistence; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.infinispan.test.TestingUtil.withCacheManagers; import static org.testng.AssertJUnit.assertEquals; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.AbstractStoreConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.MultiCacheManagerCallable; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * This is a base functional test class for tests with multiple cache stores * * @author Michal Linhard (mlinhard@redhat.com) */ @Test(groups = "unit", testName = "persistence.MultiStoresFunctionalTest") public abstract class MultiStoresFunctionalTest<TStoreConfigurationBuilder extends AbstractStoreConfigurationBuilder<?, ?>> extends AbstractInfinispanTest { private static final long TIMEOUT = 10000; protected abstract TStoreConfigurationBuilder buildCacheStoreConfig(PersistenceConfigurationBuilder builder, String discriminator) throws Exception; /** * * Create n configs using cache store. sets passivation = false, purge = false, fetch persistent * state = true */ protected List<ConfigurationBuilder> configs(int n, Method method) throws Exception { List<ConfigurationBuilder> r = new ArrayList<ConfigurationBuilder>(n); for (int i = 0; i < n; i++) { ConfigurationBuilder configBuilder = new ConfigurationBuilder(); configBuilder.clustering().cacheMode(CacheMode.DIST_SYNC).hash().numOwners(2); buildCacheStoreConfig(configBuilder.persistence().passivation(false), method.getName() + i).purgeOnStartup(false).fetchPersistentState(true); r.add(configBuilder); } return r; } /** * when a node that persisted KEY wakes up, it can't rewrite existing value. */ public void testStartStopOfBackupDoesntRewriteValue(Method m) throws Exception { final List<ConfigurationBuilder> configs = configs(2, m); withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createClusteredCacheManager(configs.get(0)), TestCacheManagerFactory.createClusteredCacheManager(configs.get(1))) { @Override public void call() { final EmbeddedCacheManager cacheManager0 = cms[0]; final EmbeddedCacheManager cacheManager1 = cms[1]; final Cache<String, String> cache0 = cacheManager0.getCache(); final Cache<String, String> cache1 = cacheManager1.getCache(); TestingUtil.blockUntilViewsChanged(TIMEOUT, 2, cache0, cache1); cache0.put("KEY", "VALUE V1"); assertEquals("VALUE V1", cache1.get("KEY")); TestingUtil.killCacheManagers(cacheManager1); TestingUtil.blockUntilViewsChanged(TIMEOUT, 1, cache0); cache0.put("KEY", "VALUE V2"); assertEquals("VALUE V2", cache0.get("KEY")); withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.createClusteredCacheManager(configs.get(1))) { @Override public void call() { Cache<String, String> newCache = cm.getCache(); TestingUtil.blockUntilViewsChanged(TIMEOUT, 2, cache0, newCache); assertEquals("VALUE V2", newCache.get("KEY")); } }); } }); } /** * When node that persisted KEY2 it will resurrect previous value of KEY2. */ public void testStartStopOfBackupResurrectsDeletedKey(Method m) throws Exception { final List<ConfigurationBuilder> configs = configs(2, m); withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createClusteredCacheManager(configs.get(0)), TestCacheManagerFactory.createClusteredCacheManager(configs.get(1))) { @Override public void call() { final EmbeddedCacheManager cacheManager0 = cms[0]; final EmbeddedCacheManager cacheManager1 = cms[1]; final Cache<String, String> cache0 = cacheManager0.getCache(); final Cache<String, String> cache1 = cacheManager1.getCache(); TestingUtil.blockUntilViewsChanged(TIMEOUT, 2, cache0, cache1); cache0.put("KEY2", "VALUE2 V1"); assertEquals("VALUE2 V1", cache1.get("KEY2")); TestingUtil.killCacheManagers(cacheManager1); TestingUtil.blockUntilViewsChanged(TIMEOUT, 1, cache0); cache0.put("KEY2", "VALUE2 V2"); assertEquals("VALUE2 V2", cache0.get("KEY2")); cache0.remove("KEY2"); assertEquals(null, cache0.get("KEY2")); withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.createClusteredCacheManager(configs.get(1))) { @Override public void call() { Cache<String, String> newCache = cm.getCache(); TestingUtil.blockUntilViewsChanged(TIMEOUT, 2, cache0, newCache); assertEquals("VALUE2 V1", newCache.get("KEY2")); } }); } }); } }
5,666
42.592308
156
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/PassivationOptionsTest.java
package org.infinispan.persistence; import java.util.stream.Stream; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.expiration.impl.CustomLoaderNonNullWithExpirationTest; import org.infinispan.manager.EmbeddedCacheManagerStartupException; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @Test(groups = "functional", testName = "persistence.PassivationOptionsTest") public class PassivationOptionsTest extends AbstractInfinispanTest { public void testPassivationWithLoader() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.persistence() .passivation(true) .addStore(CustomLoaderNonNullWithExpirationTest.SimpleLoaderConfigurationBuilder.class) .segmented(false); TestCacheManagerFactory.createCacheManager(builder); } @DataProvider(name = "passivationEnabled") public Object[][] maxIdlePassivationParams() { return Stream.of(Boolean.TRUE, Boolean.FALSE) .flatMap(passivationEnabled -> Stream.of(Boolean.TRUE, Boolean.FALSE) .map(maxIdleEnabled -> new Object[]{passivationEnabled, maxIdleEnabled})) .toArray(Object[][]::new); } @Test(dataProvider = "passivationEnabled") public void testPassivationWithMaxIdle(boolean passivationEnabled, boolean maxIdleEnabled) { ConfigurationBuilder builder = new ConfigurationBuilder(); if (maxIdleEnabled) { builder.expiration() .maxIdle(10); } builder.persistence() .passivation(passivationEnabled) .addStore(DummyInMemoryStoreConfigurationBuilder.class); try { TestCacheManagerFactory.createCacheManager(builder); } catch (Throwable t) { if (!passivationEnabled && maxIdleEnabled) { Exceptions.assertException(EmbeddedCacheManagerStartupException.class, CacheConfigurationException.class, ".*Max idle is not allowed.*", t); } else { throw t; } } } }
2,379
38.666667
152
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/BaseNonBlockingStoreTest.java
package org.infinispan.persistence; import static org.infinispan.test.TestingUtil.allEntries; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNotSame; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.marshall.WrappedBytes; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.entries.InternalCacheValue; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.container.impl.InternalEntryFactoryImpl; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.marshall.TestObjectStreamMarshaller; import org.infinispan.marshall.persistence.PersistenceMarshaller; import org.infinispan.marshall.persistence.impl.MarshalledEntryFactoryImpl; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.spi.CacheLoader; import org.infinispan.persistence.spi.CacheWriter; import org.infinispan.persistence.spi.InitializationContext; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.MarshallableEntryFactory; import org.infinispan.persistence.spi.NonBlockingStore; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.persistence.support.EnsureNonBlockingStore; import org.infinispan.persistence.support.NonBlockingStoreAdapter; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.data.Key; import org.infinispan.test.data.Person; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TestInternalCacheEntryFactory; import org.infinispan.util.ControlledTimeService; import org.infinispan.util.PersistenceMockUtil; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; /** * This is a base class containing various unit tests for each and every different CacheStore implementations. If you * need to add Cache/CacheManager tests that need to be run for each cache store/loader implementation, then use * BaseStoreFunctionalTest. */ @Test(groups = "unit", testName = "persistence.BaseNonBlockingStoreTest") public abstract class BaseNonBlockingStoreTest extends AbstractInfinispanTest { protected static final int WRITE_DELETE_BATCH_MIN_ENTRIES = Flowable.bufferSize() * 2; protected static final int WRITE_DELETE_BATCH_MAX_ENTRIES = WRITE_DELETE_BATCH_MIN_ENTRIES + 40; protected TestObjectStreamMarshaller marshaller; protected EnsureNonBlockingStore<Object, Object> store; protected ControlledTimeService timeService; protected InternalEntryFactory internalEntryFactory; protected MarshallableEntryFactory<?, ?> marshallableEntryFactory; protected Configuration configuration; protected int segmentCount; protected InitializationContext initializationContext; protected KeyPartitioner keyPartitioner = k -> Math.abs(k.hashCode() % segmentCount); protected Set<NonBlockingStore.Characteristic> characteristics; protected IntSet segments; protected static <K, V> NonBlockingStore<K, V> asNonBlockingStore(CacheLoader<K, V> loader) { return new NonBlockingStoreAdapter<>(loader); } protected static <K, V> NonBlockingStore<K, V> asNonBlockingStore(CacheWriter<K, V> writer) { return new NonBlockingStoreAdapter<>(writer); } protected abstract NonBlockingStore<Object, Object> createStore() throws Exception; protected abstract Configuration buildConfig(ConfigurationBuilder configurationBuilder); //alwaysRun = true otherwise, when we run unstable tests, this method is not invoked (because it belongs to the unit group) @BeforeMethod(alwaysRun = true) public void setUp() throws Exception { marshaller = new TestObjectStreamMarshaller(getSerializationContextInitializer()); timeService = getTimeService(); internalEntryFactory = new InternalEntryFactoryImpl(); TestingUtil.inject(internalEntryFactory, timeService); marshallableEntryFactory = new MarshalledEntryFactoryImpl(); TestingUtil.inject(marshallableEntryFactory, marshaller); try { NonBlockingStore<Object, Object> nonBlockingStore = createStore(); // Make sure all store methods don't block when we invoke them store = new EnsureNonBlockingStore<>(nonBlockingStore, keyPartitioner); startStore(store); } catch (Exception e) { log.error("Error creating store", e); throw e; } } protected void startStore(EnsureNonBlockingStore<?, ?> store) { // Reuse the same configuration between restarts if (configuration == null) { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); // Do one more than the buffer size to find issues with groupBy not being subscribed to properly builder.clustering().hash().numSegments(Flowable.bufferSize() + 20); setConfiguration(buildConfig(builder)); } store.startAndWait(createContext(configuration)); characteristics = store.characteristics(); } protected Object keyToStorage(Object key) { return key; } protected Object valueToStorage(Object value) { return value; } protected void setConfiguration(Configuration configuration) { this.configuration = configuration; this.segmentCount = configuration.clustering().hash().numSegments(); segments = IntSets.immutableRangeSet(segmentCount); } //alwaysRun = true otherwise, when we run unstable tests, this method is not invoked (because it belongs to the unit group) @AfterMethod(alwaysRun = true) public void tearDown() throws PersistenceException { try { if (store != null) { store.clearAndWait(); store.stopAndWait(); } if (marshaller != null) { marshaller.stop(); } } finally { store = null; } } /** * @return a mock marshaller for use with the cache store impls */ protected PersistenceMarshaller getMarshaller() { return marshaller; } /** * @return the {@link SerializationContextInitializer} used to initiate the user marshaller */ protected SerializationContextInitializer getSerializationContextInitializer() { return TestDataSCI.INSTANCE; } /** * To be overridden if the store requires special time handling */ protected ControlledTimeService getTimeService() { return new ControlledTimeService(); } /** * Overridden in stores which accept only certain value types */ protected Object wrap(Object key, Object value) { return value; } public void testLoadAndStoreImmortal() throws PersistenceException { assertIsEmpty(); store.write(marshalledEntry("k", "v")); MarshallableEntry<?, ?> entry = store.loadEntry(keyToStorage("k")); assertEquals(valueToStorage("v"), entry.getValue()); assertTrue("Expected an immortalEntry", entry.getMetadata() == null || entry.expiryTime() == -1 || entry.getMetadata().maxIdle() == -1); assertContains("k", true); // The store may return null or FALSE but not TRUE assertNotSame(Boolean.TRUE, store.delete(keyToStorage("k2"))); } public void testLoadAndStoreWithLifespan() throws Exception { // Store doesn't support expiration, so don't test it if (!characteristics.contains(NonBlockingStore.Characteristic.EXPIRATION)) { return; } assertIsEmpty(); long lifespan = 120000; InternalCacheEntry<Object, Object> se = internalCacheEntry("k", "v", lifespan); assertExpired(se, false); store.write(marshalledEntry(se)); assertContains("k", true); assertCorrectExpiry(store.loadEntry(keyToStorage("k")), "v", lifespan, -1, false); assertCorrectExpiry(TestingUtil.allEntries(store, segments).iterator().next(), "v", lifespan, -1, false); timeService.advance(lifespan + 1); lifespan = 2000; se = internalCacheEntry("k", "v", lifespan); assertExpired(se, false); store.write(marshalledEntry(se)); timeService.advance(lifespan + 1); purgeExpired(se); assertExpired(se, true); assertEventuallyExpires("k"); assertContains("k", false); assertIsEmpty(); } private void assertCorrectExpiry(MarshallableEntry<?, ?> me, String value, long lifespan, long maxIdle, boolean expired) { assertNotNull(String.valueOf(me), me); assertEquals(me + ".getValue()", valueToStorage(value), me.getValue()); if (lifespan > -1) { assertNotNull(me + ".getMetadata()", me.getMetadata()); assertEquals(me + ".getMetadata().lifespan()", lifespan, me.getMetadata().lifespan()); assertTrue(me + ".created() > -1", me.created() > -1); } if (maxIdle > -1) { assertNotNull(me + ".getMetadata()", me.getMetadata()); assertEquals(me + ".getMetadata().maxIdle()", maxIdle, me.getMetadata().maxIdle()); assertTrue(me + ".lastUsed() > -1", me.lastUsed() > -1); } if (me.getMetadata() != null) { assertEquals(me + ".isExpired() ", expired, me.isExpired(timeService.wallClockTime())); } } public void testLoadAndStoreWithIdle() throws Exception { // Store doesn't support expiration, so don't test it if (!characteristics.contains(NonBlockingStore.Characteristic.EXPIRATION)) { return; } assertIsEmpty(); long idle = 120000; InternalCacheEntry<Object, Object> se = internalCacheEntry("k", "v", -1, idle); assertExpired(se, false); store.write(marshalledEntry(se)); assertContains("k", true); assertCorrectExpiry(store.loadEntry(keyToStorage("k")), "v", -1, idle, false); assertCorrectExpiry(TestingUtil.allEntries(store, segments).iterator().next(), "v", -1, idle, false); timeService.advance(idle + 1); idle = 1000; se = internalCacheEntry("k", "v", -1, idle); assertExpired(se, false); store.write(marshalledEntry(se)); timeService.advance(idle + 1); purgeExpired(se); assertExpired(se, true); assertEventuallyExpires("k"); assertContains("k", false); assertIsEmpty(); } private void assertIsEmpty() { assertEmpty(TestingUtil.allEntries(store, segments), true); } protected void assertEventuallyExpires(final String key) throws Exception { Object storageKey = keyToStorage(key); eventually(() -> store.loadEntry(storageKey) == null); } /* Override if the store cannot purge all expired entries upon request */ protected boolean storePurgesAllExpired() { return true; } protected void purgeExpired(InternalCacheEntry... expiredEntries) { List<MarshallableEntry<Object, Object>> expiredList = store.purge(); if (storePurgesAllExpired()) { assertEquals(expiredEntries.length, expiredList.size()); } for (InternalCacheEntry ice : expiredEntries) { Object key = keyToStorage(ice.getKey()); Object value = valueToStorage(ice.getValue()); // This is technically O(n^2) worst case, but the arrays should be small and this is a test expiredList.removeIf(me -> me.getKey().equals(key) && me.getValue().equals(value)); } assertEmpty(expiredList, true); } public void testLoadAndStoreWithLifespanAndIdle() throws Exception { // Store doesn't support expiration, so don't test it if (!characteristics.contains(NonBlockingStore.Characteristic.EXPIRATION)) { return; } assertIsEmpty(); long lifespan = 200000; long idle = 120000; InternalCacheEntry<Object, Object> se = internalCacheEntry("k", "v", lifespan, idle); InternalCacheValue<?> icv = se.toInternalCacheValue(); assertEquals(se.getCreated(), icv.getCreated()); assertEquals(se.getLastUsed(), icv.getLastUsed()); assertExpired(se, false); store.write(marshalledEntry(se)); assertContains("k", true); assertCorrectExpiry(store.loadEntry(keyToStorage("k")), "v", lifespan, idle, false); assertCorrectExpiry(TestingUtil.allEntries(store, segments).iterator().next(), "v", lifespan, idle, false); timeService.advance(idle + 1); idle = 1000; lifespan = 4000; se = internalCacheEntry("k", "v", lifespan, idle); assertExpired(se, false); store.write(marshalledEntry(se)); timeService.advance(idle + 1); purgeExpired(se); assertExpired(se, true); //expired by idle assertEventuallyExpires("k"); assertContains("k", false); assertIsEmpty(); } public void testLoadAndStoreWithLifespanAndIdle2() throws Exception { // Store doesn't support expiration, so don't test it if (!characteristics.contains(NonBlockingStore.Characteristic.EXPIRATION)) { return; } assertContains("k", false); long lifespan = 2000; long idle = 2000; InternalCacheEntry<Object, Object> se = internalCacheEntry("k", "v", lifespan, idle); InternalCacheValue<?> icv = se.toInternalCacheValue(); assertEquals(se.getCreated(), icv.getCreated()); assertEquals(se.getLastUsed(), icv.getLastUsed()); assertExpired(se, false); store.write(marshalledEntry(se)); assertContains("k", true); assertCorrectExpiry(store.loadEntry(keyToStorage("k")), "v", lifespan, idle, false); assertCorrectExpiry(TestingUtil.allEntries(store, segments).iterator().next(), "v", lifespan, idle, false); idle = 4000; lifespan = 2000; se = internalCacheEntry("k", "v", lifespan, idle); assertExpired(se, false); store.write(marshalledEntry(se)); timeService.advance(lifespan + 1); assertExpired(se, true); //expired by lifespan purgeExpired(se); assertEventuallyExpires("k"); assertContains("k", false); assertIsEmpty(); } public void testStopStartDoesNotNukeValues() throws InterruptedException, PersistenceException { assertIsEmpty(); long lifespan = 1000; long idle = 1000; InternalCacheEntry<Object, Object> se1 = internalCacheEntry("k1", "v1", lifespan); InternalCacheEntry<Object, Object> se2 = internalCacheEntry("k2", "v2", -1); InternalCacheEntry<Object, Object> se3 = internalCacheEntry("k3", "v3", -1, idle); InternalCacheEntry<Object, Object> se4 = internalCacheEntry("k4", "v4", lifespan, idle); assertExpired(se1, false); assertExpired(se2, false); assertExpired(se3, false); assertExpired(se4, false); store.write(marshalledEntry(se1)); store.write(marshalledEntry(se2)); store.write(marshalledEntry(se3)); store.write(marshalledEntry(se4)); timeService.advance(lifespan + 1); assertExpired(se1, true); assertExpired(se2, false); assertExpired(se3, true); assertExpired(se4, true); store.stopAndWait(); startStore(store); assertExpired(se1, true); assertNull(store.loadEntry(keyToStorage("k1"))); assertContains("k1", false); assertExpired(se2, false); assertNotNull(store.loadEntry(keyToStorage("k2"))); assertContains("k2", true); assertEquals(valueToStorage("v2"), store.loadEntry(keyToStorage("k2")).getValue()); assertExpired(se3, true); assertNull(store.loadEntry(keyToStorage("k3"))); assertContains("k3", false); assertExpired(se4, true); assertNull(store.loadEntry(keyToStorage("k4"))); assertContains("k4", false); } public void testPreload() throws Exception { assertIsEmpty(); store.write(marshalledEntry("k1", "v1")); store.write(marshalledEntry("k2", "v2")); store.write(marshalledEntry("k3", "v3")); Set<MarshallableEntry<Object, Object>> set = TestingUtil.allEntries(store, segments); assertSize(set, 3); Set<Object> expected = Stream.of("k1", "k2", "k3") .map(this::keyToStorage) .collect(Collectors.toSet()); for (MarshallableEntry<?, ?> se : set) { assertTrue(expected.remove(se.getKey())); } assertEmpty(expected, true); } public void testStoreAndRemove() throws PersistenceException { assertIsEmpty(); store.write(marshalledEntry("k1", "v1")); store.write(marshalledEntry("k2", "v2")); store.write(marshalledEntry("k3", "v3")); store.write(marshalledEntry("k4", "v4")); Set<MarshallableEntry<Object, Object>> set = TestingUtil.allEntries(store, segments); assertSize(set, 4); Set<Object> expected = Stream.of("k1", "k2", "k3", "k4") .map(this::keyToStorage) .collect(Collectors.toSet()); for (MarshallableEntry<?, ?> se : set) { assertTrue(expected.remove(se.getKey())); } assertEmpty(expected, true); store.delete(keyToStorage("k1")); store.delete(keyToStorage("k2")); store.delete(keyToStorage("k3")); set = TestingUtil.allEntries(store, segments); assertSize(set, 1); assertEquals(keyToStorage("k4"), set.iterator().next().getKey()); assertEquals(1, store.publishKeysWait(segments, null).size()); } public void testApproximateSize() { assertIsEmpty(); int numKeysPerSegment = 2; int numKeys = numKeysPerSegment * segmentCount; for (int i = 0; i < numKeys; i++) { String key = "k" + i; store.write(marshalledEntry(key, "v" + i)); } assertEquals(numKeys, store.approximateSizeWait(segments)); if (configuration.persistence().stores().get(0).segmented()) { int totalSize = 0; for (int s = 0; s < segmentCount; s++) { totalSize += store.approximateSizeWait(IntSets.immutableSet(s)); } assertEquals(numKeys, totalSize); } } public void testPurgeExpired() throws Exception { // Store doesn't support expiration, so don't test it if (!characteristics.contains(NonBlockingStore.Characteristic.EXPIRATION)) { return; } assertIsEmpty(); // Increased lifespan and idle timeouts to accommodate slower cache stores // checking if cache store contains the entry right after inserting because // some slower cache stores (seen on DB2) don't manage to entry all the entries // before running out of lifespan making this test unpredictably fail on them. long lifespan = 7000; long idle = 2000; InternalCacheEntry<Object, Object> ice1 = internalCacheEntry("k1", "v1", lifespan); store.write(marshalledEntry(ice1)); assertContains("k1", true); InternalCacheEntry<Object, Object> ice2 = internalCacheEntry("k2", "v2", -1, idle); store.write(marshalledEntry(ice2)); assertContains("k2", true); InternalCacheEntry<Object, Object> ice3 = internalCacheEntry("k3", "v3", lifespan, idle); store.write(marshalledEntry(ice3)); assertContains("k3", true); InternalCacheEntry<Object, Object> ice4 = internalCacheEntry("k4", "v4", -1, -1); store.write(marshalledEntry(ice4)); // immortal entry assertContains("k4", true); InternalCacheEntry<Object, Object> ice5 = internalCacheEntry("k5", "v5", lifespan * 1000, idle * 1000); store.write(marshalledEntry(ice5)); // long life mortal entry assertContains("k5", true); timeService.advance(lifespan + 1); // Make sure we don't report that we contain these values assertContains("k1", false); assertContains("k2", false); assertContains("k3", false); assertContains("k4", true); assertContains("k5", true); purgeExpired(ice1, ice2, ice3); assertContains("k1", false); assertContains("k2", false); assertContains("k3", false); assertContains("k4", true); assertContains("k5", true); } public void testLoadAll() throws PersistenceException { assertIsEmpty(); store.write(marshalledEntry("k1", "v1")); store.write(marshalledEntry("k2", "v2")); store.write(marshalledEntry("k3", "v3")); store.write(marshalledEntry("k4", "v4")); store.write(marshalledEntry("k5", "v5")); Set<MarshallableEntry<Object, Object>> s = allEntries(store, segments); assertSize(s, 5); s = allEntries(store, segments, k -> true); assertSize(s, 5); Object storedK3 = keyToStorage("k3"); s = allEntries(store, segments, k -> !storedK3.equals(k)); assertSize(s, 4); for (MarshallableEntry<?, ?> me : s) { assertFalse(me.getKey().equals(storedK3)); } } public void testReplaceEntry() { assertIsEmpty(); InternalCacheEntry tmpIce = internalCacheEntry("ok", "v1", -1); store.write(marshalledEntry(tmpIce)); InternalCacheEntry<Object, Object> ice = internalCacheEntry("k1", "v1", -1); store.write(marshalledEntry(ice)); assertEquals(valueToStorage("v1"), store.loadEntry(keyToStorage("k1")).getValue()); InternalCacheEntry<Object, Object> ice2 = internalCacheEntry("k1", "v2", -1); store.write(marshalledEntry(ice2)); assertEquals(valueToStorage("v2"), store.loadEntry(keyToStorage("k1")).getValue()); } public void testReplaceExpiredEntry() throws Exception { assertIsEmpty(); final long lifespan = 3000; InternalCacheEntry<Object, Object> ice = internalCacheEntry("k1", "v1", lifespan); assertExpired(ice, false); store.write(marshalledEntry(ice)); Object storedKey = keyToStorage("k1"); assertEquals("v1", store.loadEntry(storedKey).getValue()); timeService.advance(lifespan + 1); assertExpired(ice, true); assertNull(store.loadEntry(storedKey)); InternalCacheEntry<Object, Object> ice2 = internalCacheEntry("k1", "v2", lifespan); assertExpired(ice2, false); store.write(marshalledEntry(ice2)); assertEquals(valueToStorage("v2"), store.loadEntry(storedKey).getValue()); timeService.advance(lifespan + 1); assertExpired(ice2, true); assertNull(store.loadEntry(storedKey)); } public void testLoadAndStoreBytesValues() throws PersistenceException, IOException, InterruptedException { assertIsEmpty(); SerializationContext ctx = ProtobufUtil.newSerializationContext(); SerializationContextInitializer sci = TestDataSCI.INSTANCE; sci.registerSchema(ctx); sci.registerMarshallers(ctx); Marshaller userMarshaller = new ProtoStreamMarshaller(ctx); WrappedBytes key = new WrappedByteArray(userMarshaller.objectToByteBuffer(new Key("key"))); WrappedBytes key2 = new WrappedByteArray(userMarshaller.objectToByteBuffer(new Key("key2"))); WrappedBytes value = new WrappedByteArray(userMarshaller.objectToByteBuffer(new Person())); assertFalse(store.contains(key)); PersistenceMarshaller persistenceMarshaller = getMarshaller(); store.write(MarshalledEntryUtil.create(key, value, persistenceMarshaller)); assertEquals(value, store.loadEntry(key).getValue()); MarshallableEntry<?, ?> entry = store.loadEntry(key); assertTrue("Expected an immortalEntry", entry.getMetadata() == null || entry.expiryTime() == -1 || entry.getMetadata().maxIdle() == -1); assertTrue(store.contains(key)); // Delete return value is optional // The store may return null or FALSE but not TRUE assertNotSame(Boolean.TRUE, store.delete(key2)); // The store may return null or TRUE but not FALSE assertNotSame(Boolean.FALSE, store.delete(key)); } public void testWriteAndDeleteBatch() { // Number of entries is randomized to even numbers between 80 and 120 int numberOfEntries = 2 * ThreadLocalRandom.current().nextInt(WRITE_DELETE_BATCH_MIN_ENTRIES / 2, WRITE_DELETE_BATCH_MAX_ENTRIES / 2 + 1); testBatch(numberOfEntries, () -> store.batchUpdate(segmentCount, Flowable.empty(), TestingUtil.multipleSegmentPublisher(Flowable.range(0, numberOfEntries).map(i -> marshalledEntry(i.toString(), "Val" + i)), MarshallableEntry::getKey, keyPartitioner))); } public void testEmptyWriteAndDeleteBatchIterable() { assertIsEmpty(); assertNull("should not be present in the store", store.loadEntry(keyToStorage(0))); store.batchUpdate(1, Flowable.empty(), Flowable.empty()); assertEquals(0, store.sizeWait(segments)); } private void testBatch(int numberOfEntries, Runnable createBatch) { assertIsEmpty(); assertNull("should not be present in the store", store.loadEntry(keyToStorage(0))); createBatch.run(); Set<MarshallableEntry<Object, Object>> set = TestingUtil.allEntries(store, segments); assertSize(set, numberOfEntries); assertNotNull(store.loadEntry(keyToStorage("56"))); int batchSize = numberOfEntries / 2; List<Object> keys = IntStream.range(0, batchSize).mapToObj(Integer::toString).map(this::keyToStorage).collect(Collectors.toList()); store.batchUpdate(segmentCount, TestingUtil.multipleSegmentPublisher(Flowable.fromIterable(keys), Function.identity(), keyPartitioner), Flowable.empty()); set = TestingUtil.allEntries(store, segments); assertSize(set, batchSize); assertNull(store.loadEntry(keyToStorage("20"))); } public void testIsAvailable() { assertTrue(store.checkAvailable()); } protected final InitializationContext createContext(Configuration configuration) { PersistenceMockUtil.InvocationContextBuilder builder = new PersistenceMockUtil.InvocationContextBuilder(getClass(), configuration, getMarshaller()) .setTimeService(timeService) .setKeyPartitioner(keyPartitioner); modifyInitializationContext(builder); initializationContext = builder.build(); return initializationContext; } protected void modifyInitializationContext(PersistenceMockUtil.InvocationContextBuilder contextBuilder) { // Default does nothing } protected final void assertContains(Object k, boolean expected) { Object transformedKey = keyToStorage(k); assertEquals("contains(" + transformedKey + ")", expected, store.contains(transformedKey)); } protected final <K> InternalCacheEntry<K, Object> internalCacheEntry(K key, Object value, long lifespan) { Object transformedKey = keyToStorage(key); Object transformedValue = valueToStorage(value); return TestInternalCacheEntryFactory.create(internalEntryFactory, (K) transformedKey, wrap(transformedKey, transformedValue), lifespan); } private InternalCacheEntry<Object, Object> internalCacheEntry(String key, String value, long lifespan, long idle) { Object transformedKey = keyToStorage(key); Object transformedValue = valueToStorage(value); return TestInternalCacheEntryFactory.create(internalEntryFactory, transformedKey, wrap(transformedKey, transformedValue), lifespan, idle); } private MarshallableEntry<Object, Object> marshalledEntry(String key, String value) { Object transformedKey = keyToStorage(key); Object transformedValue = valueToStorage(value); return MarshalledEntryUtil.create(transformedKey, wrap(transformedKey, transformedValue), getMarshaller()); } protected final MarshallableEntry<Object, Object> marshalledEntry(InternalCacheEntry<Object, Object> entry) { return MarshalledEntryUtil.create(entry, getMarshaller()); } private void assertSize(Collection<?> collection, int expected) { assertEquals(collection + ".size()", expected, collection.size()); } private void assertExpired(InternalCacheEntry<Object, Object> entry, boolean expected) { assertEquals(entry + ".isExpired() ", expected, entry.isExpired(timeService.wallClockTime())); } private void assertEmpty(Collection<?> collection, boolean expected) { assertEquals(collection + ".isEmpty()", expected, collection.isEmpty()); } }
29,311
38.610811
153
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/StoreConfigurationValidationTest.java
package org.infinispan.persistence; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.ConfigurationFor; import org.infinispan.commons.configuration.ConfiguredBy; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.persistence.Store; import org.infinispan.configuration.cache.AbstractStoreConfigurationBuilder; import org.infinispan.configuration.cache.AsyncStoreConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfiguration; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Unit test for ensuring that {@link AbstractStoreConfigurationBuilder#validate()} fails when expected. * * @author Ryan Emerson * @since 9.0 */ @Test(groups = "unit", testName = "persistence.StoreConfigurationValidationTest") public class StoreConfigurationValidationTest { @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = ".* NonSharedDummyInMemoryStore cannot be shared") public void testExceptionOnNonSharableStore() { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); builder.persistence() .addStore(NonSharedDummyStoreConfigurationBuilder.class) .shared(true) .validate(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = ".* It is not possible for a store to be transactional in a non-transactional cache. ") public void testTxStoreInNonTxCache() { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); builder.persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .transactional(true) .validate(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = ".* It is not possible for a store to be transactional when passivation is enabled. ") public void testTxStoreInPassivatedCache() { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(true); builder.persistence() .passivation(true) .addStore(DummyInMemoryStoreConfigurationBuilder.class) .transactional(true) .validate(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = ".* A store cannot be shared when utilised with a local cache.") public void testSharedStoreWithLocalCache() { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); builder.clustering() .cacheMode(CacheMode.LOCAL) .persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .shared(true) .validate(); } @Store @ConfiguredBy(NonSharedDummyStoreConfiguration.class) static class NonSharedDummyInMemoryStore extends DummyInMemoryStore { public NonSharedDummyInMemoryStore() { super(); } } @BuiltBy(NonSharedDummyStoreConfigurationBuilder.class) @ConfigurationFor(NonSharedDummyInMemoryStore.class) static class NonSharedDummyStoreConfiguration extends DummyInMemoryStoreConfiguration { public static AttributeSet attributeDefinitionSet() { return new AttributeSet(NonSharedDummyStoreConfiguration.class, DummyInMemoryStoreConfiguration.attributeDefinitionSet()); } NonSharedDummyStoreConfiguration(AttributeSet attributes, AsyncStoreConfiguration async) { super(attributes, async); } } public static class NonSharedDummyStoreConfigurationBuilder extends AbstractStoreConfigurationBuilder<NonSharedDummyStoreConfiguration, NonSharedDummyStoreConfigurationBuilder> { public NonSharedDummyStoreConfigurationBuilder(PersistenceConfigurationBuilder builder) { super(builder, NonSharedDummyStoreConfiguration.attributeDefinitionSet()); } @Override public NonSharedDummyStoreConfiguration create() { return new NonSharedDummyStoreConfiguration(attributes.protect(), async.create()); } @Override public NonSharedDummyStoreConfigurationBuilder self() { return this; } } }
4,784
42.108108
131
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/AbstractPersistenceCompatibilityTest.java
package org.infinispan.persistence; import static org.infinispan.persistence.PersistenceUtil.getQualifiedLocation; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import org.infinispan.Cache; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.data.Value; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Base compatibility test for cache stores. * * @author Pedro Ruivo * @since 11.0 */ public abstract class AbstractPersistenceCompatibilityTest<T> extends SingleCacheManagerTest { protected enum Version { _10_1, _11_0, _12_0, _12_1, } protected static final int NUMBER_KEYS = 10; protected final KeyValueWrapper<String, Value, T> valueWrapper; protected String tmpDirectory; protected Version oldVersion; protected boolean oldSegmented; protected boolean newSegmented; protected AbstractPersistenceCompatibilityTest(KeyValueWrapper<String, Value, T> valueWrapper) { this.valueWrapper = valueWrapper; this.cleanup = CleanupPhase.AFTER_METHOD; } protected String key(int index) { return "key-" + index; } protected Value value(int index) { String i = Integer.toString(index); return new Value(i, i); } protected static void copyFile(String src, Path dst, String fileName) throws IOException { InputStream is = FileLookupFactory.newInstance() .lookupFile(src, Thread.currentThread().getContextClassLoader()); File f = new File(dst.toFile(), fileName); Files.copy(is, f.toPath(), StandardCopyOption.REPLACE_EXISTING); } protected abstract void beforeStartCache() throws Exception; protected void setParameters(Version oldVersion, boolean oldSegmented, boolean newSegmented) { this.oldVersion = oldVersion; this.oldSegmented = oldSegmented; this.newSegmented = newSegmented; } protected void doTestReadWrite() throws Exception { // 10 keys // even keys stored, odd keys removed beforeStartCache(); cacheManager.defineConfiguration(cacheName(), cacheConfiguration(false).build()); Cache<String, T> cache = cacheManager.getCache(cacheName()); for (int i = 0; i < NUMBER_KEYS; ++i) { String key = key(i); if (i % 2 != 0) { assertNull("Expected null value for key " + key, cache.get(key)); } else { assertEquals("Wrong value read for key " + key, value(i), valueWrapper.unwrap(cache.get(key))); } } for (int i = 0; i < NUMBER_KEYS; ++i) { if (i % 2 != 0) { String key = key(i); cache.put(key, valueWrapper.wrap(key, value(i))); } } for (int i = 0; i < NUMBER_KEYS; ++i) { String key = key(i); assertEquals("Wrong value read for key " + key, value(i), valueWrapper.unwrap(cache.get(key))); } // Restart the CacheManager to ensure that the entries are still readable on restart cacheManager.stop(); try (EmbeddedCacheManager cm = createCacheManager()) { cm.defineConfiguration(cacheName(), cacheConfiguration(false).build()); cache = cm.getCache(cacheName()); for (int i = 0; i < NUMBER_KEYS; ++i) { String key = key(i); assertEquals("Wrong value read for key " + key, value(i), valueWrapper.unwrap(cache.get(key))); } } } @Test(enabled = false) public void generateOldData() throws IOException { newSegmented = false; ConfigurationBuilder cacheBuilder = cacheConfiguration(true); cacheManager.defineConfiguration(cacheName(), cacheBuilder.build()); Cache<String, T> cache = cacheManager.getCache(cacheName()); // 10 keys // even keys stored, odd keys removed for (int i = 0; i < NUMBER_KEYS; ++i) { if (i % 2 == 0) { String key = key(i); cache.put(key, valueWrapper.wrap(key, value(i))); } } cache.stop(); Path sourcePath = Paths.get(tmpDirectory); Path targetPath = Paths.get("generated").toAbsolutePath(); Files.createDirectories(targetPath); Files.walkFileTree(sourcePath, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Files.createDirectories(targetPath.resolve(sourcePath.relativize(dir))); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, targetPath.resolve(sourcePath.relativize(file)), StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.TERMINATE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); log.infof("Data generated in %s", targetPath); } @Override protected void setup() throws Exception { tmpDirectory = CommonsTestingUtil.tmpDirectory(this.getClass()); Util.recursiveFileRemove(tmpDirectory); log.debugf("Using tmpDirectory=%s", tmpDirectory); super.setup(); } @Override protected void teardown() { super.teardown(); Util.recursiveFileRemove(tmpDirectory); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder builder = new GlobalConfigurationBuilder().nonClusteredDefault(); builder.globalState().persistentLocation(tmpDirectory); builder.serialization().addContextInitializer(TestDataSCI.INSTANCE); amendGlobalConfigurationBuilder(builder); return TestCacheManagerFactory.createCacheManager(builder, null); } protected void amendGlobalConfigurationBuilder(GlobalConfigurationBuilder builder) { //no-op by default. To set SerializationContextInitializer (for example) } protected abstract String cacheName(); protected abstract void configurePersistence(ConfigurationBuilder builder, boolean generatingData); protected String combinePath(String path, String more) { return Paths.get(path, more).toString(); } protected Path getStoreLocation(String location, String qualifier) { return getQualifiedLocation(cacheManager.getCacheManagerConfiguration(), location, cacheName(), qualifier); } protected ConfigurationBuilder cacheConfiguration(boolean generatingData) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.LOCAL); builder.clustering().hash().numSegments(4); configurePersistence(builder, generatingData); return builder; } }
7,828
34.912844
115
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/LocalConditionalCommandTest.java
package org.infinispan.persistence; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.eviction.impl.ActivationManager; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.impl.CacheLoaderInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Tests if the conditional commands correctly fetch the value from cache loader even with the skip cache load/store * flags. * <p/> * The configuration used is a non-tx non-clustered cache without passivation. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "functional", testName = "persistence.LocalConditionalCommandTest") public class LocalConditionalCommandTest extends SingleCacheManagerTest { private static final String PRIVATE_STORE_CACHE_NAME = "private-store-cache"; private static final String SHARED_STORE_CACHE_NAME = "shared-store-cache"; private final String key = getClass().getSimpleName() + "-key"; private final String value1 = getClass().getSimpleName() + "-value1"; private final String value2 = getClass().getSimpleName() + "-value2"; private final boolean transactional; private final boolean passivation; public LocalConditionalCommandTest() { this(false, false); } protected LocalConditionalCommandTest(boolean transactional, boolean passivation) { this.transactional = transactional; this.passivation = passivation; } private static ConfigurationBuilder createConfiguration(String storeName, boolean shared, boolean transactional, boolean passivation) { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, transactional); builder.statistics().enable(); builder.persistence() .passivation(passivation) .addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(storeName + (shared ? "-shared" : "-private")) .fetchPersistentState(false) .shared(shared); builder.locking().isolationLevel(IsolationLevel.READ_COMMITTED); return builder; } @AfterMethod public void afterMethod() { if (passivation) { ActivationManager activationManager = TestingUtil.extractComponent(cache(PRIVATE_STORE_CACHE_NAME), ActivationManager.class); // Make sure no passivations are pending, which could leak between tests eventuallyEquals((long) 0, activationManager::getPendingActivationCount); } } private static <K, V> void writeToStore(Cache<K, V> cache, K key, V value) { MarshallableEntry entry = MarshalledEntryUtil.create(key, value, cache); DummyInMemoryStore store = TestingUtil.getFirstStore(cache); store.write(entry); } private static CacheLoaderInterceptor cacheLoaderInterceptor(Cache<?, ?> cache) { AsyncInterceptorChain chain = TestingUtil.extractComponent(cache, AsyncInterceptorChain.class); return chain.findInterceptorExtending( CacheLoaderInterceptor.class); } private void doTest(Cache<String, String> cache, ConditionalOperation operation, Flag flag) { assertEmpty(cache); initStore(cache); final boolean skipLoad = flag == Flag.SKIP_CACHE_LOAD || flag == Flag.SKIP_CACHE_STORE; try { if (flag != null) { operation.execute(cache.getAdvancedCache().withFlags(flag), key, value1, value2); } else { operation.execute(cache, key, value1, value2); } } catch (Exception e) { //some operation are allowed to fail. e.g. putIfAbsent. //we only check the final value log.debug(e); } assertLoadAfterOperation(cache, skipLoad); assertEquals(operation.finalValue(value1, value2, skipLoad), cache.get(key)); } private void assertLoadAfterOperation(Cache<?, ?> cache, boolean skipLoad) { assertEquals("cache load", skipLoad ? 0 : 1, cacheLoaderInterceptor(cache).getCacheLoaderLoads()); } private void assertEmpty(Cache<?, ?> cache) { assertTrue(cache + ".isEmpty()", cache.isEmpty()); } private void initStore(Cache<String, String> cache) { writeToStore(cache, key, value1); DummyInMemoryStore store = TestingUtil.getFirstStore(cache); assertTrue(store.contains(key)); cacheLoaderInterceptor(cache).resetStatistics(); } public void testPutIfAbsentWithSkipCacheLoader() { doTest(this.cache(PRIVATE_STORE_CACHE_NAME), ConditionalOperation.PUT_IF_ABSENT, Flag.SKIP_CACHE_LOAD); } public void testPutIfAbsentWithIgnoreReturnValues() { doTest(this.cache(PRIVATE_STORE_CACHE_NAME), ConditionalOperation.PUT_IF_ABSENT, Flag.IGNORE_RETURN_VALUES); } public void testPutIfAbsent() { doTest(this.cache(PRIVATE_STORE_CACHE_NAME), ConditionalOperation.PUT_IF_ABSENT, null); } public void testReplaceWithSkipCacheLoader() { doTest(this.cache(PRIVATE_STORE_CACHE_NAME), ConditionalOperation.REPLACE, Flag.SKIP_CACHE_LOAD); } public void testReplaceWithIgnoreReturnValues() { doTest(this.cache(PRIVATE_STORE_CACHE_NAME), ConditionalOperation.REPLACE, Flag.IGNORE_RETURN_VALUES); } public void testReplace() { doTest(this.cache(PRIVATE_STORE_CACHE_NAME), ConditionalOperation.REPLACE, null); } public void testReplaceIfWithSkipCacheLoader() { doTest(this.cache(PRIVATE_STORE_CACHE_NAME), ConditionalOperation.REPLACE_IF, Flag.SKIP_CACHE_LOAD); } public void testReplaceIfWithIgnoreReturnValues() { doTest(this.cache(PRIVATE_STORE_CACHE_NAME), ConditionalOperation.REPLACE_IF, Flag.IGNORE_RETURN_VALUES); } public void testReplaceIf() { doTest(this.cache(PRIVATE_STORE_CACHE_NAME), ConditionalOperation.REPLACE_IF, null); } public void testRemoveIfWithSkipCacheLoader() { doTest(this.cache(PRIVATE_STORE_CACHE_NAME), ConditionalOperation.REMOVE_IF, Flag.SKIP_CACHE_LOAD); } public void testRemoveIfWithIgnoreReturnValues() { doTest(this.cache(PRIVATE_STORE_CACHE_NAME), ConditionalOperation.REMOVE_IF, Flag.IGNORE_RETURN_VALUES); } public void testRemoveIf() { doTest(this.cache(PRIVATE_STORE_CACHE_NAME), ConditionalOperation.REMOVE_IF, null); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { EmbeddedCacheManager embeddedCacheManager = TestCacheManagerFactory.createClusteredCacheManager(); embeddedCacheManager.defineConfiguration(PRIVATE_STORE_CACHE_NAME, createConfiguration(getClass().getSimpleName(), false, transactional, passivation).build()); if (!passivation) { embeddedCacheManager.defineConfiguration(SHARED_STORE_CACHE_NAME, createConfiguration(getClass().getSimpleName(), true, transactional, false).build()); } return embeddedCacheManager; } private enum ConditionalOperation { PUT_IF_ABSENT { @Override public <K, V> void execute(Cache<K, V> cache, K key, V value1, V value2) { cache.putIfAbsent(key, value2); } @Override public <V> V finalValue(V value1, V value2, boolean skipLoad) { return skipLoad ? value2 : value1; } }, REPLACE { @Override public <K, V> void execute(Cache<K, V> cache, K key, V value1, V value2) { cache.replace(key, value2); } @Override public <V> V finalValue(V value1, V value2, boolean skipLoad) { return skipLoad ? value1 : value2; } }, REPLACE_IF { @Override public <K, V> void execute(Cache<K, V> cache, K key, V value1, V value2) { cache.replace(key, value1, value2); } @Override public <V> V finalValue(V value1, V value2, boolean skipLoad) { return skipLoad ? value1 : value2; } }, REMOVE_IF { @Override public <K, V> void execute(Cache<K, V> cache, K key, V value1, V value2) { cache.remove(key, value1); } @Override public <V> V finalValue(V value1, V value2, boolean skipLoad) { return skipLoad ? value1 : null; } }; public abstract <K, V> void execute(Cache<K, V> cache, K key, V value1, V value2); public abstract <V> V finalValue(V value1, V value2, boolean skipLoad); } }
9,161
37.987234
165
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/KeyValueWrapper.java
package org.infinispan.persistence; /** * Wraps the key/value to be stored in the cache. * * @author Pedro Ruivo * @since 11.0 */ public interface KeyValueWrapper<K, V, T> { T wrap(K key, V value); V unwrap(T object); }
235
13.75
49
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/AsyncStoreParallelIterationTest.java
package org.infinispan.persistence; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.metadata.Metadata; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; /** * @author Dan Berindei * @since 9.0 */ @Test(groups = "functional", testName = "persistence.AsyncStoreParallelIterationTest") @CleanupAfterMethod public class AsyncStoreParallelIterationTest extends ParallelIterationTest { @Override protected void configurePersistence(ConfigurationBuilder cb) { DummyInMemoryStoreConfigurationBuilder discb = cb.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); discb.async().enabled(true); } @Override protected void teardown() { super.teardown(); } @Override protected void assertMetadataEmpty(Metadata metadata, Object key) { // Async store always returns the metadata } }
1,013
28.823529
86
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/PersistenceManagerAvailabilityTest.java
package org.infinispan.persistence; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.PersistenceAvailabilityChanged; import org.infinispan.notifications.cachelistener.event.PersistenceAvailabilityChangedEvent; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.persistence.spi.StoreUnavailableException; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @CleanupAfterMethod @Test(testName = "persistence.PersistenceManagerAvailabilityTest", groups = "functional") public class PersistenceManagerAvailabilityTest extends SingleCacheManagerTest { private Cache<Object, Object> createManagerAndGetCache(int startFailures) { GlobalConfigurationBuilder globalConfiguration = new GlobalConfigurationBuilder(); ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(false); config.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class) .startFailures(startFailures); cacheManager = TestCacheManagerFactory.createCacheManager(globalConfiguration, config); return cacheManager.getCache(); } @Test(expectedExceptions = StoreUnavailableException.class) public void testCacheAvailability() { Cache<Object, Object> cache = createManagerAndGetCache(0); cache.put(1, 1); DummyInMemoryStore dims = TestingUtil.getFirstStore(cache); dims.setAvailable(false); PersistenceManager pm = TestingUtil.extractComponent(cache, PersistenceManager.class); eventually(() -> !pm.isAvailable()); try { cache.put(1, 2); } catch (Exception e) { assertEquals(1, cache.get(1)); throw e; } TestingUtil.killCaches(); } @Test(expectedExceptions = CacheException.class) public void testUnavailableStoreOnStart() { createManagerAndGetCache(11); } public void testStoreReconnect() { testAvailabilityFailover(dims -> dims.setAvailable(false), dims -> dims.setAvailable(true)); } public void testStoreReconnectWithAvailabilityException() { testAvailabilityFailover(dims -> dims.setExceptionOnAvailbilityCheck(true), dims -> dims.setExceptionOnAvailbilityCheck(false)); } private void testAvailabilityFailover(Consumer<DummyInMemoryStore> failAction, Consumer<DummyInMemoryStore> recoverAction) { PersistenceAvailabilityListener pal = new PersistenceAvailabilityListener(); Cache<Object, Object> cache = createManagerAndGetCache(0); cache.addListener(pal); assertEquals(0, pal.availableCount.get()); assertEquals(0, pal.unavailableCount.get()); cache.put(1, 1); PersistenceManager pm = TestingUtil.extractComponent(cache, PersistenceManager.class); assertTrue(pm.isAvailable()); DummyInMemoryStore dims = TestingUtil.getFirstStore(cache); failAction.accept(dims); eventually(() -> !pm.isAvailable()); eventuallyEquals(1, () -> pal.unavailableCount.get()); try { cache.put(1, 2); fail("Expected " + StoreUnavailableException.class.getSimpleName()); } catch (PersistenceException ignore) { } recoverAction.accept(dims); eventuallyEquals(1, () -> pal.availableCount.get()); assertTrue(pm.isAvailable()); cache.put(1, 3); assertEquals(3, cache.get(1)); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { // Manager is created later return null; } @Override protected void setup() throws Exception { // Manager is created later } @Listener public static class PersistenceAvailabilityListener { AtomicInteger availableCount = new AtomicInteger(); AtomicInteger unavailableCount = new AtomicInteger(); @PersistenceAvailabilityChanged public void availabilityChange(PersistenceAvailabilityChangedEvent event) { if (event.isAvailable()) availableCount.incrementAndGet(); else unavailableCount.incrementAndGet(); } } }
4,967
38.744
134
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/LocalTxConditionalCommandPassivationTest.java
package org.infinispan.persistence; import org.testng.annotations.Test; /** * Tests if the conditional commands correctly fetch the value from cache loader even with the skip cache load/store * flags. * <p/> * The configuration used is a tx non-clustered cache with passivation. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "functional", testName = "persistence.LocalTxConditionalCommandPassivationTest") public class LocalTxConditionalCommandPassivationTest extends LocalConditionalCommandTest { public LocalTxConditionalCommandPassivationTest() { super(true, true); } }
606
26.590909
116
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/AddStoreTest.java
package org.infinispan.persistence; import static org.infinispan.test.fwk.TestCacheManagerFactory.createCacheManager; import static org.infinispan.test.fwk.TestCacheManagerFactory.createClusteredCacheManager; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.util.concurrent.CompletionException; import java.util.function.Consumer; import org.infinispan.Cache; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.IntSets; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.SingleFileStoreConfigurationBuilder; import org.infinispan.configuration.cache.StoreConfiguration; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.impl.CacheLoaderInterceptor; import org.infinispan.interceptors.impl.CacheWriterInterceptor; import org.infinispan.interceptors.impl.ClusteredCacheLoaderInterceptor; import org.infinispan.interceptors.impl.PassivationCacheLoaderInterceptor; import org.infinispan.interceptors.impl.PassivationClusteredCacheLoaderInterceptor; import org.infinispan.interceptors.impl.PassivationWriterInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.file.SingleFileStore; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @since 13.0 */ @Test(groups = "functional", testName = "persistence.AddStoreTest") public class AddStoreTest extends AbstractInfinispanTest { public void testAddStore() { ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); ConfigurationBuilder toAddBuilder = new ConfigurationBuilder(); toAddBuilder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); addAndCheckStore(cacheBuilder, toAddBuilder.build().persistence().stores().get(0), this::checkStore); } public void testAddAsyncStore() { ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); ConfigurationBuilder toAddBuilder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); toAddBuilder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).async().enable(); addAndCheckStore(cacheBuilder, toAddBuilder.build().persistence().stores().get(0), this::checkStore); } @Test public void testAddStoreWithToClusteredCache() { ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); cacheBuilder.clustering().cacheMode(CacheMode.DIST_SYNC); ConfigurationBuilder toAddBuilder = new ConfigurationBuilder(); toAddBuilder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); addAndCheckStore(cacheBuilder, toAddBuilder.build().persistence().stores().get(0), this::checkClustered); } @Test public void testAddStoreWithToRrplCache() { ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); cacheBuilder.clustering().cacheMode(CacheMode.REPL_SYNC); ConfigurationBuilder toAddBuilder = new ConfigurationBuilder(); toAddBuilder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); addAndCheckStore(cacheBuilder, toAddBuilder.build().persistence().stores().get(0), this::checkClustered); } @Test public void testAddStoreWithPassivation() { testPassivation(new ConfigurationBuilder()); } @Test public void testAddStoreWithPassivationToClusteredCache() { ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); cacheBuilder.clustering().cacheMode(CacheMode.DIST_SYNC); testPassivation(cacheBuilder); } @Test public void testAddExtraStoreToCache() { String location = null; try { ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); cacheBuilder.clustering().cacheMode(CacheMode.DIST_SYNC); location = CommonsTestingUtil.tmpDirectory(this.getClass()); cacheBuilder.persistence().addStore(SingleFileStoreConfigurationBuilder.class).location(location); ConfigurationBuilder toAddBuilder = new ConfigurationBuilder(); toAddBuilder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); addAndCheckStore(cacheBuilder, toAddBuilder.build().persistence().stores().get(0), this::checkClustered); } finally { if (location != null) { Util.recursiveFileRemove(location); } } } @Test(expectedExceptions = CompletionException.class, expectedExceptionsMessageRegExp = ".*Cache.*is non empty.*") public void testAddToNonEmptyCache() { EmbeddedCacheManager cm = null; try { ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); cacheBuilder.clustering().cacheMode(CacheMode.DIST_SYNC); cm = createClusteredCacheManager(cacheBuilder); Cache<Object, Object> cache = cm.getCache(); cache.put("k", "v"); PersistenceManager persistenceManager = TestingUtil.extractComponent(cache, PersistenceManager.class); ConfigurationBuilder storeBuilder = new ConfigurationBuilder(); storeBuilder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); join(persistenceManager.addStore(storeBuilder.build().persistence().stores().get(0))); } finally { TestingUtil.killCacheManagers(cm); } } private void addAndCheckStore(ConfigurationBuilder builder, StoreConfiguration storeConfiguration, Consumer<Cache<?, ?>> check) { EmbeddedCacheManager cm = null; try { builder.statistics().enable(); cm = !builder.clustering().cacheMode().isClustered() ? createCacheManager(builder) : createClusteredCacheManager(builder); Cache<Object, Object> cache = cm.getCache(); PersistenceManager persistenceManager = TestingUtil.extractComponent(cache, PersistenceManager.class); // Add store join(persistenceManager.addStore(storeConfiguration)); int storesBefore = cache.getCacheConfiguration().persistence().stores().size(); int storeSizeAfterAdding = countStores(persistenceManager); // Check the store was added to the persistenceManager assertEquals(storesBefore + 1, storeSizeAfterAdding); // Check the interceptors were created check.accept(cache); // Add some data cache.put("key1", "value1"); cache.put("key2", "value2"); // Check the data hit the store int expected = cache.getCacheConfiguration().persistence().passivation() ? 1 : 2; assertEquals(expected, getDummyStoreSize(persistenceManager, cache.getCacheConfiguration().clustering().hash().numSegments())); // Disable the store join(persistenceManager.disableStore(DummyInMemoryStore.class.getName())); // Check store is gone assertEquals(storesBefore, countStores(persistenceManager)); } finally { TestingUtil.killCacheManagers(cm); } } private int countStores(PersistenceManager pm) { return pm.getStoresAsString().size(); } private Class loadClass(String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } private long getDummyStoreSize(PersistenceManager persistenceManager, int numSegments) { return persistenceManager.getStoresAsString().stream() .filter(s -> s.equals(DummyInMemoryStore.class.getName())) .map(this::loadClass) .map(s -> persistenceManager.getStores(s).iterator().next()) .map(store -> { if (store instanceof DummyInMemoryStore) { DummyInMemoryStore dummyInMemoryStore = (DummyInMemoryStore) store; return dummyInMemoryStore.size(); } else if (store instanceof SingleFileStore) { SingleFileStore<?, ?> singleFileStore = (SingleFileStore<?, ?>) store; return join(singleFileStore.size(IntSets.immutableRangeSet(numSegments))); } return -1L; }).findFirst().orElse(-1L); } private void checkStore(Cache<?, ?> cache) { AsyncInterceptorChain asyncInterceptorChain = cache.getAdvancedCache().getAdvancedCache().getAsyncInterceptorChain(); assertNotNull(asyncInterceptorChain.findInterceptorWithClass(CacheLoaderInterceptor.class)); assertNotNull(asyncInterceptorChain.findInterceptorWithClass(CacheWriterInterceptor.class)); } private void checkPassivation(Cache<?, ?> cache) { AsyncInterceptorChain asyncInterceptorChain = cache.getAdvancedCache().getAdvancedCache().getAsyncInterceptorChain(); assertNotNull(asyncInterceptorChain.findInterceptorWithClass(PassivationWriterInterceptor.class)); if (cache.getAdvancedCache().getCacheConfiguration().clustering().cacheMode().isClustered()) { assertNotNull(asyncInterceptorChain.findInterceptorWithClass(PassivationClusteredCacheLoaderInterceptor.class)); } else { assertNotNull(asyncInterceptorChain.findInterceptorWithClass(PassivationCacheLoaderInterceptor.class)); } } private void checkClustered(Cache<?, ?> cache) { AsyncInterceptorChain asyncInterceptorChain = cache.getAdvancedCache().getAdvancedCache().getAsyncInterceptorChain(); assertNotNull(asyncInterceptorChain.findInterceptorWithClass(ClusteredCacheLoaderInterceptor.class)); } private void testPassivation(ConfigurationBuilder cacheBuilder) { String location = null; try { location = CommonsTestingUtil.tmpDirectory(this.getClass()); cacheBuilder.persistence().passivation(true).addStore(SingleFileStoreConfigurationBuilder.class).location(location); cacheBuilder.memory().maxCount(1); ConfigurationBuilder toAddBuilder = new ConfigurationBuilder(); toAddBuilder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); addAndCheckStore(cacheBuilder, toAddBuilder.build().persistence().stores().get(0), this::checkPassivation); } finally { if (location != null) { Util.recursiveFileRemove(location); } } } }
10,823
42.46988
136
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/InitCountTest.java
package org.infinispan.persistence; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.AbstractCacheTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 6.0 */ @Test(groups = "functional", testName = "persistence.InitCountTest") public class InitCountTest extends AbstractCacheTest { public void testInitInvocationCountNoDelegate() { test(false); } public void testInitInvocationCountWithDelegate() { test(true); } /** * @param async set to true means the cache store instance is placed under an DelegatingCacheWriter */ private void test(boolean async) { ConfigurationBuilder dcc = TestCacheManagerFactory.getDefaultCacheConfiguration(true); DummyInMemoryStoreConfigurationBuilder builder = dcc.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); if (async) { builder.async().enable(); } EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(dcc); Cache<Object,Object> cache = cacheManager.getCache(); try { DummyInMemoryStore dims = TestingUtil.getFirstStore(cache); assertEquals(1, dims.getInitCount()); } finally { TestingUtil.killCacheManagers(cacheManager); } } }
1,689
32.8
128
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/APINonTxPersistenceTest.java
package org.infinispan.persistence; import org.infinispan.api.APINonTxTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.testng.annotations.Test; /** * Test that ensure that when persistence is used with an always empty data container that various operations * are properly supported * @author wburns * @since 9.2 */ @Test(groups = "functional", testName = "persistence.APINonTxPersistenceTest") public class APINonTxPersistenceTest extends APINonTxTest { @Override protected void configure(ConfigurationBuilder builder) { builder .memory().size(0) .persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(getClass().getName()) .purgeOnStartup(true) ; } @Override public void testEvict() { // Ignoring test as we have nothing to evict } }
993
30.0625
109
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/LocalTxConditionalCommandTest.java
package org.infinispan.persistence; import org.testng.annotations.Test; /** * Tests if the conditional commands correctly fetch the value from cache loader even with the skip cache load/store * flags. * <p/> * The configuration used is a tx non-clustered cache with passivation. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "functional", testName = "persistence.LocalTxConditionalCommandTest") public class LocalTxConditionalCommandTest extends LocalConditionalCommandTest { public LocalTxConditionalCommandTest() { super(true, false); } }
574
25.136364
116
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/BaseStoreFunctionalTest.java
package org.infinispan.persistence; import static org.testng.AssertJUnit.assertArrayEquals; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.infinispan.Cache; import org.infinispan.CacheSet; import org.infinispan.CacheStream; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.ByRef; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.configuration.cache.StoreConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.eviction.EvictionType; import org.infinispan.factories.annotations.SurvivesRestarts; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.persistence.support.WaitNonBlockingStore; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.data.Address; import org.infinispan.test.data.Person; import org.infinispan.test.data.Sex; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.Test; /** * This is a base functional test class containing tests that should be executed for each cache store/loader * implementation. As these are functional tests, they should interact against Cache/CacheManager only and any access to * the underlying cache store/loader should be done to verify contents. */ @Test(groups = {"unit", "smoke"}, testName = "persistence.BaseStoreFunctionalTest") public abstract class BaseStoreFunctionalTest extends SingleCacheManagerTest { private static final SerializationContextInitializer CONTEXT_INITIALIZER = TestDataSCI.INSTANCE; protected abstract PersistenceConfigurationBuilder createCacheStoreConfig(PersistenceConfigurationBuilder persistence, String cacheName, boolean preload); protected ConfigurationBuilder getDefaultCacheConfiguration() { return TestCacheManagerFactory.getDefaultCacheConfiguration(false); } protected Object wrap(String key, String value) { return value; } protected String unwrap(Object wrapped) { return (String) wrapped; } protected BaseStoreFunctionalTest() { cleanup = CleanupPhase.AFTER_METHOD; } @Override protected void teardown() { TestingUtil.clearContent(cacheManager); super.teardown(); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); global.globalState().persistentLocation(CommonsTestingUtil.tmpDirectory(this.getClass())); global.serialization().addContextInitializer(getSerializationContextInitializer()); global.cacheContainer().security().authorization().enable(); return createCacheManager(false, global, new ConfigurationBuilder()); } protected EmbeddedCacheManager createCacheManager(boolean start, GlobalConfigurationBuilder global, ConfigurationBuilder cb) { return TestCacheManagerFactory.newDefaultCacheManager(start, global, cb); } protected SerializationContextInitializer getSerializationContextInitializer() { return CONTEXT_INITIALIZER; } protected void assertPersonEqual(Person firstPerson, Person secondPerson) { assertEquals(firstPerson, secondPerson); } public void testTwoCachesSameCacheStore() { ConfigurationBuilder cb = getDefaultCacheConfiguration(); createCacheStoreConfig(cb.persistence(), "testTwoCachesSameCacheStore", false); Configuration c = cb.build(); TestingUtil.defineConfiguration(cacheManager, "testTwoCachesSameCacheStore-1", c); TestingUtil.defineConfiguration(cacheManager, "testTwoCachesSameCacheStore-2", c); Cache<String, Object> first = cacheManager.getCache("testTwoCachesSameCacheStore-1"); Cache<String, Object> second = cacheManager.getCache("testTwoCachesSameCacheStore-2"); first.start(); second.start(); first.put("key", wrap("key", "val")); assertEquals("val", unwrap(first.get("key"))); assertNull(second.get("key")); second.put("key2", wrap("key2", "val2")); assertEquals("val2", unwrap(second.get("key2"))); assertNull(first.get("key2")); } public void testPreloadAndExpiry() { ConfigurationBuilder cb = getDefaultCacheConfiguration(); createCacheStoreConfig(cb.persistence(), "testPreloadAndExpiry", true); TestingUtil.defineConfiguration(cacheManager, "testPreloadAndExpiry", cb.build()); Cache<String, Object> cache = cacheManager.getCache("testPreloadAndExpiry"); cache.start(); assert cache.getCacheConfiguration().persistence().preload(); cache.put("k1", wrap("k1", "v")); cache.put("k2", wrap("k2", "v"), 111111, TimeUnit.MILLISECONDS); cache.put("k3", wrap("k3", "v"), -1, TimeUnit.MILLISECONDS, 222222, TimeUnit.MILLISECONDS); cache.put("k4", wrap("k4", "v"), 333333, TimeUnit.MILLISECONDS, 444444, TimeUnit.MILLISECONDS); assertCacheEntry(cache, "k1", "v", -1, -1); assertCacheEntry(cache, "k2", "v", 111111, -1); assertCacheEntry(cache, "k3", "v", -1, 222222); assertCacheEntry(cache, "k4", "v", 333333, 444444); cache.stop(); cache.start(); assertCacheEntry(cache, "k1", "v", -1, -1); assertCacheEntry(cache, "k2", "v", 111111, -1); assertCacheEntry(cache, "k3", "v", -1, 222222); assertCacheEntry(cache, "k4", "v", 333333, 444444); } public void testPreloadStoredAsBinary() { ConfigurationBuilder cb = getDefaultCacheConfiguration(); createCacheStoreConfig(cb.persistence(), "testPreloadStoredAsBinary", true).memory().storageType(StorageType.BINARY); TestingUtil.defineConfiguration(cacheManager, "testPreloadStoredAsBinary", cb.build()); Cache<String, Person> cache = cacheManager.getCache("testPreloadStoredAsBinary"); cache.start(); assert cache.getCacheConfiguration().persistence().preload(); assertEquals(StorageType.BINARY, cache.getCacheConfiguration().memory().storageType()); byte[] pictureBytes = new byte[]{1, 82, 123, 19}; cache.put("k1", createEmptyPerson("1")); cache.put("k2", new Person("2", null, pictureBytes, null, null, false, 4.6, 5.6f, 8.4, 9.2f), 111111, TimeUnit.MILLISECONDS); cache.put("k3", new Person("3", null, null, Sex.MALE, null, false, 4.7, 5.7f, 8.5, 9.3f), -1, TimeUnit.MILLISECONDS, 222222, TimeUnit.MILLISECONDS); cache.put("k4", new Person("4", new Address("Street", "City", 12345), null, null, null, true, 4.8, 5.8f, 8.6, 9.4f), 333333, TimeUnit.MILLISECONDS, 444444, TimeUnit.MILLISECONDS); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("EST")); calendar.set(2009, Calendar.MARCH, 18, 3, 22, 57); // Chop off the last milliseconds as some databases don't have that high of accuracy calendar.setTimeInMillis((calendar.getTimeInMillis() / 1000) * 1000); Date infinispanBirthDate = calendar.getTime(); Person infinispanPerson = createEmptyPerson("Infinispan"); infinispanPerson.setBirthDate(infinispanBirthDate); infinispanPerson.setAcceptedToS(true); cache.put("Infinispan", infinispanPerson); // Just to prove nothing in memory even with stop cache.getAdvancedCache().getDataContainer().clear(); assertPersonEqual(createEmptyPerson("1"), cache.get("k1")); Person person2 = createEmptyPerson("2"); person2.setPicture(pictureBytes); person2.setMoneyOwned(4.6); person2.setMoneyOwed(5.6f); person2.setDecimalField(8.4); person2.setRealField(9.2f); assertPersonEqual(person2, cache.get("k2")); Person person3 = createEmptyPerson("3"); person3.setSex(Sex.MALE); person3.setMoneyOwned(4.7); person3.setMoneyOwed(5.7f); person3.setDecimalField(8.5); person3.setRealField(9.3f); assertPersonEqual(person3, cache.get("k3")); assertPersonEqual(new Person("4", new Address("Street", "City", 12345), null, null, null, true, 4.8, 5.8f, 8.6, 9.4f), cache.get("k4")); assertPersonEqual(infinispanPerson, cache.get("Infinispan")); cache.stop(); cache.start(); assertEquals(5, cache.entrySet().size()); assertPersonEqual(createEmptyPerson("1"), cache.get("k1")); assertPersonEqual(person2, cache.get("k2")); assertPersonEqual(person3, cache.get("k3")); assertPersonEqual(new Person("4", new Address("Street", "City", 12345), null, null, null, true, 4.8, 5.8f, 8.6, 9.4f), cache.get("k4")); assertPersonEqual(infinispanPerson, cache.get("Infinispan")); } protected Person createEmptyPerson(String name) { return new Person(name); } public void testStoreByteArrays(final Method m) throws PersistenceException { ConfigurationBuilder base = getDefaultCacheConfiguration(); // we need to purge the container when loading, because we could try to compare // some old entry using ByteArrayEquivalence and this throws ClassCastException // for non-byte[] arguments TestingUtil.defineConfiguration(cacheManager, m.getName(), configureCacheLoader(base, m.getName(), true).build()); Cache<byte[], byte[]> cache = cacheManager.getCache(m.getName()); byte[] key = {1, 2, 3}; byte[] value = {4, 5, 6}; cache.put(key, value); // Lookup in memory, sanity check byte[] lookupKey = {1, 2, 3}; byte[] found = cache.get(lookupKey); assertNotNull(found); assertArrayEquals(value, found); cache.evict(key); // Lookup in cache store found = cache.get(lookupKey); assertNotNull(found); assertArrayEquals(value, found); } public void testRemoveCache() { GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); global.globalState().persistentLocation(CommonsTestingUtil.tmpDirectory(this.getClass())); global.serialization().addContextInitializer(getSerializationContextInitializer()); ConfigurationBuilder cb = getDefaultCacheConfiguration(); final String cacheName = "testRemoveCache"; createCacheStoreConfig(cb.persistence(), cacheName, true); EmbeddedCacheManager local = createCacheManager(true, global, cb); try { local.defineConfiguration(cacheName, local.getDefaultCacheConfiguration()); Cache<String, Object> cache = local.getCache(cacheName); assertTrue(local.isRunning(cacheName)); cache.put("1", wrap("1", "v1")); assertCacheEntry(cache, "1", "v1", -1, -1); local.administration().removeCache(cacheName); assertFalse(local.isRunning(cacheName)); } finally { TestingUtil.killCacheManagers(local); } } public void testRemoveCacheWithPassivation() { GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); global.globalState().persistentLocation(CommonsTestingUtil.tmpDirectory(this.getClass())); global.serialization().addContextInitializer(getSerializationContextInitializer()); ConfigurationBuilder cb = getDefaultCacheConfiguration(); final String cacheName = "testRemoveCacheWithPassivation"; createCacheStoreConfig(cb.persistence().passivation(true), cacheName, true); EmbeddedCacheManager local = createCacheManager(true, global, cb); try { local.defineConfiguration(cacheName, local.getDefaultCacheConfiguration()); Cache<String, Object> cache = local.getCache(cacheName); assertTrue(local.isRunning(cacheName)); cache.put("1", wrap("1", "v1")); assertCacheEntry(cache, "1", "v1", -1, -1); ByRef<Boolean> passivate = new ByRef<>(false); PersistenceManager actual = cache.getAdvancedCache().getComponentRegistry().getComponent(PersistenceManager.class); PersistenceManager stub = new TrackingPersistenceManager(actual, passivate); TestingUtil.replaceComponent(cache, PersistenceManager.class, stub, true); local.administration().removeCache(cacheName); assertFalse(local.isRunning(cacheName)); assertFalse(passivate.get()); } finally { TestingUtil.killCacheManagers(local); } } public void testPutAllBatch() { int numberOfEntries = 100; String cacheName = "testPutAllBatch"; ConfigurationBuilder cb = getDefaultCacheConfiguration(); createCacheStoreConfig(cb.persistence(), cacheName, false); TestingUtil.defineConfiguration(cacheManager, cacheName, cb.build()); Cache<String, Object> cache = cacheManager.getCache(cacheName); Map<String, Object> entriesMap = IntStream.range(0, numberOfEntries).boxed() .collect(Collectors.toMap(Object::toString, i -> wrap(i.toString(), "Val" + i))); cache.putAll(entriesMap); assertEquals(numberOfEntries, cache.size()); WaitNonBlockingStore<String, Object> store = TestingUtil.getFirstStoreWait(cache); for (int i = 0; i < numberOfEntries; ++i) { assertNotNull("Entry for key: " + i + " was null", store.loadEntry(toStorage(cache, Integer.toString(i)))); } } public void testIterator() { int numberOfEntries = 100; String cacheName = "testIterator"; ConfigurationBuilder cb = getDefaultCacheConfiguration(); createCacheStoreConfig(cb.persistence(), cacheName, false); TestingUtil.defineConfiguration(cacheManager, cacheName, cb.build()); Cache<String, Object> cache = cacheManager.getCache(cacheName); Map<String, Object> entriesMap = IntStream.range(0, numberOfEntries).boxed() .collect(Collectors.toMap(Object::toString, i -> wrap(i.toString(), "Val" + i))); cache.putAll(entriesMap); Map<String, Object> results = new HashMap<>(numberOfEntries); try (CloseableIterator<Map.Entry<String, Object>> iter = cache.getAdvancedCache().entrySet().iterator()) { iter.forEachRemaining(e -> results.put(e.getKey(), e.getValue())); } assertEquals(entriesMap, results); } public void testIteratorWithSegment() { int numberOfEntries = 100; String cacheName = "testIteratorWithSegment"; ConfigurationBuilder cb = getDefaultCacheConfiguration(); createCacheStoreConfig(cb.persistence(), cacheName, false); TestingUtil.defineConfiguration(cacheManager, cacheName, cb.build()); Cache<String, Object> cache = cacheManager.getCache(cacheName); IntSet segments = IntSets.mutableEmptySet(); for (int i = 0; i < cache.getCacheConfiguration().clustering().hash().numSegments(); ++i) { if (i % 2 == 0) { segments.set(i); } } Map<String, Object> entriesMap = IntStream.range(0, numberOfEntries).boxed() .collect(Collectors.toMap(Object::toString, i -> wrap(i.toString(), "Val" + i))); cache.putAll(entriesMap); KeyPartitioner kp = TestingUtil.extractComponent(cache, KeyPartitioner.class); Map<String, Object> targetMap = entriesMap.entrySet().stream().filter(e -> segments.contains(kp.getSegment(e.getKey())) ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map<String, Object> results = new HashMap<>(numberOfEntries); try (CacheStream<Map.Entry<String, Object>> stream = cache.getAdvancedCache().entrySet().stream()) { stream.filterKeySegments(segments).iterator().forEachRemaining(e -> results.put(e.getKey(), e.getValue())); } assertEquals(targetMap, results); } Object fromStorage(Cache<?, ?> cache, Object value) { return cache.getAdvancedCache().getValueDataConversion() .withRequestMediaType(MediaType.APPLICATION_OBJECT) .fromStorage(value); } Object toStorage(Cache<?, ?> cache, Object key) { return cache.getAdvancedCache().getKeyDataConversion() .withRequestMediaType(MediaType.APPLICATION_OBJECT) .toStorage(key); } public void testLoadEntrySet() { int numberOfEntries = 10; ConfigurationBuilder cb = getDefaultCacheConfiguration(); createCacheStoreConfig(cb.persistence(), "testLoadEntrySet", true); Configuration configuration = cb.build(); TestingUtil.defineConfiguration(cacheManager, "testLoadEntrySet", configuration); Cache<String, Object> cache = cacheManager.getCache("testLoadEntrySet"); Map<String, Object> entriesMap = IntStream.range(0, numberOfEntries).boxed() .collect(Collectors.toMap(Object::toString, i -> wrap(i.toString(), "Val" + i))); cache.putAll(entriesMap); cache.stop(); cache.start(); CacheSet<Map.Entry<String, Object>> set = cache.entrySet(); assertEquals(numberOfEntries, cache.size()); assertEquals(numberOfEntries, set.size()); set.forEach(e -> assertEquals(entriesMap.get(e.getKey()), e.getValue())); } public void testReloadWithEviction() { int numberOfEntries = 10; ConfigurationBuilder cb = getDefaultCacheConfiguration(); createCacheStoreConfig(cb.persistence(), "testReloadWithEviction", false).memory().size(numberOfEntries / 2).evictionType(EvictionType.COUNT); TestingUtil.defineConfiguration(cacheManager, "testReloadWithEviction", cb.build()); Cache<String, Object> cache = cacheManager.getCache("testReloadWithEviction"); Map<String, Object> entriesMap = IntStream.range(0, numberOfEntries).boxed() .collect(Collectors.toMap(Object::toString, i -> wrap(i.toString(), "Val" + i))); cache.putAll(entriesMap); assertEquals(numberOfEntries, cache.size()); entriesMap.forEach((k, v) -> assertEquals(v, cache.get(k))); cache.stop(); cache.start(); assertEquals(numberOfEntries, cache.size()); entriesMap.forEach((k, v) -> assertEquals(v, cache.get(k))); } protected ConfigurationBuilder configureCacheLoader(ConfigurationBuilder base, String cacheName, boolean purge) { ConfigurationBuilder cfg = base == null ? getDefaultCacheConfiguration() : base; cfg.transaction().transactionMode(TransactionMode.TRANSACTIONAL); createCacheStoreConfig(cfg.persistence(), cacheName, false); cfg.persistence().stores().get(0).purgeOnStartup(purge); return cfg; } private void assertCacheEntry(Cache cache, String key, String value, long lifespanMillis, long maxIdleMillis) { DataContainer dc = cache.getAdvancedCache().getDataContainer(); InternalCacheEntry ice = dc.get(toStorage(cache, key)); assertNotNull(ice); assertEquals(value, unwrap(fromStorage(cache, ice.getValue()))); assertEquals(lifespanMillis, ice.getLifespan()); assertEquals(maxIdleMillis, ice.getMaxIdle()); if (lifespanMillis > -1) assert ice.getCreated() > -1 : "Lifespan is set but created time is not"; if (maxIdleMillis > -1) assert ice.getLastUsed() > -1 : "Max idle is set but last used is not"; } @SurvivesRestarts static class TrackingPersistenceManager extends org.infinispan.persistence.support.DelegatingPersistenceManager { private final ByRef<Boolean> passivate; public TrackingPersistenceManager(PersistenceManager actual, ByRef<Boolean> passivate) { super(actual); this.passivate = passivate; } @Override public void start() { // Do nothing, the actual PersistenceManager is already started when it is wrapped } @Override public <K, V> CompletionStage<Void> writeEntries(Iterable<MarshallableEntry<K, V>> iterable, Predicate<? super StoreConfiguration> predicate) { passivate.set(true); return super.writeEntries(iterable, predicate); } } }
21,159
44.505376
185
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/FlushingAsyncStoreTest.java
package org.infinispan.persistence; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.support.DelayStore; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * FlushingAsyncStoreTest. * * @author Sanne Grinovero */ @Test(groups = "functional", testName = "persistence.FlushingAsyncStoreTest", singleThreaded = true) public class FlushingAsyncStoreTest extends SingleCacheManagerTest { public static final String CACHE_NAME = "AsyncStoreInMemory"; public FlushingAsyncStoreTest() { cleanup = CleanupPhase.AFTER_METHOD; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder config = getDefaultStandaloneCacheConfig(false); config .persistence() .addStore(DelayStore.ConfigurationBuilder.class) .storeName(this.getClass().getName()) .async().enable() .build(); EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(config); cacheManager.defineConfiguration(CACHE_NAME, config.build()); return cacheManager; } public void writeOnStorage() throws ExecutionException, InterruptedException, TimeoutException { cache = cacheManager.getCache(CACHE_NAME); DelayStore store = TestingUtil.getFirstStore(cache); store.delayBeforeModification(1); cache.put("key1", "value"); Future<Void> stopFuture = fork(() -> cache.stop()); assertFalse(stopFuture.isDone()); assertEquals(0, (int) store.stats().get("write")); store.endDelay(); stopFuture.get(10, TimeUnit.SECONDS); assertEquals(1, (int) store.stats().get("write")); assertEquals(1, DummyInMemoryStore.getStoreDataSize(store.getStoreName())); } }
2,325
34.784615
100
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/LocalModeNoPassivationTest.java
package org.infinispan.persistence; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; /** * Test if keys are properly passivated and reloaded in local mode (to ensure fix for ISPN-2712 did no break local mode). * * @author anistor@redhat.com * @since 5.2 */ @Test(groups = "functional", testName = "persistence.LocalModeNoPassivationTest") @CleanupAfterMethod public class LocalModeNoPassivationTest extends LocalModePassivationTest { LocalModeNoPassivationTest() { super(false); } }
541
26.1
121
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/ClusteredTxConditionalCommandTest.java
package org.infinispan.persistence; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.distribution.Ownership; import org.infinispan.test.fwk.InCacheMode; import org.testng.annotations.Test; /** * Tests if the conditional commands correctly fetch the value from cache loader even with the skip cache load/store * flags. * <p/> * The configuration used is a tx distributed cache without passivation. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "functional", testName = "persistence.ClusteredTxConditionalCommandTest") @InCacheMode({CacheMode.DIST_SYNC}) public class ClusteredTxConditionalCommandTest extends ClusteredConditionalCommandTest { // TX optimistic but without WSC! public ClusteredTxConditionalCommandTest() { super(true, false); } @Override protected <K, V> void assertLoadAfterOperation(CacheHelper<K, V> cacheHelper, ConditionalOperation operation, Ownership ownership, boolean skipLoad) { switch (ownership) { case PRIMARY: assertLoad(cacheHelper, skipLoad ? 0 : 1, 0, 0); break; case BACKUP: // If the command succeeds, WSC is executed - load on primary owner assertLoad(cacheHelper, 0, skipLoad ? 0 : 1, 0); break; case NON_OWNER: if (skipLoad) { // Replace_if does not load anything because it is unsuccessful on originator, as the retrieved // remote entry is null due to the skip load flag. assertLoad(cacheHelper, 0, 0, 0); } else { // The entry is loaded into DC upon the initial value retrieval (ClusteredGetCommand). // It gets loaded all the time on primary, but if the response to the retrieval does not // come soon enough, staggered logic sends second retrieval to backup owner, so it's possible // that both owners load once. assertEquals("primary owner load", 1, cacheHelper.loads(Ownership.PRIMARY)); long backupLoads = cacheHelper.loads(Ownership.BACKUP); assertTrue("backup owner load: " + backupLoads, backupLoads <= 1); assertEquals("non owner load", 0, cacheHelper.loads(Ownership.NON_OWNER)); } break; } } }
2,429
40.896552
153
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/ClusteredConditionalCommandTest.java
package org.infinispan.persistence; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.getFirstStore; import static org.infinispan.test.TestingUtil.waitForNoRebalance; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.util.EnumMap; import java.util.List; import java.util.Map; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.Ownership; import org.infinispan.eviction.impl.ActivationManager; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.impl.CacheLoaderInterceptor; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.InCacheMode; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.SkipException; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Tests if the conditional commands correctly fetch the value from cache loader even with the skip cache load/store * flags. * <p/> * The configuration used is a non-tx distributed cache without passivation. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "functional", testName = "persistence.ClusteredConditionalCommandTest") @InCacheMode({ CacheMode.DIST_SYNC }) public class ClusteredConditionalCommandTest extends MultipleCacheManagersTest { private static final String PRIVATE_STORE_CACHE_NAME = "private-store-cache"; private static final String SHARED_STORE_CACHE_NAME = "shared-store-cache"; private final String key = getClass().getSimpleName() + "-key"; private final String value1 = getClass().getSimpleName() + "-value1"; private final String value2 = getClass().getSimpleName() + "-value2"; private final boolean passivation; public ClusteredConditionalCommandTest() { this(false, false); } protected ClusteredConditionalCommandTest(boolean transactional, boolean passivation) { this.transactional = transactional; this.passivation = passivation; this.cacheMode = CacheMode.DIST_SYNC; } private ConfigurationBuilder createConfiguration(String storeName, boolean shared, boolean transactional, boolean passivation, int storePrefix) { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(cacheMode, transactional); builder.statistics().enable(); builder.persistence() .passivation(passivation) .addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(storeName + (shared ? "-shared" : storePrefix)) .fetchPersistentState(false) .shared(shared); builder.locking().isolationLevel(IsolationLevel.READ_COMMITTED); return builder; } @AfterMethod public void afterMethod() { if (passivation) { for (EmbeddedCacheManager cacheManager : cacheManagers) { ActivationManager activationManager = TestingUtil.extractComponent(cacheManager.getCache(PRIVATE_STORE_CACHE_NAME), ActivationManager.class); // Make sure no activations are pending, which could leak between tests eventuallyEquals((long) 0, activationManager::getPendingActivationCount); } } } private static <K, V> void writeToStore(CacheHelper<K, V> cacheHelper, Ownership ownership, K key, V value) { MarshallableEntry entry = MarshalledEntryUtil.create(key, value, cacheHelper.cache(ownership)); cacheHelper.cacheStore(ownership).write(entry); } private <K, V> CacheHelper<K, V> create(List<Cache<K, V>> cacheList) { CacheHelper<K, V> cacheHelper = new CacheHelper<>(); for (Cache<K, V> cache : cacheList) { ClusteringDependentLogic clusteringDependentLogic = extractComponent(cache, ClusteringDependentLogic.class); DistributionInfo distributionInfo = clusteringDependentLogic.getCacheTopology().getDistribution(key); log.debugf("owners for key %s are %s", key, distributionInfo.writeOwners()); if (distributionInfo.isPrimary()) { log.debug("Cache " + address(cache) + " is the primary owner"); assertTrue(cacheHelper.addCache(Ownership.PRIMARY, cache)); } else if (distributionInfo.isWriteBackup()) { log.debug("Cache " + address(cache) + " is the backup owner"); assertTrue(cacheHelper.addCache(Ownership.BACKUP, cache)); } else { log.debug("Cache " + address(cache) + " is the non owner"); assertTrue(cacheHelper.addCache(Ownership.NON_OWNER, cache)); } } return cacheHelper; } private void doTest(String cacheName, ConditionalOperation operation, Ownership ownership, Flag flag, boolean shared) { if (shared && passivation) { // Skip the test, shared stores don't support passivation return; } List<Cache<String, String>> cacheList = getCaches(cacheName); // These are not valid test combinations - so just ignore them if (shared && passivation) { throw new SkipException("Shared passivation is not supported"); } waitForNoRebalance(cacheList); final CacheHelper<String, String> cacheHelper = create(cacheList); final boolean skipLoad = flag == Flag.SKIP_CACHE_LOAD || flag == Flag.SKIP_CACHE_STORE; assertEmpty(cacheList); initStore(cacheHelper, shared); try { if (flag != null) { operation.execute(cacheHelper.cache(ownership).getAdvancedCache().withFlags(flag), key, value1, value2); } else { operation.execute(cacheHelper.cache(ownership), key, value1, value2); } } catch (Exception e) { //some operation are allowed to fail. e.g. putIfAbsent. //we only check the final value log.debug(e); } assertLoadAfterOperation(cacheHelper, operation, ownership, skipLoad); Cache<String, String> primary = cacheHelper.cache(Ownership.PRIMARY); Cache<String, String> backup = cacheHelper.cache(Ownership.BACKUP); assertEquals(operation.finalValue(value1, value2, skipLoad), primary.get(key)); if (backup != null) { assertEquals(operation.finalValue(value1, value2, skipLoad), backup.get(key)); } //don't test in non_owner because it generates remote gets and they can cross tests causing random failures. } protected <K, V> void assertLoadAfterOperation(CacheHelper<K, V> cacheHelper, ConditionalOperation operation, Ownership ownership, boolean skipLoad) { //in non-transactional caches, only the primary owner will load from store // backup will load only in case that it is origin (and needs previous value) assertLoad(cacheHelper, skipLoad ? 0 : 1, 0, 0); } protected final <K, V> void assertLoad(CacheHelper<K, V> cacheHelper, int primaryOwner, int backupOwner, int nonOwner) { assertEquals("primary owner load", primaryOwner, cacheHelper.loads(Ownership.PRIMARY)); assertEquals("backup owner load", backupOwner, cacheHelper.loads(Ownership.BACKUP)); assertEquals("non owner load", nonOwner, cacheHelper.loads(Ownership.NON_OWNER)); } private <K, V> void assertEmpty(List<Cache<K, V>> cacheList) { for (Cache<K, V> cache : cacheList) { assertTrue(cache + ".isEmpty()", cache.isEmpty()); } } private void initStore(CacheHelper<String, String> cacheHelper, boolean shared) { DummyInMemoryStore primaryStore = cacheHelper.cacheStore(Ownership.PRIMARY); DummyInMemoryStore backupStore = cacheHelper.cacheStore(Ownership.BACKUP); DummyInMemoryStore nonOwnerStore = cacheHelper.cacheStore(Ownership.NON_OWNER); if (shared) { writeToStore(cacheHelper, Ownership.PRIMARY, key, value1); assertTrue(primaryStore.contains(key)); if (backupStore != null) { assertTrue(backupStore.contains(key)); } assertTrue(nonOwnerStore.contains(key)); } else { writeToStore(cacheHelper, Ownership.PRIMARY, key, value1); assertTrue(primaryStore.contains(key)); if (backupStore != null) { writeToStore(cacheHelper, Ownership.BACKUP, key, value1); assertTrue(backupStore.contains(key)); } assertFalse(nonOwnerStore.contains(key)); } cacheHelper.resetStats(Ownership.PRIMARY); cacheHelper.resetStats(Ownership.BACKUP); cacheHelper.resetStats(Ownership.NON_OWNER); } @Override protected void createCacheManagers() throws Throwable { createCluster( 3); int index = 0; for (EmbeddedCacheManager cacheManager : cacheManagers) { if (!passivation) { cacheManager.defineConfiguration(SHARED_STORE_CACHE_NAME, createConfiguration(getClass().getSimpleName(), true, transactional, false, index).build()); } cacheManager.defineConfiguration(PRIVATE_STORE_CACHE_NAME, createConfiguration(getClass().getSimpleName(), false, transactional, passivation, index).build()); index++; } } public void testPutIfAbsentOnPrimaryOwnerWithSkipCacheLoaderShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.PRIMARY, Flag.SKIP_CACHE_LOAD, true); } public void testPutIfAbsentOnPrimaryOwnerWithSkipCacheLoader() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.PRIMARY, Flag.SKIP_CACHE_LOAD, false); } public void testPutIfAbsentOnPrimaryOwnerWithIgnoreReturnValuesShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.PRIMARY, Flag.IGNORE_RETURN_VALUES, true); } public void testPutIfAbsentOnPrimaryOwnerWithIgnoreReturnValues() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.PRIMARY, Flag.IGNORE_RETURN_VALUES, false); } public void testPutIfAbsentOnPrimaryOwnerShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.PRIMARY, null, true); } public void testPutIfAbsentOnPrimaryOwner() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.PRIMARY, null, false); } @InCacheMode(CacheMode.DIST_SYNC) public void testPutIfAbsentOnBackupOwnerWithSkipCacheLoaderShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.BACKUP, Flag.SKIP_CACHE_LOAD, true); } @InCacheMode(CacheMode.DIST_SYNC) public void testPutIfAbsentOnBackupOwnerWithSkipCacheLoader() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.BACKUP, Flag.SKIP_CACHE_LOAD, false); } @InCacheMode(CacheMode.DIST_SYNC) public void testPutIfAbsentOnBackupOwnerWithIgnoreReturnValuesShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.BACKUP, Flag.IGNORE_RETURN_VALUES, true); } @InCacheMode(CacheMode.DIST_SYNC) public void testPutIfAbsentOnBackupOwnerWithIgnoreReturnValues() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.BACKUP, Flag.IGNORE_RETURN_VALUES, false); } @InCacheMode(CacheMode.DIST_SYNC) public void testPutIfAbsentOnBackupOwnerShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.BACKUP, null, true); } @InCacheMode(CacheMode.DIST_SYNC) public void testPutIfAbsentOnBackupOwner() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.BACKUP, null, false); } public void testPutIfAbsentOnNonOwnerWithSkipCacheLoaderShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.NON_OWNER, Flag.SKIP_CACHE_LOAD, true); } public void testPutIfAbsentOnNonOwnerWithSkipCacheLoader() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.NON_OWNER, Flag.SKIP_CACHE_LOAD, false); } public void testPutIfAbsentOnNonOwnerWithIgnoreReturnValuesShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.NON_OWNER, Flag.IGNORE_RETURN_VALUES, true); } public void testPutIfAbsentOnNonOwnerWithIgnoreReturnValues() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.NON_OWNER, Flag.IGNORE_RETURN_VALUES, false); } public void testPutIfAbsentOnNonOwnerShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.NON_OWNER, null, true); } public void testPutIfAbsentOnNonOwner() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.PUT_IF_ABSENT, Ownership.NON_OWNER, null, false); } public void testReplaceOnPrimaryOwnerWithSkipCacheLoaderShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.PRIMARY, Flag.SKIP_CACHE_LOAD, true); } public void testReplaceOnPrimaryOwnerWithSkipCacheLoader() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.PRIMARY, Flag.SKIP_CACHE_LOAD, false); } public void testReplaceOnPrimaryOwnerWithIgnoreReturnValuesShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.PRIMARY, Flag.IGNORE_RETURN_VALUES, true); } public void testReplaceOnPrimaryOwnerWithIgnoreReturnValues() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.PRIMARY, Flag.IGNORE_RETURN_VALUES, false); } public void testReplaceOnPrimaryOwnerShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.PRIMARY, null, true); } public void testReplaceOnPrimaryOwner() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.PRIMARY, null, false); } @InCacheMode(CacheMode.DIST_SYNC) public void testReplaceOnBackupOwnerWithSkipCacheLoaderShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.BACKUP, Flag.SKIP_CACHE_LOAD, true); } @InCacheMode(CacheMode.DIST_SYNC) public void testReplaceOnBackupOwnerWithSkipCacheLoader() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.BACKUP, Flag.SKIP_CACHE_LOAD, false); } @InCacheMode(CacheMode.DIST_SYNC) public void testReplaceOnBackupOwnerWithIgnoreReturnValuesShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.BACKUP, Flag.IGNORE_RETURN_VALUES, true); } @InCacheMode(CacheMode.DIST_SYNC) public void testReplaceOnBackupOwnerWithIgnoreReturnValues() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.BACKUP, Flag.IGNORE_RETURN_VALUES, false); } @InCacheMode(CacheMode.DIST_SYNC) public void testReplaceOnBackupOwnerShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.BACKUP, null, true); } @InCacheMode(CacheMode.DIST_SYNC) public void testReplaceOnBackupOwner() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.BACKUP, null, false); } public void testReplaceOnNonOwnerWithSkipCacheLoaderShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.NON_OWNER, Flag.SKIP_CACHE_LOAD, true); } public void testReplaceOnNonOwnerWithSkipCacheLoader() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.NON_OWNER, Flag.SKIP_CACHE_LOAD, false); } public void testReplaceOnNonOwnerWithIgnoreReturnValuesShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.NON_OWNER, Flag.IGNORE_RETURN_VALUES, true); } public void testReplaceOnNonOwnerWithIgnoreReturnValues() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.NON_OWNER, Flag.IGNORE_RETURN_VALUES, false); } public void testReplaceOnNonOwnerShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.NON_OWNER, null, true); } public void testReplaceOnNonOwner() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE, Ownership.NON_OWNER, null, false); } public void testReplaceIfOnPrimaryOwnerWithSkipCacheLoaderShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.PRIMARY, Flag.SKIP_CACHE_LOAD, true); } public void testReplaceIfOnPrimaryOwnerWithSkipCacheLoader() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.PRIMARY, Flag.SKIP_CACHE_LOAD, false); } public void testReplaceIfOnPrimaryOwnerWithIgnoreReturnValuesShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.PRIMARY, Flag.IGNORE_RETURN_VALUES, true); } public void testReplaceIfOnPrimaryOwnerWithIgnoreReturnValues() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.PRIMARY, Flag.IGNORE_RETURN_VALUES, false); } public void testReplaceIfOnPrimaryOwnerShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.PRIMARY, null, true); } public void testReplaceIfOnPrimaryOwner() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.PRIMARY, null, false); } @InCacheMode(CacheMode.DIST_SYNC) public void testReplaceIfOnBackupOwnerWithSkipCacheLoaderShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.BACKUP, Flag.SKIP_CACHE_LOAD, true); } @InCacheMode(CacheMode.DIST_SYNC) public void testReplaceIfOnBackupOwnerWithSkipCacheLoader() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.BACKUP, Flag.SKIP_CACHE_LOAD, false); } @InCacheMode(CacheMode.DIST_SYNC) public void testReplaceIfOnBackupOwnerWithIgnoreReturnValuesShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.BACKUP, Flag.IGNORE_RETURN_VALUES, true); } @InCacheMode(CacheMode.DIST_SYNC) public void testReplaceIfOnBackupOwnerWithIgnoreReturnValues() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.BACKUP, Flag.IGNORE_RETURN_VALUES, false); } @InCacheMode(CacheMode.DIST_SYNC) public void testReplaceIfOnBackupOwnerShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.BACKUP, null, true); } @InCacheMode(CacheMode.DIST_SYNC) public void testReplaceIfOnBackupOwner() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.BACKUP, null, false); } public void testReplaceIfOnNonOwnerWithSkipCacheLoaderShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.NON_OWNER, Flag.SKIP_CACHE_LOAD, true); } public void testReplaceIfOnNonOwnerWithSkipCacheLoader() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.NON_OWNER, Flag.SKIP_CACHE_LOAD, false); } public void testReplaceIfOnNonOwnerWithIgnoreReturnValuesShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.NON_OWNER, Flag.IGNORE_RETURN_VALUES, true); } public void testReplaceIfOnNonOwnerWithIgnoreReturnValues() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.NON_OWNER, Flag.IGNORE_RETURN_VALUES, false); } public void testReplaceIfOnNonOwnerShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.NON_OWNER, null, true); } public void testReplaceIfOnNonOwner() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REPLACE_IF, Ownership.NON_OWNER, null, false); } public void testRemoveIfOnPrimaryOwnerWithSkipCacheLoaderShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.PRIMARY, Flag.SKIP_CACHE_LOAD, true); } public void testRemoveIfOnPrimaryOwnerWithSkipCacheLoader() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.PRIMARY, Flag.SKIP_CACHE_LOAD, false); } public void testRemoveIfOnPrimaryOwnerWithIgnoreReturnValuesShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.PRIMARY, Flag.IGNORE_RETURN_VALUES, true); } public void testRemoveIfOnPrimaryOwnerWithIgnoreReturnValues() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.PRIMARY, Flag.IGNORE_RETURN_VALUES, false); } public void testRemoveIfOnPrimaryOwnerShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.PRIMARY, null, true); } public void testRemoveIfOnPrimaryOwner() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.PRIMARY, null, false); } @InCacheMode(CacheMode.DIST_SYNC) public void testRemoveIfOnBackupOwnerWithSkipCacheLoaderShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.BACKUP, Flag.SKIP_CACHE_LOAD, true); } @InCacheMode(CacheMode.DIST_SYNC) public void testRemoveIfOnBackupOwnerWithSkipCacheLoader() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.BACKUP, Flag.SKIP_CACHE_LOAD, false); } @InCacheMode(CacheMode.DIST_SYNC) public void testRemoveIfOnBackupOwnerWithIgnoreReturnValuesShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.BACKUP, Flag.IGNORE_RETURN_VALUES, true); } @InCacheMode(CacheMode.DIST_SYNC) public void testRemoveIfOnBackupOwnerWithIgnoreReturnValues() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.BACKUP, Flag.IGNORE_RETURN_VALUES, false); } @InCacheMode(CacheMode.DIST_SYNC) public void testRemoveIfOnBackupOwnerShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.BACKUP, null, true); } @InCacheMode(CacheMode.DIST_SYNC) public void testRemoveIfOnBackupOwner() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.BACKUP, null, false); } public void testRemoveIfOnNonOwnerWithSkipCacheLoaderShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.NON_OWNER, Flag.SKIP_CACHE_LOAD, true); } public void testRemoveIfOnNonOwnerWithSkipCacheLoader() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.NON_OWNER, Flag.SKIP_CACHE_LOAD, false); } public void testRemoveIfOnNonOwnerWithIgnoreReturnValuesShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.NON_OWNER, Flag.IGNORE_RETURN_VALUES, true); } public void testRemoveIfOnNonOwnerWithIgnoreReturnValues() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.NON_OWNER, Flag.IGNORE_RETURN_VALUES, false); } public void testRemoveIfOnNonOwnerShared() { doTest(SHARED_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.NON_OWNER, null, true); } public void testRemoveIfOnNonOwner() { doTest(PRIVATE_STORE_CACHE_NAME, ConditionalOperation.REMOVE_IF, Ownership.NON_OWNER, null, false); } protected enum ConditionalOperation { PUT_IF_ABSENT { @Override public <K, V> void execute(Cache<K, V> cache, K key, V value1, V value2) { cache.putIfAbsent(key, value2); } @Override public <V> V finalValue(V value1, V value2, boolean skipLoad) { return skipLoad ? value2 : value1; } }, REPLACE { @Override public <K, V> void execute(Cache<K, V> cache, K key, V value1, V value2) { cache.replace(key, value2); } @Override public <V> V finalValue(V value1, V value2, boolean skipLoad) { return skipLoad ? value1 : value2; } }, REPLACE_IF { @Override public <K, V> void execute(Cache<K, V> cache, K key, V value1, V value2) { cache.replace(key, value1, value2); } @Override public <V> V finalValue(V value1, V value2, boolean skipLoad) { return skipLoad ? value1 : value2; } }, REMOVE_IF { @Override public <K, V> void execute(Cache<K, V> cache, K key, V value1, V value2) { cache.remove(key, value1); } @Override public <V> V finalValue(V value1, V value2, boolean skipLoad) { return skipLoad ? value1 : null; } }; public abstract <K, V> void execute(Cache<K, V> cache, K key, V value1, V value2); public abstract <V> V finalValue(V value1, V value2, boolean skipLoad); } protected static class CacheHelper<K, V> { private final Map<Ownership, Cache<K, V>> cacheEnumMap; private CacheHelper() { cacheEnumMap = new EnumMap<>(Ownership.class); } public boolean addCache(Ownership ownership, Cache<K, V> cache) { boolean contains = cacheEnumMap.containsKey(ownership); if (!contains) { cacheEnumMap.put(ownership, cache); } return !contains; } private Cache<K, V> cache(Ownership ownership) { return cacheEnumMap.get(ownership); } private DummyInMemoryStore cacheStore(Ownership ownership) { Cache<K, V> cache = cache(ownership); return cache != null ? getFirstStore(cache) : null; } protected long loads(Ownership ownership) { Cache<K, V> cache = cache(ownership); if (cache == null) return 0; AsyncInterceptorChain chain = extractComponent(cache, AsyncInterceptorChain.class); CacheLoaderInterceptor interceptor = chain.findInterceptorExtending(CacheLoaderInterceptor.class); return interceptor.getCacheLoaderLoads(); } private void resetStats(Ownership ownership) { Cache<K, V> cache = cache(ownership); if (cache == null) return; AsyncInterceptorChain chain = extractComponent(cache, AsyncInterceptorChain.class); CacheLoaderInterceptor interceptor = chain.findInterceptorExtending( CacheLoaderInterceptor.class); interceptor.resetStatistics(); } } }
27,645
41.207634
153
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/ClusteredConditionalCommandPassivationTest.java
package org.infinispan.persistence; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.fwk.InCacheMode; import org.testng.annotations.Test; /** * Tests if the conditional commands correctly fetch the value from cache loader even with the skip cache load/store * flags. * <p/> * The configuration used is a non-tx distributed cache with passivation. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "functional", testName = "persistence.ClusteredConditionalCommandPassivationTest") @InCacheMode({ CacheMode.DIST_SYNC }) public class ClusteredConditionalCommandPassivationTest extends ClusteredConditionalCommandTest { public ClusteredConditionalCommandPassivationTest() { super(false, true); } }
754
29.2
116
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/keymappers/DefaultTwoWayKey2StringMapperTest.java
package org.infinispan.persistence.keymappers; import java.util.UUID; import org.infinispan.commons.util.Util; import org.testng.annotations.Test; @Test(groups = "unit", testName = "persistence.keymappers.DefaultTwoWayKey2StringMapperTest") public class DefaultTwoWayKey2StringMapperTest { DefaultTwoWayKey2StringMapper mapper = new DefaultTwoWayKey2StringMapper(); public void testKeyMapper() { String skey = mapper.getStringMapping("k1"); assert skey.equals("k1"); skey = mapper.getStringMapping(Integer.valueOf(100)); assert !skey.equals("100"); Integer i = (Integer) mapper.getKeyMapping(skey); assert i == 100; skey = mapper.getStringMapping(Boolean.TRUE); assert !skey.equalsIgnoreCase("true"); Boolean b = (Boolean) mapper.getKeyMapping(skey); assert b; skey = mapper.getStringMapping(Double.valueOf(3.141592d)); assert !skey.equals("3.141592"); Double d = (Double) mapper.getKeyMapping(skey); assert d == 3.141592d; UUID uuid = Util.threadLocalRandomUUID(); skey = mapper.getStringMapping(uuid); assert !uuid.equals(uuid.toString()); UUID u = (UUID) mapper.getKeyMapping(skey); assert u.equals(uuid); } public void testPrimitivesAreSupported() { assert mapper.isSupportedType(Integer.class); assert mapper.isSupportedType(Byte.class); assert mapper.isSupportedType(Short.class); assert mapper.isSupportedType(Long.class); assert mapper.isSupportedType(Double.class); assert mapper.isSupportedType(Float.class); assert mapper.isSupportedType(Boolean.class); assert mapper.isSupportedType(String.class); } public void testTwoWayContract() { Object[] toTest = { 0, new Byte("1"), new Short("2"), (long) 3, new Double("3.4"), new Float("3.5"), Boolean.FALSE, "some string" }; for (Object o : toTest) { Class<?> type = o.getClass(); String rep = mapper.getStringMapping(o); assert o.equals(mapper.getKeyMapping(rep)) : String.format("Failed on type %s and value %s", type, rep); } } public void testAssumption() { // even if they have the same value, they have a different type assert !new Float(3.0f).equals(new Integer(3)); } public void testString() { assert mapper.isSupportedType(String.class); assert assertWorks("") : "Expected empty string, was " + mapper.getStringMapping(""); assert assertWorks("mircea") : "Expected 'mircea', was " + mapper.getStringMapping("mircea"); } public void testShort() { assert mapper.isSupportedType(Short.class); assert assertWorks((short) 2); } public void testByte() { assert mapper.isSupportedType(Byte.class); assert assertWorks((byte) 2); } public void testLong() { assert mapper.isSupportedType(Long.class); assert assertWorks(new Long(2)); } public void testInteger() { assert mapper.isSupportedType(Integer.class); assert assertWorks(2); } public void testDouble() { assert mapper.isSupportedType(Double.class); assert assertWorks(2.4d); } public void testFloat() { assert mapper.isSupportedType(Float.class); assert assertWorks(2.1f); } public void testBoolean() { assert mapper.isSupportedType(Boolean.class); assert assertWorks(true); assert assertWorks(false); } public void testUuid() { assert mapper.isSupportedType(UUID.class); assert assertWorks(Util.threadLocalRandomUUID()); } private boolean assertWorks(Object key) { return mapper.getKeyMapping(mapper.getStringMapping(key)).equals(key); } }
3,720
28.299213
138
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/manager/PersistenceManagerTest.java
package org.infinispan.persistence.manager; import static org.infinispan.commons.test.Exceptions.expectCompletionException; import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.BOTH; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.getFirstStore; import static org.infinispan.test.TestingUtil.getStore; import static org.infinispan.util.concurrent.CompletionStages.join; 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.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.commons.IllegalLifecycleStateException; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.util.ByRef; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.support.DelayStore; import org.infinispan.persistence.support.FailStore; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestException; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.subscribers.TestSubscriber; /** * A {@link PersistenceManager} unit test. * * @author Pedro Ruivo * @since 9.3 */ @Test(groups = "unit", testName = "persistence.PersistenceManagerTest") @CleanupAfterMethod public class PersistenceManagerTest extends SingleCacheManagerTest { /** * Simulates cache receiving a topology update while stopping. */ public void testPublishAfterStop() { PersistenceManager persistenceManager = extractComponent(cache, PersistenceManager.class); KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); String key = "k"; insertEntry(persistenceManager, keyPartitioner, key, "v"); persistenceManager.stop(); ByRef<Throwable> tRef = new ByRef<>(null); // The stopped PersistenceManager should never pass the request to the store Flowable.fromPublisher(persistenceManager.publishEntries(true, true)) .blockingSubscribe(ignore -> fail("shouldn't run"), tRef::set); Throwable t = tRef.get(); Exceptions.assertException(IllegalLifecycleStateException.class, t); } /** * Simulates cache stopping while processing a state request. */ public void testStopDuringPublish() throws ExecutionException, InterruptedException, TimeoutException { PersistenceManager persistenceManager = extractComponent(cache, PersistenceManager.class); KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); insertEntry(persistenceManager, keyPartitioner, "k1", "v1"); insertEntry(persistenceManager, keyPartitioner, "k2", "v2"); insertEntry(persistenceManager, keyPartitioner, "k3", "v3"); DelayStore store = getFirstStore(cache); store.delayBeforeEmit(1); CountDownLatch before = new CountDownLatch(1); CountDownLatch after = new CountDownLatch(1); Future<Integer> publisherFuture = fork(() -> { TestSubscriber<Object> subscriber = TestSubscriber.create(0); Flowable.fromPublisher(persistenceManager.publishEntries(true, true)) .subscribe(subscriber); before.countDown(); assertTrue(after.await(10, TimeUnit.SECONDS)); // request all the elements after we have initiated stop subscriber.request(Long.MAX_VALUE); subscriber.await(10, TimeUnit.SECONDS); subscriber.assertNoErrors(); subscriber.assertComplete(); return subscriber.values().size(); }); assertTrue(before.await(30, TimeUnit.SECONDS)); Future<Void> stopFuture = fork(persistenceManager::stop); // Stop is unable to proceed while the publisher hasn't completed Thread.sleep(50); assertFalse(stopFuture.isDone()); assertFalse(publisherFuture.isDone()); after.countDown(); // Publisher can't continue because the store emit is delayed Thread.sleep(50); assertFalse(stopFuture.isDone()); assertFalse(publisherFuture.isDone()); // Emit the entries and allow PMI to stop store.endDelay(); Integer count = publisherFuture.get(30, TimeUnit.SECONDS); stopFuture.get(30, TimeUnit.SECONDS); assertEquals(3, count.intValue()); } public void testEarlyTerminatedPublish() { PersistenceManager persistenceManager = extractComponent(cache, PersistenceManager.class); KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); // This has to be > 128 - as the flowable pulls a chunk of that size for (int i = 0; i < 140; ++i) { String key = "k" + i; insertEntry(persistenceManager, keyPartitioner, key, "v"); } DelayStore store = getFirstStore(cache); store.delayBeforeEmit(1); PersistenceManagerImpl pmImpl = (PersistenceManagerImpl) persistenceManager; assertFalse(pmImpl.anyLocksHeld()); assertFalse(cache.isEmpty()); assertFalse(pmImpl.anyLocksHeld()); store.endDelay(); } public void testStoreExceptionInWrite() { PersistenceManager pm = extractComponent(cache, PersistenceManager.class); KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); DelayStore store1 = getStore(cache, 0, true); FailStore store2 = getStore(cache, 1, true); store2.failModification(2); String key = "k"; int segment = keyPartitioner.getSegment(key); expectCompletionException(TestException.class, pm.writeToAllNonTxStores(MarshalledEntryUtil.create(key, "v", cache), segment, BOTH)); assertTrue(store1.contains(key)); expectCompletionException(TestException.class, pm.deleteFromAllStores(key, segment, BOTH)); assertFalse(store1.contains(key)); } @Override protected EmbeddedCacheManager createCacheManager() { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg.persistence().addStore(DelayStore.ConfigurationBuilder.class); cfg.persistence().addStore(FailStore.ConfigurationBuilder.class); cfg.persistence().addStore(FailStore.ConfigurationBuilder.class); return TestCacheManagerFactory.createCacheManager(cfg); } private void insertEntry(PersistenceManager persistenceManager, KeyPartitioner keyPartitioner, String k, String v) { join(persistenceManager.writeToAllNonTxStores(MarshalledEntryUtil.create(k, v, cache), keyPartitioner.getSegment(k), BOTH)); } }
7,167
41.414201
119
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/dummy/DummyInMemoryStoreTest.java
package org.infinispan.persistence.dummy; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.BaseNonBlockingStoreTest; import org.infinispan.persistence.spi.NonBlockingStore; import org.testng.annotations.Test; @Test(groups = "unit", testName = "persistence.dummy.DummyInMemoryStoreTest") public class DummyInMemoryStoreTest extends BaseNonBlockingStoreTest { @Override protected NonBlockingStore createStore() { return new DummyInMemoryStore(); } @Override protected Configuration buildConfig(ConfigurationBuilder configurationBuilder) { return configurationBuilder.persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(getClass().getName()) .build(); } }
858
33.36
83
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/dummy/Element.java
package org.infinispan.persistence.dummy; import java.util.HashMap; import java.util.Map; /** * An enumeration of all the recognized XML element local names for the DummyInMemory cache store */ public enum Element { // must be first UNKNOWN(null), DUMMY_STORE("dummy-store"); private final String name; Element(final String name) { this.name = name; } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, Element> MAP; static { final Map<String, Element> map = new HashMap<String, Element>(8); for (Element element : values()) { final String name = element.getLocalName(); if (name != null) { map.put(name, element); } } MAP = map; } public static Element forName(final String localName) { final Element element = MAP.get(localName); return element == null ? UNKNOWN : element; } @Override public String toString() { return name; } }
1,105
19.481481
97
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/dummy/DummyInMemoryStoreConfiguration.java
package org.infinispan.persistence.dummy; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.ConfigurationFor; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.cache.AbstractStoreConfiguration; import org.infinispan.configuration.cache.AsyncStoreConfiguration; @BuiltBy(DummyInMemoryStoreConfigurationBuilder.class) @ConfigurationFor(DummyInMemoryStore.class) public class DummyInMemoryStoreConfiguration extends AbstractStoreConfiguration<DummyInMemoryStoreConfiguration> { static final AttributeDefinition<Boolean> SLOW = AttributeDefinition.builder("slow", false).immutable().build(); static final AttributeDefinition<String> STORE_NAME = AttributeDefinition.builder("store-name", null, String.class).immutable().build(); static final AttributeDefinition<Integer> START_FAILURES = AttributeDefinition.builder("start-failures", 0).immutable().build(); public static AttributeSet attributeDefinitionSet() { return new AttributeSet(DummyInMemoryStoreConfiguration.class, AbstractStoreConfiguration.attributeDefinitionSet(), SLOW, STORE_NAME, START_FAILURES); } public DummyInMemoryStoreConfiguration(AttributeSet attributes, AsyncStoreConfiguration async) { super(Element.DUMMY_STORE, attributes, async); } public boolean slow() { return attributes.attribute(SLOW).get(); } public String storeName() { return attributes.attribute(STORE_NAME).get(); } public int startFailures() { return attributes.attribute(START_FAILURES).get(); } }
1,688
45.916667
156
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/dummy/DummyInMemoryStore.java
package org.infinispan.persistence.dummy; import java.io.IOException; import java.lang.reflect.Method; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.PrimitiveIterator; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.function.Predicate; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.commons.IllegalLifecycleStateException; import org.infinispan.commons.configuration.ConfiguredBy; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.persistence.Store; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.infinispan.commons.util.Util; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.configuration.cache.ClusteringConfiguration; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.marshall.persistence.PersistenceMarshaller; import org.infinispan.persistence.spi.InitializationContext; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.MarshalledValue; import org.infinispan.persistence.spi.NonBlockingStore; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.persistence.support.WaitNonBlockingStore; import org.infinispan.test.TestingUtil; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.reactivestreams.Publisher; import io.reactivex.rxjava3.core.Flowable; /** * A Dummy cache store which stores objects in memory. Instance of the store can be shared * amongst multiple caches by utilising the same `storeName` for each store instance. */ @ConfiguredBy(DummyInMemoryStoreConfiguration.class) @Store(shared = true) public class DummyInMemoryStore implements WaitNonBlockingStore { public static final int SLOW_STORE_WAIT = 100; private static final Log log = LogFactory.getLog(DummyInMemoryStore.class); private static final ConcurrentMap<String, AtomicReferenceArray<Map<Object, byte[]>>> stores = new ConcurrentHashMap<>(); private static final ConcurrentMap<String, ConcurrentMap<String, AtomicInteger>> storeStats = new ConcurrentHashMap<>(); private String storeName; private AtomicReferenceArray<Map<Object, byte[]>> store; // When a store is 'shared', multiple nodes could be trying to update it concurrently. private ConcurrentMap<String, AtomicInteger> stats; private int segmentCount; private AtomicInteger initCount = new AtomicInteger(); private TimeService timeService; private Cache<?, ?> cache; private PersistenceMarshaller marshaller; private DummyInMemoryStoreConfiguration configuration; private KeyPartitioner keyPartitioner; private InitializationContext ctx; private volatile boolean running; private volatile boolean available; private volatile boolean exceptionOnAvailbilityCheck; private AtomicInteger startAttempts = new AtomicInteger(); @Override public CompletionStage<Void> start(InitializationContext ctx) { this.ctx = ctx; this.configuration = ctx.getConfiguration(); this.keyPartitioner = ctx.getKeyPartitioner(); this.cache = ctx.getCache(); this.marshaller = ctx.getPersistenceMarshaller(); this.storeName = makeStoreName(configuration, cache); this.initCount.incrementAndGet(); this.timeService = ctx.getTimeService(); if (store != null) return CompletableFutures.completedNull(); if (configuration.startFailures() > startAttempts.incrementAndGet()) throw new PersistenceException(); if (configuration.segmented()) { ClusteringConfiguration clusteringConfiguration = cache.getCacheConfiguration().clustering(); segmentCount = clusteringConfiguration.hash().numSegments(); } else { segmentCount = 1; } store = new AtomicReferenceArray<>(segmentCount); stats = newStatsMap(); boolean shouldStartSegments = true; if (storeName != null) { AtomicReferenceArray<Map<Object, byte[]>> existing = stores.putIfAbsent(storeName, store); if (existing != null) { store = existing; log.debugf("Reusing in-memory cache store %s", storeName); shouldStartSegments = false; } else { // Clean up the array for this test TestResourceTracker.addResource(new TestResourceTracker.Cleaner<>(storeName) { @Override public void close() { removeStoreData(ref); storeStats.remove(ref); } }); log.debugf("Creating new in-memory cache store %s", storeName); } ConcurrentMap<String, AtomicInteger> existingStats = storeStats.putIfAbsent(storeName, stats); if (existingStats != null) { stats = existingStats; } } if (shouldStartSegments) { for (int i = 0; i < segmentCount; ++i) { store.set(i, new ConcurrentHashMap<>()); } } // record at the end! record("start"); running = true; available = true; return CompletableFutures.completedNull(); } @Override public KeyPartitioner getKeyPartitioner() { return keyPartitioner; } private String makeStoreName(DummyInMemoryStoreConfiguration configuration, Cache<?, ?> cache) { String configName = configuration.storeName(); if (configName == null) return null; return cache != null ? configName + "_" + cache.getName() : configName; } public DummyInMemoryStore(String storeName) { this.storeName = storeName; } public DummyInMemoryStore() { } public boolean isRunning() { return running; } public int getInitCount() { return initCount.get(); } private void record(String method) { stats.get(method).incrementAndGet(); } private Map<Object, byte[]> mapForSegment(int segment) { if (!configuration.segmented()) { return store.get(0); } Map<Object, byte[]> map = store.get(segment); return map == null ? Collections.emptyMap() : map; } @Override public Set<Characteristic> characteristics() { return EnumSet.of(Characteristic.BULK_READ, Characteristic.EXPIRATION, Characteristic.SHAREABLE, Characteristic.SEGMENTABLE); } @Override public CompletionStage<Void> write(int segment, MarshallableEntry entry) { assertRunning(); record("write"); if (configuration.slow()) { TestingUtil.sleepThread(SLOW_STORE_WAIT); } if (log.isTraceEnabled()) log.tracef("Store %s for segment %s in dummy map store@%s", entry, segment, Util.hexIdHashCode(store)); Map<Object, byte[]> map = mapForSegment(segment); map.put(entry.getKey(), serialize(entry)); return CompletableFutures.completedNull(); } @Override public CompletionStage<Void> clear() { assertRunning(); record("clear"); if (log.isTraceEnabled()) log.trace("Clear store"); for (int i = 0; i < store.length(); ++i) { Map<Object, byte[]> map = store.get(i); if (map != null) { map.clear(); } } return CompletableFutures.completedNull(); } @Override public CompletionStage<Boolean> delete(int segment, Object key) { assertRunning(); record("delete"); Map<Object, byte[]> map = mapForSegment(segment); if (map.remove(key) != null) { if (log.isTraceEnabled()) log.tracef("Removed %s from dummy store for segment %s", key, segment); return CompletableFutures.completedTrue(); } if (log.isTraceEnabled()) log.tracef("Key %s not present in store, so don't remove", key); return CompletableFutures.completedFalse(); } @Override public Publisher<MarshallableEntry> purgeExpired() { assertRunning(); record("purgeExpired"); return Flowable.defer(() -> { long currentTimeMillis = timeService.wallClockTime(); return Flowable.range(0, store.length()) .concatMap(offset -> { Map<Object, byte[]> map = store.get(offset); if (map == null) { return Flowable.empty(); } return Flowable.fromIterable(map.entrySet()) .map(entry -> deserialize(entry.getKey(), entry.getValue())) .filter(me -> isExpired(me, currentTimeMillis)) .doOnNext(me -> map.remove(me.getKey())); }); }); } @Override public CompletionStage<MarshallableEntry> load(int segment, Object key) { assertRunning(); record("load"); if (key == null) return null; Map<Object, byte[]> map = mapForSegment(segment); MarshallableEntry me = deserialize(key, map.get(key)); if (me == null) return CompletableFutures.completedNull(); long now = timeService.wallClockTime(); if (isExpired(me, now)) { log.tracef("Key %s exists, but has expired. Entry is %s", key, me); return CompletableFutures.completedNull(); } return CompletableFuture.completedFuture(me); } private boolean isExpired(MarshallableEntry me, long now) { return me.isExpired(now); } @Override public Flowable<MarshallableEntry> publishEntries(IntSet segments, Predicate filter, boolean fetchValue) { assertRunning(); record("publishEntries"); log.tracef("Publishing entries in store %s segments %s with filter %s", storeName, segments, filter); Flowable<Map.Entry<Object, byte[]>> flowable; if (configuration.segmented()) { flowable = Flowable.fromIterable(segments) .concatMap(segment -> { Map<Object, byte[]> map = store.get(segment); if (map == null || map.isEmpty()) { return Flowable.<Map.Entry<Object, byte[]>>empty(); } return Flowable.fromIterable(map.entrySet()); }); } else { flowable = Flowable.fromIterable(store.get(0).entrySet()); } Flowable<MarshallableEntry> meFlowable = flowable.map(entry -> deserialize(entry.getKey(), entry.getValue())); if (filter != null) { meFlowable = meFlowable.filter(e -> filter.test(e.getKey())); } if (configuration.slow()) { meFlowable = meFlowable.doOnNext(ignore -> Thread.sleep(SLOW_STORE_WAIT)); } Flowable<MarshallableEntry> meFlowableFinal = meFlowable; // Defer the check for time, so it can be subscribed to at different times return Flowable.defer(() -> { final long currentTimeMillis = timeService.wallClockTime(); return meFlowableFinal.filter(me -> !isExpired(me, currentTimeMillis)); }); } private ConcurrentMap<String, AtomicInteger> newStatsMap() { ConcurrentMap<String, AtomicInteger> m = new ConcurrentHashMap<>(); for (Method method: NonBlockingStore.class.getMethods()) { m.put(method.getName(), new AtomicInteger(0)); } return m; } @Override public CompletionStage<Void> stop() { if (running) { record("stop"); running = false; available = false; store = null; } return CompletableFutures.completedNull(); } @Override public CompletionStage<Boolean> isAvailable() { if (exceptionOnAvailbilityCheck) { throw new RuntimeException(); } return CompletableFutures.booleanStage(available); } public void setExceptionOnAvailbilityCheck(boolean throwException) { this.exceptionOnAvailbilityCheck = throwException; } public void setAvailable(boolean available) { log.debugf("Store availability change: %s -> %s", this.available, available); this.available = available; } public String getStoreName() { return storeName; } /** * @return a count of entries in all the segments, including expired entries */ public long getStoreDataSize() { return CompletionStages.join(sizeIncludingExpired(IntSets.immutableRangeSet(store.length()), store)); } public static long getStoreDataSize(String storeName) { AtomicReferenceArray<Map<Object, byte[]>> store = stores.get(storeName); return store != null ? CompletionStages.join( sizeIncludingExpired(IntSets.immutableRangeSet(store.length()), store)) : 0; } public static void removeStoreData(String storeName) { stores.remove(storeName); } public static void removeStatData(String storeName) { storeStats.remove(storeName); } public static AtomicReferenceArray<Map<Object, byte[]>> getStoreDataForName(String storeName) { return stores.get(storeName); } public byte[] valueToStoredBytes(Object object) throws IOException, InterruptedException { ByteBuffer actualBytes = marshaller.objectToBuffer(object); MarshallableEntry<?, ?> me = ctx.getMarshallableEntryFactory().create(null, actualBytes); return marshaller.objectToByteBuffer(me.getMarshalledValue()); } public boolean isEmpty() { for (int i = 0; i < store.length(); ++i) { Map<Object, byte[]> map = store.get(i); if (map != null && !map.isEmpty()) { return false; } } return true; } public Set<Object> keySet() { Set<Object> set = new HashSet<>(); for (int i = 0; i < store.length(); ++i) { Map<Object, byte[]> map = store.get(i); if (map != null) { set.addAll(map.keySet()); } } return set; } public Map<String, Integer> stats() { Map<String, Integer> copy = new HashMap<>(stats.size()); for (String k: stats.keySet()) copy.put(k, stats.get(k).get()); return copy; } public void clearStats() { for (AtomicInteger atomicInteger: stats.values()) atomicInteger.set(0); } @Override public CompletionStage<Long> size(IntSet segments) { record("size"); AtomicLong size = new AtomicLong(); long now = timeService.wallClockTime(); for (PrimitiveIterator.OfInt iter = segments.iterator(); iter.hasNext(); ) { int segment = iter.nextInt(); Map<Object, byte[]> map = store.get(segment); if (map != null) { map.forEach((key, bytes) -> { MarshallableEntry<?, ?> me = deserialize(key, bytes); if (!me.isExpired(now)) { size.incrementAndGet(); } }); } } return CompletableFuture.completedFuture(size.get()); } /** * Helper method only invoked by tests */ public long size() { return CompletionStages.join(size(IntSets.immutableRangeSet(store.length()))); } private static CompletionStage<Long> sizeIncludingExpired(IntSet segments, AtomicReferenceArray<Map<Object, byte[]>> store) { long size = 0; for (PrimitiveIterator.OfInt iter = segments.iterator(); iter.hasNext(); ) { int segment = iter.nextInt(); Map<Object, byte[]> map = store.get(segment); if (map != null) { size += map.size(); } } return CompletableFuture.completedFuture(size); } @Override public CompletionStage<Long> approximateSize(IntSet segments) { record("size"); return sizeIncludingExpired(segments, store); } @Override public CompletionStage<Boolean> containsKey(int segment, Object key) { assertRunning(); record("containsKey"); if (key == null) return CompletableFutures.completedFalse(); Map<Object, byte[]> map = mapForSegment(segment); MarshallableEntry me = deserialize(key, map.get(key)); if (me == null) return CompletableFutures.completedFalse(); long now = timeService.wallClockTime(); if (isExpired(me, now)) { log.tracef("Key %s exists, but has expired. Entry is %s", key, me); return CompletableFutures.completedFalse(); } return CompletableFutures.completedTrue(); } private byte[] serialize(MarshallableEntry entry) { try { return marshaller.objectToByteBuffer(entry.getMarshalledValue()); } catch (IOException e) { throw new CacheException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CacheException(e); } } private MarshallableEntry deserialize(Object key, byte[] b) { try { if (b == null) return null; // We have to fetch metadata to tell if a key or entry is expired. Note this can be changed // after API changes MarshalledValue value = (MarshalledValue) marshaller.objectFromByteBuffer(b); return ctx.getMarshallableEntryFactory().create(key, value); } catch (ClassNotFoundException | IOException e) { throw new CacheException(e); } } private void assertRunning() { if (!running) throw new IllegalLifecycleStateException(); if (!available) throw new PersistenceException(); } @Override public CompletionStage<Void> addSegments(IntSet segments) { assertRunning(); record("addSegments"); if (configuration.segmented() && storeName == null) { if (log.isTraceEnabled()) log.tracef("Adding segments %s", segments); segments.forEach((int segment) -> { if (store.get(segment) == null) { store.set(segment, new ConcurrentHashMap<>()); } }); } return CompletableFutures.completedNull(); } @Override public CompletionStage<Void> removeSegments(IntSet segments) { assertRunning(); record("removeSegments"); if (configuration.segmented() && storeName == null) { if (log.isTraceEnabled()) log.tracef("Removing segments %s", segments); segments.forEach((int segment) -> store.getAndSet(segment, null)); } return CompletableFutures.completedNull(); } public DummyInMemoryStoreConfiguration getConfiguration() { return configuration; } }
18,920
34.103896
135
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/dummy/Attribute.java
package org.infinispan.persistence.dummy; import java.util.HashMap; import java.util.Map; /** * Enumerates the attributes used by the Dummy cache store configuration */ public enum Attribute { // must be first UNKNOWN(null), STORE_NAME("store-name"), START_FAILURES("start-failures"), SLOW("slow"); private final String name; Attribute(final String name) { this.name = name; } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, Attribute> attributes; static { Map<String, Attribute> map = new HashMap<>(); for (Attribute attribute : values()) { final String name = attribute.getLocalName(); if (name != null) { map.put(name, attribute); } } attributes = map; } public static Attribute forName(final String localName) { final Attribute attribute = attributes.get(localName); return attribute == null ? UNKNOWN : attribute; } @Override public String toString() { return name; } }
1,157
19.678571
72
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/dummy/DummyInMemoryStoreFunctionalTest.java
package org.infinispan.persistence.dummy; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; import org.infinispan.persistence.BaseStoreFunctionalTest; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; @Test(groups = "unit", testName = "persistence.dummy.DummyInMemoryStoreFunctionalTest") public class DummyInMemoryStoreFunctionalTest extends BaseStoreFunctionalTest { @AfterClass protected void clearTempDir() { DummyInMemoryStore.removeStoreData(getClass().getName()); } @Override protected PersistenceConfigurationBuilder createCacheStoreConfig(PersistenceConfigurationBuilder persistence, String cacheName, boolean preload) { persistence .addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(getClass().getName()) .purgeOnStartup(false).preload(preload); return persistence; } }
933
36.36
112
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/dummy/DummyInMemoryStoreConfigurationBuilder.java
package org.infinispan.persistence.dummy; import static org.infinispan.persistence.dummy.DummyInMemoryStoreConfiguration.SLOW; import static org.infinispan.persistence.dummy.DummyInMemoryStoreConfiguration.START_FAILURES; import static org.infinispan.persistence.dummy.DummyInMemoryStoreConfiguration.STORE_NAME; import org.infinispan.commons.configuration.Combine; import org.infinispan.configuration.cache.AbstractStoreConfigurationBuilder; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; public class DummyInMemoryStoreConfigurationBuilder extends AbstractStoreConfigurationBuilder<DummyInMemoryStoreConfiguration, DummyInMemoryStoreConfigurationBuilder> { public DummyInMemoryStoreConfigurationBuilder(PersistenceConfigurationBuilder builder) { super(builder, DummyInMemoryStoreConfiguration.attributeDefinitionSet()); } @Override public DummyInMemoryStoreConfigurationBuilder self() { return this; } /** * If true, then writes to this store are artificially slowed by {@value DummyInMemoryStore#SLOW_STORE_WAIT} milliseconds. * @deprecated Use {@link org.infinispan.persistence.support.DelayStore} instead. */ @Deprecated public DummyInMemoryStoreConfigurationBuilder slow(boolean slow) { attributes.attribute(SLOW).set(slow); return this; } /** * A storeName can be utilised to lookup existing DummyInMemoryStore instances associated with the provided String. If * an instance is already mapped to the provided string, then that instance is utilised. Otherwise a new instance is * created and associated with the given string. This can be useful for testing shared stores, across multiple CacheManager instances. */ public DummyInMemoryStoreConfigurationBuilder storeName(String storeName) { attributes.attribute(STORE_NAME).set(storeName); return this; } public DummyInMemoryStoreConfigurationBuilder startFailures(int failures) { attributes.attribute(START_FAILURES).set(failures); return this; } @Override public DummyInMemoryStoreConfiguration create() { return new DummyInMemoryStoreConfiguration(attributes.protect(), async.create()); } @Override public DummyInMemoryStoreConfigurationBuilder read(DummyInMemoryStoreConfiguration template, Combine combine) { super.read(template, combine); return this; } }
2,418
39.316667
137
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/dummy/DummyInMemoryStoreConfigurationParser.java
package org.infinispan.persistence.dummy; import static org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationParser.NAMESPACE; import org.infinispan.commons.configuration.io.ConfigurationReader; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ConfigurationParser; import org.infinispan.configuration.parsing.Namespace; import org.infinispan.configuration.parsing.ParseUtils; import org.infinispan.configuration.parsing.Parser; import org.kohsuke.MetaInfServices; /** * @author William Burns * @since 14.0 */ @MetaInfServices @Namespace(root = "dummy-store") @Namespace(uri = NAMESPACE + "*", root = "dummy-store") public class DummyInMemoryStoreConfigurationParser implements ConfigurationParser { static final String NAMESPACE = Parser.NAMESPACE + "store:dummy:"; @Override public void readElement(ConfigurationReader reader, ConfigurationBuilderHolder holder) { Element element = Element.forName(reader.getLocalName()); switch (element) { case DUMMY_STORE: { ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder(); parseDummyCacheStore(reader, builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class)); break; } default: { throw ParseUtils.unexpectedElement(reader); } } } private void parseDummyCacheStore(ConfigurationReader reader, DummyInMemoryStoreConfigurationBuilder builder) { for (int i = 0; i < reader.getAttributeCount(); i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); String value = reader.getAttributeValue(i); Attribute attribute = Attribute.forName(reader.getAttributeName(i)); switch (attribute) { case SLOW: builder.slow(Boolean.valueOf(value)); break; case START_FAILURES: builder.startFailures(Integer.parseInt(value)); break; case STORE_NAME: builder.storeName(value); break; default: { Parser.parseStoreAttribute(reader, i, builder); } } } while (reader.inTag()) { Parser.parseStoreElement(reader, builder); } } @Override public Namespace[] getNamespaces() { return ParseUtils.getNamespaceAnnotations(getClass()); } }
2,531
33.216216
119
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/file/SingleFileStoreTest.java
package org.infinispan.persistence.file; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.util.concurrent.CompletionStage; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.util.IntSets; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; import org.infinispan.configuration.cache.SingleFileStoreConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.BaseNonBlockingStoreTest; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.NonBlockingStore; import org.infinispan.test.fwk.TestInternalCacheEntryFactory; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.AfterClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "unit", testName = "persistence.SingleFile.SingleFileStoreTest") public class SingleFileStoreTest extends BaseNonBlockingStoreTest { private String tmpDirectory = CommonsTestingUtil.tmpDirectory(this.getClass()); private boolean segmented; @AfterClass(alwaysRun = true) protected void clearTempDir() { Util.recursiveFileRemove(tmpDirectory); } public SingleFileStoreTest segmented(boolean segmented) { this.segmented = segmented; return this; } @Factory public Object[] factory() { return new Object[] { new SingleFileStoreTest().segmented(false), new SingleFileStoreTest().segmented(true), }; } @Override protected String parameters() { return "[" + segmented + "]"; } @Override protected Configuration buildConfig(ConfigurationBuilder cb) { createCacheStoreConfig(cb.persistence()); return cb.build(); } protected SingleFileStoreConfigurationBuilder createCacheStoreConfig(PersistenceConfigurationBuilder lcb) { SingleFileStoreConfigurationBuilder cfg = lcb.addStore(SingleFileStoreConfigurationBuilder.class); cfg.segmented(segmented); cfg.location(tmpDirectory); cfg.fragmentationFactor(0.5f); return cfg; } @Override protected NonBlockingStore createStore() { clearTempDir(); return new SingleFileStore<>(); } /** * Test to make sure that when segments are added or removed that there are no issues */ public void testSegmentsRemovedAndAdded() { Object key = "first-key"; Object value = "some-value"; int segment = keyPartitioner.getSegment(key); if (!segmented) { Exceptions.expectException(UnsupportedOperationException.class, () -> store.removeSegments(IntSets.immutableSet(segment))); Exceptions.expectException(UnsupportedOperationException.class, () -> store.addSegments(IntSets.immutableSet(segment))); return; } InternalCacheEntry entry = TestInternalCacheEntryFactory.create(key, value); MarshallableEntry me = MarshalledEntryUtil.create(entry, getMarshaller()); store.write(me); assertTrue(store.contains(key)); // Now remove the segment that held our key CompletionStages.join(store.removeSegments(IntSets.immutableSet(segment))); assertFalse(store.contains(key)); // Now add the segment back CompletionStages.join(store.addSegments(IntSets.immutableSet(segment))); store.write(me); assertTrue(store.contains(key)); } public void testStopDuringClear() { InternalCacheEntry entry = TestInternalCacheEntryFactory.create("key", "value"); MarshallableEntry me = MarshalledEntryUtil.create(entry, getMarshaller()); store.write(me); CompletionStage<Void> clearStage = store.clear(); store.stopAndWait(); CompletionStages.join(clearStage); // The store must be able to start startStore(store); // But because clear does its work on a separate thread, it may run after stop long size = CompletionStages.join(store.size(IntSets.immutableRangeSet(segmentCount))); assertTrue(size == 0 || size == 1); } }
4,491
33.553846
110
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/file/SingleFileStoreCompatibilityTest.java
package org.infinispan.persistence.file; import static org.infinispan.persistence.file.SingleFileStore.getStoreFile; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionException; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.configuration.cache.AbstractSegmentedStoreConfiguration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.AbstractPersistenceCompatibilityTest; import org.infinispan.persistence.IdentityKeyValueWrapper; import org.infinispan.test.data.Value; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Tests if {@link SingleFileStore} can migrate data from Infinispan 10.1.x. * * @author Pedro Ruivo * @since 11.0 */ @Test(groups = "functional", testName = "persistence.file.SingleFileStoreCompatibilityTest") public class SingleFileStoreCompatibilityTest extends AbstractPersistenceCompatibilityTest<Value> { private static final Map<Version, String> files = new HashMap<>(); static { files.put(Version._10_1, "sfs/10_1/sfs-store-cache.dat"); files.put(Version._11_0, "sfs/11_0/sfs-store-cache.dat"); files.put(Version._12_1, "sfs/12_1/sfs-store-cache.dat"); } private static final Map<Version, byte[]> magic = new HashMap<>(); static { magic.put(Version._10_1, SingleFileStore.MAGIC_BEFORE_11); magic.put(Version._11_0, SingleFileStore.MAGIC_11_0); magic.put(Version._12_0, SingleFileStore.MAGIC_12_0); magic.put(Version._12_1, SingleFileStore.MAGIC_12_1); } public SingleFileStoreCompatibilityTest() { super(IdentityKeyValueWrapper.instance()); } @DataProvider public Object[][] segmented() { return new Object[][] { {false, false}, {false, true}, {true, false}, {true, true}, }; } @Test(dataProvider = "segmented") public void testReadWriteFrom101(boolean oldSegmented, boolean newSegmented) throws Exception { setParameters(Version._10_1, oldSegmented, newSegmented); beforeStartCache(); cacheManager.defineConfiguration(cacheName(), cacheConfiguration(false).build()); Exceptions.expectException(CacheConfigurationException.class, CompletionException.class, ".*ISPN000616.*", () -> cacheManager.getCache(cacheName())); } @Test(dataProvider = "segmented") public void testReadWriteFrom11(boolean oldSegmented, boolean newSegmented) throws Exception { setParameters(Version._11_0, oldSegmented, newSegmented); doTestReadWrite(); } @Test(dataProvider = "segmented") public void testReadWriteFrom121(boolean oldSegmented, boolean newSegmented) throws Exception { setParameters(Version._12_1, oldSegmented, newSegmented); doTestReadWrite(); } @Override protected void beforeStartCache() throws Exception { InputStream is = FileLookupFactory.newInstance().lookupFile(files.get(oldVersion), Thread.currentThread().getContextClassLoader()); //copy data to the store file if (oldSegmented) { File segment1File = getSegmentFile(1); createParentDirectories(segment1File); Files.copy(is, segment1File.toPath(), StandardCopyOption.REPLACE_EXISTING); File segment2File = getSegmentFile(2); createParentDirectories(segment2File); Files.write(segment2File.toPath(), magic.get(oldVersion)); } else { File sfsFile = getStoreFile(tmpDirectory, cacheName()); createParentDirectories(sfsFile); Files.copy(is, sfsFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } } private void createParentDirectories(File file) { if (!file.getParentFile().exists()) { assertTrue(file.getParentFile().mkdirs()); } } private File getSegmentFile(int segment) { String segmentPath = AbstractSegmentedStoreConfiguration.fileLocationTransform(tmpDirectory, segment); return getStoreFile(segmentPath, cacheName()); } @Override protected String cacheName() { return "sfs-cache-store"; } @Override protected void configurePersistence(ConfigurationBuilder builder, boolean generatingData) { builder.persistence().addSingleFileStore() .segmented(oldSegmented) .location(tmpDirectory); } }
4,751
35
114
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/file/SingleFileStoreStressTest.java
package org.infinispan.persistence.file; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.infinispan.Cache; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; /** * Test concurrent reads, writes, and clear operations on the SingleFileStore. * * @author Dan Berindei */ @Test(groups = "unit", testName = "persistence.file.SingleFileStoreStressTest") public class SingleFileStoreStressTest extends SingleCacheManagerTest { private static final String CACHE_NAME = "testCache"; private static final String TIMES_STRING = "123456789_"; public static final int NUM_SEGMENTS = 256; public static final IntSet ALL_SEGMENTS = IntSets.immutableRangeSet(NUM_SEGMENTS); private String location; @Override protected void teardown() { super.teardown(); Util.recursiveFileRemove(this.location); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { location = CommonsTestingUtil.tmpDirectory(SingleFileStoreStressTest.class); GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); globalBuilder.globalState().enable().persistentLocation(location); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().hash().numSegments(NUM_SEGMENTS); builder.persistence().addSingleFileStore().purgeOnStartup(true).segmented(false); EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(globalBuilder, builder); cacheManager.defineConfiguration(CACHE_NAME, builder.build()); return cacheManager; } private File getFileStore() { return new File(location, CACHE_NAME + ".dat"); } public void testReadsAndWrites() throws ExecutionException, InterruptedException { final int writerThreads = 2; final int readerThreads = 2; Cache<String, String> cache = cacheManager.getCache(CACHE_NAME); SingleFileStore<String, String> store = TestingUtil.getFirstStore(cache); assertEquals(0, (long) join(store.size(IntSets.immutableSet(0)))); final List<String> keys = populateStore(5, 0, store, cache); final CountDownLatch stopLatch = new CountDownLatch(1); Future[] writeFutures = new Future[writerThreads]; for (int i = 0; i < writerThreads; i++) { writeFutures[i] = fork(stopOnException(new WriteTask(store, cache, keys, stopLatch), stopLatch)); } Future[] readFutures = new Future[readerThreads]; for (int i = 0; i < readerThreads; i++) { readFutures[i] = fork(stopOnException(new ReadTask(store, keys, false, stopLatch), stopLatch)); } stopLatch.await(2, SECONDS); stopLatch.countDown(); for (int i = 0; i < writerThreads; i++) { writeFutures[i].get(); } for (int i = 0; i < readerThreads; i++) { readFutures[i].get(); } } public void testWritesAndClear() throws ExecutionException, InterruptedException { final int writerThreads = 2; final int readerThreads = 2; final int numberOfKeys = 5; Cache<String, String> cache = cacheManager.getCache(CACHE_NAME); SingleFileStore<String, String> store = TestingUtil.getFirstStore(cache); assertEquals(0, (long) join(store.size(IntSets.immutableSet(0)))); final List<String> keys = new ArrayList<>(numberOfKeys); for (int j = 0; j < numberOfKeys; j++) { String key = "key" + j; keys.add(key); } final CountDownLatch stopLatch = new CountDownLatch(1); Future[] writeFutures = new Future[writerThreads]; for (int i = 0; i < writerThreads; i++) { writeFutures[i] = fork(stopOnException(new WriteTask(store, cache, keys, stopLatch), stopLatch)); } Future[] readFutures = new Future[readerThreads]; for (int i = 0; i < readerThreads; i++) { readFutures[i] = fork(stopOnException(new ReadTask(store, keys, true, stopLatch), stopLatch)); } Future clearFuture = fork(stopOnException(new ClearTask(store, stopLatch), stopLatch)); stopLatch.await(2, SECONDS); stopLatch.countDown(); for (int i = 0; i < writerThreads; i++) { writeFutures[i].get(); } for (int i = 0; i < readerThreads; i++) { readFutures[i].get(); } clearFuture.get(); } public void testSpaceOptimization() throws InterruptedException { final int numberOfKeys = 100; final int times = 10; Cache<String, String> cache = cacheManager.getCache(CACHE_NAME); SingleFileStore<String, String> store = TestingUtil.getFirstStore(cache); assertEquals(0, (long) join(store.size(IntSets.immutableSet(0)))); long [] fileSizesWithoutPurge = new long [times]; long [] fileSizesWithPurge = new long [times]; File file = new File(location, CACHE_NAME + ".dat"); // Write values for all keys iteratively such that the entry size increases during each iteration // Also record the file size after each such iteration. // Since entry sizes increase during each iteration, new entries won't fit in old free entries for (int i = 0; i < times; i++) { populateStore(numberOfKeys, i, store, cache); fileSizesWithoutPurge[i] = file.length(); } // Clear the store so that we can start fresh again store.clear(); // Repeat the same logic as above // Just that, in this case we will call purge after each iteration ExecutorService executor = Executors.newSingleThreadExecutor(getTestThreadFactory("Purge")); try { for (int i = 0; i < times; i++) { populateStore(numberOfKeys, i, store, cache); // Call purge so that the entries are coalesced // Since this will merge and make bigger free entries available, new entries should get some free slots (unlike earlier case) // This should prove that the file size increases slowly Flowable.fromPublisher(store.purgeExpired()).blockingSubscribe(); fileSizesWithPurge[i] = file.length(); } } finally { executor.shutdownNow(); } // Verify that file size increases slowly when the space optimization logic (implemented within store.purge()) is used for (int j = 2; j < times; j++) { assertTrue(fileSizesWithPurge[j] < fileSizesWithoutPurge[j]); } } public void testFileTruncation() throws ExecutionException, InterruptedException { final int writerThreads = 2; final int readerThreads = 2; final int numberOfKeys = 5; Cache<String, String> cache = cacheManager.getCache(CACHE_NAME); SingleFileStore<String, String> store = TestingUtil.getFirstStore(cache); assertEquals(0, (long) join(store.size(IntSets.immutableSet(0)))); // Write a few entries into the cache final List<String> keys = populateStore(5, 0, store, cache); // Do some reading/writing entries with random size final CountDownLatch stopLatch = new CountDownLatch(1); Future[] writeFutures = new Future[writerThreads]; for (int i = 0; i < writerThreads; i++) { writeFutures[i] = fork(stopOnException(new WriteTask(store, cache, keys, stopLatch), stopLatch)); } Future[] readFutures = new Future[readerThreads]; for (int i = 0; i < readerThreads; i++) { readFutures[i] = fork(stopOnException(new ReadTask(store, keys, false, stopLatch), stopLatch)); } stopLatch.await(2, SECONDS); stopLatch.countDown(); for (int i = 0; i < writerThreads; i++) { writeFutures[i].get(); } for (int i = 0; i < readerThreads; i++) { readFutures[i].get(); } File file = getFileStore(); long length1 = file.length(); Flowable.fromPublisher(store.purgeExpired()).blockingSubscribe(); long length2 = file.length(); assertTrue(String.format("Length1=%d, Length2=%d", length1, length2), length2 <= length1); // Write entry with size larger than any previous to ensure that it is placed at the end of the file String key = "key" + numberOfKeys; byte[] bytes = new byte[(int) store.getFileSize()]; Arrays.fill(bytes, (byte) 'a'); join(store.write(0, MarshalledEntryUtil.create(key, new String(bytes), cache))); length1 = file.length(); // Delete entry in order to guarantee that there will be space available at the end of the file to truncate join(store.delete(0, key)); Flowable.fromPublisher(store.purgeExpired()).blockingSubscribe(); length2 = file.length(); assertTrue(String.format("Length1=%d, Length2=%d", length1, length2), length2 < length1); } public List<String> populateStore(int numKeys, int numPadding, SingleFileStore<String, String> store, Cache<String, String> cache) { final List<String> keys = new ArrayList<>(numKeys); for (int j = 0; j < numKeys; j++) { String key = "key" + j; String value = key + "_value_" + j + times(numPadding); keys.add(key); join(store.write(0, MarshalledEntryUtil.create(key, value, cache))); } return keys; } public void testProcess() throws ExecutionException, InterruptedException { final int writerThreads = 2; final int numberOfKeys = 2000; Cache<String, String> cache = cacheManager.getCache(CACHE_NAME); SingleFileStore<String, String> store = TestingUtil.getFirstStore(cache); assertEquals(0, (long) join(store.size(IntSets.immutableSet(0)))); final List<String> keys = new ArrayList<>(numberOfKeys); populateStoreRandomValues(numberOfKeys, store, cache, keys); final CountDownLatch stopLatch = new CountDownLatch(1); Future[] writeFutures = new Future[writerThreads]; for (int i = 0; i < writerThreads; i++) { writeFutures[i] = fork(stopOnException(new WriteTask(store, cache, keys, stopLatch), stopLatch)); } Future processFuture = fork(stopOnException(new ProcessTask(store), stopLatch)); // Stop the writers only after we finish processing processFuture.get(); stopLatch.countDown(); for (int i = 0; i < writerThreads; i++) { writeFutures[i].get(); } } public void testProcessWithNoDiskAccess() throws ExecutionException, InterruptedException { final int writerThreads = 2; final int numberOfKeys = 2000; Cache<String, String> cache = cacheManager.getCache(CACHE_NAME); SingleFileStore<String, String> store = TestingUtil.getFirstStore(cache); assertEquals(0, (long) CompletionStages.join(store.size(IntSets.immutableSet(0)))); final List<String> keys = new ArrayList<>(numberOfKeys); populateStoreRandomValues(numberOfKeys, store, cache, keys); final CountDownLatch stopLatch = new CountDownLatch(1); Future[] writeFutures = new Future[writerThreads]; for (int i = 0; i < writerThreads; i++) { writeFutures[i] = fork(stopOnException(new WriteTask(store, cache, keys, stopLatch), stopLatch)); } Future processFuture = fork(stopOnException(new ProcessTaskNoDiskRead(store), stopLatch)); // Stop the writers only after we finish processing processFuture.get(); stopLatch.countDown(); for (int i = 0; i < writerThreads; i++) { writeFutures[i].get(); } } private void populateStoreRandomValues(int numberOfKeys, SingleFileStore<String, String> store, Cache<String, String> cache, List<String> keys) { for (int j = 0; j < numberOfKeys; j++) { String key = "key" + j; String value = key + "_value_" + j + times(new Random().nextInt(10)); keys.add(key); join(store.write(0, MarshalledEntryUtil.create(key, value, cache))); } } private Callable<Object> stopOnException(Callable<Object> task, CountDownLatch stopLatch) { return new StopOnExceptionTask(task, stopLatch); } private String times(int count) { if (count == 0) return ""; StringBuilder sb = new StringBuilder(TIMES_STRING.length() * count); for (int i = 0; i < count; i++) { sb.append(TIMES_STRING); } return sb.toString(); } private class WriteTask implements Callable<Object> { SingleFileStore<String, String> store; final Cache cache; final List<String> keys; final CountDownLatch stopLatch; WriteTask(SingleFileStore store, Cache cache, List<String> keys, CountDownLatch stopLatch) { this.store = store; this.cache = cache; this.keys = keys; this.stopLatch = stopLatch; } @Override public Object call() throws Exception { TestResourceTracker.testThreadStarted(SingleFileStoreStressTest.this.getTestName()); Random random = new Random(); int i = 0; while (stopLatch.getCount() != 0) { String key = keys.get(random.nextInt(keys.size())); String value = key + "_value_" + i + "_" + times(random.nextInt(1000) / 10); MarshallableEntry<String, String> entry = MarshalledEntryUtil.create(key, value, cache); join(store.write(0, entry)); i++; } return null; } } private static class ReadTask implements Callable<Object> { final boolean allowNulls; final CountDownLatch stopLatch; final List<String> keys; SingleFileStore<String, String> store; ReadTask(SingleFileStore<String, String> store, List<String> keys, boolean allowNulls, CountDownLatch stopLatch) { this.allowNulls = allowNulls; this.stopLatch = stopLatch; this.keys = keys; this.store = store; } @Override public Random call() throws Exception { Random random = new Random(); while (stopLatch.getCount() != 0) { String key = keys.get(random.nextInt(keys.size())); MarshallableEntry<String, String> entryFromStore = join(store.load(0, key)); if (entryFromStore == null) { assertTrue(allowNulls); } else { String storeValue = (String) entryFromStore.getValue(); assertEquals(key, entryFromStore.getKey()); assertTrue(storeValue.startsWith(key)); } } return null; } } private class ClearTask implements Callable<Object> { final CountDownLatch stopLatch; SingleFileStore<String, String> store; ClearTask(SingleFileStore store, CountDownLatch stopLatch) { this.stopLatch = stopLatch; this.store = store; } @Override public Object call() throws Exception { File file = getFileStore(); assertTrue(file.exists()); MILLISECONDS.sleep(100); while (stopLatch.getCount() != 0) { log.tracef("Clearing store, store size before = %d, file size before = %d", store.getFileSize(), file.length()); store.clear(); MILLISECONDS.sleep(1); // The store size is incremented before values are actually written, so the on-disk size should always be // smaller than the logical size. long fileSizeAfterClear = file.length(); long storeSizeAfterClear = store.getFileSize(); log.tracef("Cleared store, store size after = %d, file size after = %d", storeSizeAfterClear, fileSizeAfterClear); assertTrue("Store size " + storeSizeAfterClear + " is smaller than the file size " + fileSizeAfterClear, fileSizeAfterClear <= storeSizeAfterClear); MILLISECONDS.sleep(100); } return null; } } private class ProcessTask implements Callable<Object> { SingleFileStore<String, String> store; ProcessTask(SingleFileStore<String, String> store) { this.store = store; } @Override public Object call() throws Exception { File file = getFileStore(); assertTrue(file.exists()); Long sum = Flowable.fromPublisher(store.publishEntries(ALL_SEGMENTS, null, true)) .doOnNext(me -> { String key = me.getKey(); String value = me.getValue(); assertEquals(key, (value.substring(0, key.length()))); }).count().blockingGet(); log.tracef("Processed %d entries from the store", sum); return null; } } private class ProcessTaskNoDiskRead implements Callable<Object> { final SingleFileStore<?, ?> store; ProcessTaskNoDiskRead(SingleFileStore<?, ?> store) { this.store = store; } @Override public Object call() throws Exception { File file = getFileStore(); assertTrue(file.exists()); Long sum = Flowable.fromPublisher(store.publishEntries(ALL_SEGMENTS, null, false)) .doOnNext(me -> { Object key = me.getKey(); assertNotNull(key); }).count().blockingGet(); log.tracef("Processed %d in-memory keys from the store", sum); return null; } } private class StopOnExceptionTask implements Callable<Object> { final CountDownLatch stopLatch; final Callable<Object> delegate; StopOnExceptionTask(Callable<Object> delegate, CountDownLatch stopLatch) { this.stopLatch = stopLatch; this.delegate = delegate; } @Override public Object call() throws Exception { try { return delegate.call(); } catch (Throwable t) { stopLatch.countDown(); throw new Exception(t); } } } }
19,304
37.843058
148
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/file/SingleFileGracefulShutdownMigrationTest.java
package org.infinispan.persistence.file; import static org.testng.AssertJUnit.assertEquals; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import org.infinispan.Cache; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.ByRef; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.commons.util.Util; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * SFS content created on multiple branches using the below code: * <pre> * public static void main(String[] args) throws Exception { * // TODO update to required destination folder * Path sfsPath = Paths.get(); * String cacheName = "update-cache"; * ConfigurationBuilderHolder cbh = new ConfigurationBuilderHolder(); * // TODO Uncomment for `all-entries-java-serialization.dat` * // cbh.getGlobalConfigurationBuilder().serialization().marshaller(new JavaSerializationMarshaller()); * cbh.newConfigurationBuilder(cacheName) * .persistence() * .addSingleFileStore() * .purgeOnStartup(true) * .segmented(false) * .location(sfsPath.toString()); * * // Generate 11.x .dat file * // Then use this to ensure that migration works with the various scenarios * // Save 12.1.x .dat file after broken migration and use this for tests * // Fix broken migration code * try (EmbeddedCacheManager cacheManager = new DefaultCacheManager(cbh, true)) { * Cache<Object, Object> cache = cacheManager.getCache(cacheName); * SingleFileStore<Object, Object> store = TestingUtil.getWriter(cache, 0); * MarshallableEntryFactory<Object, Object> mef = TestingUtil.extractComponent(cache, MarshallableEntryFactory.class); * * // Primitive values * IntStream.range(0, 1000).forEach(i -> cache.put(i, i)); * * // Values with expiration. Need to verify that this is still loaded and timestamp restarted. * IntStream.range(1000, 2000).forEach(i -> cache.put(i, i, 1, TimeUnit.MINUTES)); * * // WrappedByteArrays * WrappedByteArray wba = new WrappedByteArray("wrapped-bytes".getBytes(StandardCharsets.UTF_8)); * cache.put(wba, wba); * * // Async Xsite PrivateMetadata entry * DefaultIracVersionGenerator iracVersionGenerator = new DefaultIracVersionGenerator(""); * TestingUtil.replaceField("site-name", "localSite", iracVersionGenerator, DefaultIracVersionGenerator.class); * PrivateMetadata privateMetadata = new PrivateMetadata.Builder() * .iracMetadata(iracVersionGenerator.generateNewMetadata(2)) * .build(); * MarshallableEntry<Object, Object> me = mef.create("irac-key", "irac-value", null, privateMetadata, -1, -1); * store.write(me); * * // Optimistic Tx PrivateMetadata entry * privateMetadata = new PrivateMetadata.Builder() * .entryVersion(new NumericVersionGenerator().generateNew()) * .build(); * me = mef.create("opt-tx-key", "opt-tx-value", null, privateMetadata, -1, -1); * store.write(me); * } * } * </pre> * <p> * Files stored in `sfs/corrupt` contain already corrupted .dat files that were originally created in 11.x and were * migrated to 12.1.x with the broken SFS migration code. Hence, when these .dat files are loaded the SFS attempts to * recover the corrupt data. * * @author Ryan Emerson * @since 13.0 */ @Test(groups = "unit", testName = "persistence.file.SingleFileGracefulShutdownMigrationTest") public class SingleFileGracefulShutdownMigrationTest extends AbstractInfinispanTest { private static final String CACHE_NAME = "update-cache"; private String tmpDirectory; @BeforeClass protected void setUpTempDir() throws IOException { tmpDirectory = CommonsTestingUtil.tmpDirectory(this.getClass()); new File(tmpDirectory).mkdirs(); } @AfterClass protected void clearTempDir() { Util.recursiveFileRemove(tmpDirectory); } enum Marshaller { PROTOSTREAM, JAVA_SERIALIZATION } @DataProvider(name = "testFiles") Object[][] singleTypes() { return new Object[][]{ // Not possible to test corrupt Marshaller.JAVA_SERIALIZATION bytes as previously 11.x -> 12. migration always fails with non-protostream marshallers // MAGIC_11_0 {"sfs/11_0/all-entries-java-serialization.dat", Marshaller.JAVA_SERIALIZATION}, // MAGIC_12_0 created on 12.1.x {"sfs/12_0/all-entries-java-serialization.dat", Marshaller.JAVA_SERIALIZATION}, // 11.x -> 12.1.x migration resulting in corrupt data {"sfs/corrupt/all-entries.dat", Marshaller.PROTOSTREAM}, // MAGIC_12_0 created on 12.1.x {"sfs/12_0/all-entries.dat", Marshaller.PROTOSTREAM}, }; } @Test(dataProvider = "testFiles") public void testAllEntriesRecovered(String fileName, Marshaller marshallerType) throws Exception { int numEntries = 1003; InputStream is = FileLookupFactory.newInstance().lookupFile(fileName, Thread.currentThread().getContextClassLoader()); Files.copy(is, Paths.get(tmpDirectory).resolve(CACHE_NAME + ".dat"), StandardCopyOption.REPLACE_EXISTING); ConfigurationBuilderHolder cbh = new ConfigurationBuilderHolder(); if (marshallerType == Marshaller.JAVA_SERIALIZATION) cbh.getGlobalConfigurationBuilder().serialization().marshaller(new JavaSerializationMarshaller()); cbh.newConfigurationBuilder(CACHE_NAME) .persistence() .addSingleFileStore() .segmented(false) .location(tmpDirectory); try (EmbeddedCacheManager cacheManager = new DefaultCacheManager(cbh, true)) { Cache<Object, Object> cache = cacheManager.getCache(CACHE_NAME); ByRef.Integer i = new ByRef.Integer(0); // Iterate all entries to ensure values can be read cache.forEach((k, v) -> i.inc()); assertEquals(numEntries, i.get()); // Write to a migrated key cache.put(0, "RuntimeValue"); // Create a new key cache.put("NewKey", "NewValue"); } // Start it up a second time to make sure the migrated data is properly read still try (EmbeddedCacheManager cacheManager = new DefaultCacheManager(cbh, true)) { Cache<Object, Object> cache = cacheManager.getCache(CACHE_NAME); ByRef.Integer i = new ByRef.Integer(0); // Iterate all entries to ensure values can be read cache.forEach((k, v) -> i.inc()); assertEquals(numEntries + 1, i.get()); // Ensure that the entry updated after migration can be read assertEquals("RuntimeValue", cache.get(0)); // Ensure that the entry created after migration can be read assertEquals("NewValue", cache.get("NewKey")); } } }
7,553
42.66474
161
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/file/SingleFileMigrateCorruptTest.java
package org.infinispan.persistence.file; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.commons.util.Util; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.container.entries.CacheEntry; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test that replicates 11.x -> 12.1.x corrupt migration. * <p> * To reproduce `sfs/corrupt/migrate_corrupt_test.dat` execute {@link SFSCreator11_0} on the 11.x branch and then * execute {@link SFSCorruptedMigration12_1} with 12.1.4.Final or below. * * @author Ryan Emerson * @since 13.0 */ @Test(groups = "unit", testName = "persistence.file.SingleFileMigrateCorruptTest") public class SingleFileMigrateCorruptTest extends AbstractInfinispanTest { static final String CACHE_NAME = "update-cache"; private String tmpDirectory; @BeforeClass protected void setUpTempDir() throws IOException { tmpDirectory = CommonsTestingUtil.tmpDirectory(this.getClass()); new File(tmpDirectory).mkdirs(); } @AfterClass protected void clearTempDir() { Util.recursiveFileRemove(tmpDirectory); } public void testAllEntriesRecovered() throws Exception { InputStream is = FileLookupFactory.newInstance().lookupFile("sfs/corrupt/migrate_corrupt_test.dat", Thread.currentThread().getContextClassLoader()); Files.copy(is, Paths.get(tmpDirectory).resolve(CACHE_NAME + ".dat"), StandardCopyOption.REPLACE_EXISTING); ConfigurationBuilderHolder cbh = new ConfigurationBuilderHolder(); cbh.newConfigurationBuilder(CACHE_NAME) .persistence() .addSingleFileStore() .segmented(false) .location(tmpDirectory); try (EmbeddedCacheManager cacheManager = new DefaultCacheManager(cbh, true)) { Cache<Object, Object> cache = cacheManager.getCache(CACHE_NAME); // Ensure all expected values are readable assertContent(cache.getAdvancedCache(), false); // Write to a migrated key cache.put(0, "RuntimeValue"); // Create a new key cache.put("NewKey", "NewValue"); } // Start it up a second time to make sure the migrated data is properly read still try (EmbeddedCacheManager cacheManager = new DefaultCacheManager(cbh, true)) { Cache<Object, Object> cache = cacheManager.getCache(CACHE_NAME); // Ensure all expected values are readable assertContent(cache.getAdvancedCache(), true); // Ensure that the entry updated after migration can be read assertEquals("RuntimeValue", cache.get(0)); // Ensure that the entry created after migration can be read assertEquals("NewValue", cache.get("NewKey")); } } private void assertContent(AdvancedCache<Object, Object> cache, boolean skip0) { IntStream.range(skip0 ? 1 : 0, 1000).forEach(i -> { if (i % 4 == 0) { // Ensure that we have the expected values from SFSCorruptedMigration12_1 assertEquals(i + "-updated-12.1", cache.get(i)); } else { // Ensure that we have the expected values from SFSCreator11_0 assertEquals(i, cache.get(i)); } }); IntStream.range(1000, 2000).forEach(i -> { CacheEntry<Object, Object> entry = cache.getCacheEntry(i); if (i % 8 == 0) { assertNotNull("No entry found for key: " + i, entry); // Ensure that we have the expected values from SFSCorruptedMigration12_1 assertEquals(i + "-updated-12.1", entry.getValue()); // We overrode the expiration lifespan assertEquals(-1, entry.getLifespan()); } else if (i % 4 == 0) { // These should have expired since they were inserted after the corruption occurred assertNull("Entry was supposed to be expired for key: " + i, entry); } else { assertNotNull("No entry found for key: " + i, entry); // Ensure that we have the expected values from SFSCreator11_0 assertEquals(i, entry.getValue()); assertEquals(longTimeMilliseconds(), entry.getLifespan()); } }); IntStream.range(2000, 3000).forEach(i -> { if (i % 4 == 0) { assertEquals(i + "-12.1-with-expiration", cache.get(i)); } else if (i % 2 == 0) { assertNull(cache.get(i)); } else { assertEquals(i + "-12.1", cache.get(i)); } }); } static long longTimeMilliseconds() { return TimeUnit.DAYS.toMillis(365 * 50); } } /** * Used to generate initial .dat file on 11.x branch * <p> * Migrate and manipulate .dat file created by {@link SFSCreator11_0}. Results in a corrupted .dat file */ //final class SFSCreator11_0 { // static final String CACHE_NAME = "update-cache"; // public static void main(String[] args) throws Exception { // Path sfsPath = Paths.get("/tmp/sfs"); // ConfigurationBuilderHolder cbh = new ConfigurationBuilderHolder(); // cbh.newConfigurationBuilder(CACHE_NAME) // .persistence() // .addSingleFileStore() // .purgeOnStartup(true) // .segmented(false) // .location(sfsPath.toString()); // // // Total number of entries 2003 // try (EmbeddedCacheManager cacheManager = new DefaultCacheManager(cbh, true)) { // Cache<Object, Object> cache = cacheManager.getCache(CACHE_NAME); // SingleFileStore<Object, Object> store = TestingUtil.getWriter(cache, 0); // MarshallableEntryFactory<Object, Object> mef = TestingUtil.extractComponent(cache, MarshallableEntryFactory.class); // // // Primitive values // IntStream.range(0, 1000).forEach(i -> cache.put(i, i)); // // // Values with expiration. // IntStream.range(1000, 2000).forEach(i -> cache.put(i, i, SingleFileMigrateCorruptTest.longTimeMilliseconds(), TimeUnit.MILLISECONDS)); // // // WrappedByteArrays // WrappedByteArray wba = new WrappedByteArray("wrapped-bytes".getBytes(StandardCharsets.UTF_8)); // cache.put(wba, wba); // // // Async Xsite PrivateMetadata entry // DefaultIracVersionGenerator iracVersionGenerator = new DefaultIracVersionGenerator(); // TestingUtil.replaceField("site-name", "localSite", iracVersionGenerator, DefaultIracVersionGenerator.class); // PrivateMetadata privateMetadata = new PrivateMetadata.Builder() // .iracMetadata(iracVersionGenerator.generateNewMetadata(2)) // .build(); // MarshallableEntry<Object, Object> me = mef.create("irac-key", "irac-value", null, privateMetadata, -1, -1); // store.write(me); // // // Optimistic Tx PrivateMetadata entry // privateMetadata = new PrivateMetadata.Builder() // .entryVersion(new NumericVersionGenerator().generateNew()) // .build(); // me = mef.create("opt-tx-key", "opt-tx-value", null, privateMetadata, -1, -1); // store.write(me); // } // } //} /** * Migrate and manipulate .dat file created by {@link SFSCreator11_0}. Results in a corrupted .dat file */ //final class SFSCorruptedMigration12_1 { // static final String CACHE_NAME = "update-cache"; // public static void main(String[] args) throws Exception { // Path sfsPath = Paths.get("/tmp/sfs"); // ConfigurationBuilderHolder cbh = new ConfigurationBuilderHolder(); // cbh.newConfigurationBuilder(CACHE_NAME) // .persistence() // .addSingleFileStore() // .segmented(false) // .location(sfsPath.toString()); // // // Total number of entries 3003 // try (EmbeddedCacheManager cacheManager = new DefaultCacheManager(cbh, true)) { // Cache<Object, Object> cache = cacheManager.getCache(CACHE_NAME); // // // Primitive values // IntStream.range(0, 1000).forEach(i -> { // // Overwrite a subset of values // if (i % 4 == 0) // cache.put(i, i + "-updated-12.1"); // }); // // // Values with expiration. Need to verify that this is still loaded and timestamp restarted. // IntStream.range(1000, 2000).forEach(i -> { // // Overwrite a subset of values // if (i % 8 == 0) { // cache.put(i, i + "-updated-12.1"); // } else if (i % 4 == 0) { // cache.put(i, i + "-updated-12.1", 1, TimeUnit.SECONDS); // } // }); // // IntStream.range(2000, 3000).forEach(i -> { // if (i % 4 == 0) { // cache.put(i, i + "-12.1-with-expiration", SingleFileMigrateCorruptTest.longTimeMilliseconds(), TimeUnit.MILLISECONDS); // } else if (i % 2 == 0) { // cache.put(i, i + "-12.1-with-expiration", 1, TimeUnit.SECONDS); // } else { // cache.put(i, i + "-12.1"); // } // }); // // Don't update PrivateMetadata entries as that will result in runtime exception // } // } //}
9,875
39.641975
154
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/file/SingleFileStoreFunctionalTest.java
package org.infinispan.persistence.file; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.util.List; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; import org.infinispan.configuration.cache.SingleFileStoreConfiguration; import org.infinispan.configuration.cache.StoreConfiguration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.persistence.BaseStoreFunctionalTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Single file cache store functional test. * * @author Galder Zamarreño * @since 6.0 */ @Test(groups = {"unit", "smoke"}, testName = "persistence.file.SingleFileStoreFunctionalTest") public class SingleFileStoreFunctionalTest extends BaseStoreFunctionalTest { private String tmpDirectory; @BeforeClass protected void setUpTempDir() { tmpDirectory = CommonsTestingUtil.tmpDirectory(this.getClass()); Util.recursiveFileRemove(tmpDirectory); } @AfterClass protected void clearTempDir() { Util.recursiveFileRemove(tmpDirectory); new File(tmpDirectory).mkdirs(); } @Override protected PersistenceConfigurationBuilder createCacheStoreConfig(PersistenceConfigurationBuilder persistence, String cacheName, boolean preload) { persistence .addSingleFileStore() .location(tmpDirectory) .preload(preload); return persistence; } public void testParsingEmptyElement() throws Exception { String config = TestingUtil.wrapXMLWithSchema( "<cache-container default-cache=\"default\">" + " <local-cache name=\"default\">\n" + " <persistence passivation=\"false\"> \n" + " <single-file-store shared=\"false\" preload=\"true\"/> \n" + " </persistence>\n" + " </local-cache>\n" + "</cache-container>"); ConfigurationBuilderHolder holder = new ParserRegistry().parse(config); List<StoreConfiguration> storeConfigs = holder.getDefaultConfigurationBuilder().build().persistence().stores(); assertEquals(1, storeConfigs.size()); SingleFileStoreConfiguration fileStoreConfig = (SingleFileStoreConfiguration) storeConfigs.get(0); assertNull(fileStoreConfig.location()); assertEquals(-1, fileStoreConfig.maxEntries()); } public void testParsingElement() throws Exception { String config = TestingUtil.wrapXMLWithoutSchema( "<cache-container default-cache=\"default\">" + " <local-cache name=\"default\">\n" + " <persistence passivation=\"false\"> \n" + " <single-file-store path=\"other-location\" segmented=\"false\" max-entries=\"100\" shared=\"false\" preload=\"true\" fragmentation-factor=\"0.75\"/> \n" + " </persistence>\n" + " </local-cache>\n" + "</cache-container>"); InputStream is = new ByteArrayInputStream(config.getBytes()); ConfigurationBuilderHolder holder = new ParserRegistry().parse(config); List<StoreConfiguration> storeConfigs = holder.getDefaultConfigurationBuilder().build().persistence().stores(); assertEquals(1, storeConfigs.size()); SingleFileStoreConfiguration fileStoreConfig = (SingleFileStoreConfiguration) storeConfigs.get(0); assertEquals("other-location", fileStoreConfig.location()); assertEquals(100, fileStoreConfig.maxEntries()); assertEquals(0.75f, fileStoreConfig.fragmentationFactor(), 0f); Util.recursiveFileRemove("other-location"); } }
4,015
41.273684
176
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/file/BoundedSingleFileStoreTest.java
package org.infinispan.persistence.file; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.SingleFileStoreConfigurationBuilder; import org.infinispan.marshall.TestObjectStreamMarshaller; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.PersistenceMockUtil; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Tests for single-file cache store when configured to be bounded. * * @author Galder Zamarreño * @since 6.0 */ @Test(groups = "unit", testName = "persistence.file.BoundedSingleFileStoreTest") public class BoundedSingleFileStoreTest extends AbstractInfinispanTest { SingleFileStore<Object, Object> store; String tmpDirectory; private TestObjectStreamMarshaller marshaller; @BeforeClass protected void setUpTempDir() { tmpDirectory = CommonsTestingUtil.tmpDirectory(this.getClass()); } @AfterClass protected void clearTempDir() { Util.recursiveFileRemove(tmpDirectory); } @BeforeMethod public void setUp() throws Exception { clearTempDir(); store = new SingleFileStore<>(); ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); builder .persistence() .addStore(SingleFileStoreConfigurationBuilder.class) .location(this.tmpDirectory) .segmented(false) .maxEntries(1); marshaller = new TestObjectStreamMarshaller(); CompletionStages.join(store.start(PersistenceMockUtil.createContext(getClass(), builder.build(), marshaller))); } @AfterMethod public void tearDown() throws PersistenceException { try { if (store != null) { store.clear(); store.stop(); } marshaller.stop(); } finally { store = null; } } public void testStoreSizeExceeded() { assertStoreSize(0, 0); TestObjectStreamMarshaller sm = new TestObjectStreamMarshaller(); try { store.write(0, MarshalledEntryUtil.create(1, "v1", sm)); store.write(0, MarshalledEntryUtil.create(1, "v2", sm)); assertStoreSize(1, 1); } finally { sm.stop(); } } private void assertStoreSize(int expectedEntries, int expectedFree) { assertEquals("Entries: " + store.getEntries(), expectedEntries, store.getEntries().size()); assertEquals("Free: " + store.getFreeList(), expectedFree, store.getFreeList().size()); } }
3,090
32.597826
117
java
null
infinispan-main/core/src/test/java/org/infinispan/persistence/file/SingleFileGracefulShutdownMigrationXsiteTest.java
package org.infinispan.persistence.file; import static org.testng.AssertJUnit.assertEquals; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Objects; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.xsite.statetransfer.AbstractStateTransferTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * A test to ensure that the PrivateMetadata instances created as part of the 12_0 -> 12_1 SFS migrateCorruptDataV12_0 * allow recovered entries to be read/write xsite after startup. * * @author Ryan Emerson * @since 13.0 */ @Test(groups = "unit", testName = "persistence.file.SingleFileGracefulShutdownMigrationXsiteTest") public class SingleFileGracefulShutdownMigrationXsiteTest extends AbstractStateTransferTest { private String tmpDirectory; private String lonDirectory; private String nycDirectory; public SingleFileGracefulShutdownMigrationXsiteTest() { this.initialClusterSize = 1; this.nycBackupStrategy = BackupConfiguration.BackupStrategy.ASYNC; this.lonBackupStrategy = BackupConfiguration.BackupStrategy.ASYNC; this.implicitBackupCache = true; } @BeforeClass(alwaysRun = true) @Override public void createBeforeClass() { tmpDirectory = CommonsTestingUtil.tmpDirectory(this.getClass()); new File(tmpDirectory).mkdirs(); File f = new File(tmpDirectory, LON); lonDirectory = f.getPath(); f.mkdirs(); f = new File(tmpDirectory, NYC); nycDirectory = f.getPath(); f.mkdirs(); try (InputStream nyc = FileLookupFactory.newInstance().lookupFile("sfs/corrupt/xsite/nyc.dat", Thread.currentThread().getContextClassLoader()); InputStream lon = FileLookupFactory.newInstance().lookupFile("sfs/corrupt/xsite/lon.dat", Thread.currentThread().getContextClassLoader())) { Files.copy(lon, Paths.get(lonDirectory).resolve(TestCacheManagerFactory.DEFAULT_CACHE_NAME + ".dat"), StandardCopyOption.REPLACE_EXISTING); Files.copy(nyc, Paths.get(nycDirectory).resolve(TestCacheManagerFactory.DEFAULT_CACHE_NAME + ".dat"), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new RuntimeException(e); } super.createBeforeClass(); } @AfterClass(alwaysRun = true) @Override protected void clearContent() { super.destroy(); Util.recursiveFileRemove(tmpDirectory); } private ConfigurationBuilder cfg(String location) { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.persistence() .addSingleFileStore() .segmented(false) .location(location) .fetchPersistentState(true); return builder; } @Override protected ConfigurationBuilder getNycActiveConfig() { return cfg(nycDirectory); } @Override protected ConfigurationBuilder getLonActiveConfig() { return cfg(lonDirectory); } @Test public void testAllEntriesRecovered() { Cache<Object, Object> lonCache = cache(LON, 0); Cache<Object, Object> nycCache = cache(NYC, 0); startStateTransfer(lonCache, NYC); startStateTransfer(nycCache, LON); assertEventuallyStateTransferNotRunning(); assertEventuallyStateTransferNotRunning(cache(NYC, 0)); assertInSite(LON, cache -> assertEquals("sfs-value-lon", cache.get(LON))); assertInSite(LON, cache -> assertEquals("sfs-value-nyc", cache.get(NYC))); assertInSite(NYC, cache -> assertEquals("sfs-value-lon", cache.get(LON))); assertInSite(NYC, cache -> assertEquals("sfs-value-nyc", cache.get(NYC))); // Update entries lonCache.put(LON, "Updated"); assertEventuallyInSite(LON, cache -> Objects.equals("Updated", cache.get(LON)), 30, TimeUnit.SECONDS); assertEventuallyInSite(NYC, cache -> Objects.equals("Updated", cache.get(LON)), 30, TimeUnit.SECONDS); nycCache.put(NYC, "Updated"); assertEventuallyInSite(LON, cache -> Objects.equals("Updated", cache.get(NYC)), 30, TimeUnit.SECONDS); assertEventuallyInSite(NYC, cache -> Objects.equals("Updated", cache.get(NYC)), 30, TimeUnit.SECONDS); } }
4,789
37.629032
151
java