Search in sources :

Example 1 with PutFromLoadValidator

use of org.hibernate.cache.infinispan.access.PutFromLoadValidator in project hibernate-orm by hibernate.

the class CorrectnessTestCase method getPutFromLoadValidator.

private PutFromLoadValidator getPutFromLoadValidator(SessionFactoryImplementor sfi, String regionName) throws NoSuchFieldException, IllegalAccessException {
    RegionAccessStrategy strategy = sfi.getSecondLevelCacheRegionAccessStrategy(regionName);
    if (strategy == null) {
        return null;
    }
    Field delegateField = getField(strategy.getClass(), "delegate");
    Object delegate = delegateField.get(strategy);
    if (delegate == null) {
        return null;
    }
    if (InvalidationCacheAccessDelegate.class.isInstance(delegate)) {
        Field validatorField = InvalidationCacheAccessDelegate.class.getDeclaredField("putValidator");
        validatorField.setAccessible(true);
        return (PutFromLoadValidator) validatorField.get(delegate);
    } else {
        return null;
    }
}
Also used : Field(java.lang.reflect.Field) PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator) RegionAccessStrategy(org.hibernate.cache.spi.access.RegionAccessStrategy)

Example 2 with PutFromLoadValidator

use of org.hibernate.cache.infinispan.access.PutFromLoadValidator in project hibernate-orm by hibernate.

the class CorrectnessTestCase method checkForEmptyPendingPuts.

protected void checkForEmptyPendingPuts() throws Exception {
    Field pp = PutFromLoadValidator.class.getDeclaredField("pendingPuts");
    pp.setAccessible(true);
    Method getInvalidators = null;
    List<DelayedInvalidators> delayed = new LinkedList<>();
    for (int i = 0; i < sessionFactories.length; i++) {
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactories[i];
        for (Object regionName : sfi.getCache().getSecondLevelCacheRegionNames()) {
            PutFromLoadValidator validator = getPutFromLoadValidator(sfi, (String) regionName);
            if (validator == null) {
                log.warn("No validator for " + regionName);
                continue;
            }
            ConcurrentMap<Object, Object> map = (ConcurrentMap) pp.get(validator);
            for (Iterator<Map.Entry<Object, Object>> iterator = map.entrySet().iterator(); iterator.hasNext(); ) {
                Map.Entry entry = iterator.next();
                if (getInvalidators == null) {
                    getInvalidators = entry.getValue().getClass().getMethod("getInvalidators");
                    getInvalidators.setAccessible(true);
                }
                java.util.Collection invalidators = (java.util.Collection) getInvalidators.invoke(entry.getValue());
                if (invalidators != null && !invalidators.isEmpty()) {
                    delayed.add(new DelayedInvalidators(map, entry.getKey()));
                }
            }
        }
    }
    // poll until all invalidations come
    long deadline = System.currentTimeMillis() + 30000;
    while (System.currentTimeMillis() < deadline) {
        iterateInvalidators(delayed, getInvalidators, (k, i) -> {
        });
        if (delayed.isEmpty()) {
            break;
        }
        Thread.sleep(1000);
    }
    if (!delayed.isEmpty()) {
        iterateInvalidators(delayed, getInvalidators, (k, i) -> log.warnf("Left invalidators on key %s: %s", k, i));
        throw new IllegalStateException("Invalidators were not cleared: " + delayed.size());
    }
}
Also used : PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) ConcurrentMap(java.util.concurrent.ConcurrentMap) Method(java.lang.reflect.Method) LinkedList(java.util.LinkedList) Field(java.lang.reflect.Field) Collection(org.hibernate.mapping.Collection) Map(java.util.Map) TreeMap(java.util.TreeMap) NavigableMap(java.util.NavigableMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap)

Example 3 with PutFromLoadValidator

use of org.hibernate.cache.infinispan.access.PutFromLoadValidator in project hibernate-orm by hibernate.

the class BaseTransactionalDataRegion method prepareForValidation.

protected void prepareForValidation() {
    if (strategy != null) {
        assert strategy == Strategy.VALIDATION;
        return;
    }
    validator = new PutFromLoadValidator(cache, factory);
    strategy = Strategy.VALIDATION;
}
Also used : PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator)

Example 4 with PutFromLoadValidator

use of org.hibernate.cache.infinispan.access.PutFromLoadValidator in project hibernate-orm by hibernate.

the class AbstractRegionAccessStrategyTest method evictOrRemoveAllTest.

protected void evictOrRemoveAllTest(final boolean evict) throws Exception {
    final Object KEY = generateNextKey();
    assertEquals(0, localRegion.getCache().size());
    assertEquals(0, remoteRegion.getCache().size());
    SharedSessionContractImplementor s1 = mockedSession();
    assertNull("local is clean", localAccessStrategy.get(s1, KEY, s1.getTimestamp()));
    SharedSessionContractImplementor s2 = mockedSession();
    assertNull("remote is clean", remoteAccessStrategy.get(s2, KEY, s2.getTimestamp()));
    CountDownLatch localPutFromLoadLatch = expectRemotePutFromLoad(remoteRegion.getCache(), localRegion.getCache());
    CountDownLatch remotePutFromLoadLatch = expectRemotePutFromLoad(localRegion.getCache(), remoteRegion.getCache());
    SharedSessionContractImplementor s3 = mockedSession();
    localAccessStrategy.putFromLoad(s3, KEY, VALUE1, s3.getTimestamp(), 1);
    SharedSessionContractImplementor s5 = mockedSession();
    remoteAccessStrategy.putFromLoad(s5, KEY, VALUE1, s5.getTimestamp(), 1);
    // putFromLoad is applied on local node synchronously, but if there's a concurrent update
    // from the other node it can silently fail when acquiring the loc . Then we could try to read
    // before the update is fully applied.
    assertTrue(localPutFromLoadLatch.await(1, TimeUnit.SECONDS));
    assertTrue(remotePutFromLoadLatch.await(1, TimeUnit.SECONDS));
    SharedSessionContractImplementor s4 = mockedSession();
    SharedSessionContractImplementor s6 = mockedSession();
    assertEquals(VALUE1, localAccessStrategy.get(s4, KEY, s4.getTimestamp()));
    assertEquals(VALUE1, remoteAccessStrategy.get(s6, KEY, s6.getTimestamp()));
    CountDownLatch endInvalidationLatch;
    if (invalidation && !evict) {
        // removeAll causes transactional remove commands which trigger EndInvalidationCommands on the remote side
        // if the cache is non-transactional, PutFromLoadValidator.registerRemoteInvalidations cannot find
        // current session nor register tx synchronization, so it falls back to simple InvalidationCommand.
        endInvalidationLatch = new CountDownLatch(1);
        if (transactional) {
            PutFromLoadValidator originalValidator = PutFromLoadValidator.removeFromCache(remoteRegion.getCache());
            assertEquals(PutFromLoadValidator.class, originalValidator.getClass());
            PutFromLoadValidator mockValidator = spy(originalValidator);
            doAnswer(invocation -> {
                try {
                    return invocation.callRealMethod();
                } finally {
                    endInvalidationLatch.countDown();
                }
            }).when(mockValidator).endInvalidatingKey(any(), any());
            PutFromLoadValidator.addToCache(remoteRegion.getCache(), mockValidator);
            cleanup.add(() -> {
                PutFromLoadValidator.removeFromCache(remoteRegion.getCache());
                PutFromLoadValidator.addToCache(remoteRegion.getCache(), originalValidator);
            });
        } else {
            ExpectingInterceptor.get(remoteRegion.getCache()).when((ctx, cmd) -> cmd instanceof InvalidateCommand).countDown(endInvalidationLatch);
            cleanup.add(() -> ExpectingInterceptor.cleanup(remoteRegion.getCache()));
        }
    } else {
        endInvalidationLatch = new CountDownLatch(0);
    }
    withTx(localEnvironment, mockedSession(), () -> {
        if (evict) {
            localAccessStrategy.evictAll();
        } else {
            SoftLock softLock = localAccessStrategy.lockRegion();
            localAccessStrategy.removeAll();
            localAccessStrategy.unlockRegion(softLock);
        }
        return null;
    });
    SharedSessionContractImplementor s7 = mockedSession();
    assertNull(localAccessStrategy.get(s7, KEY, s7.getTimestamp()));
    assertEquals(0, localRegion.getCache().size());
    SharedSessionContractImplementor s8 = mockedSession();
    assertNull(remoteAccessStrategy.get(s8, KEY, s8.getTimestamp()));
    assertEquals(0, remoteRegion.getCache().size());
    // Wait for async propagation of EndInvalidationCommand before executing naked put
    assertTrue(endInvalidationLatch.await(1, TimeUnit.SECONDS));
    TIME_SERVICE.advance(1);
    CountDownLatch lastPutFromLoadLatch = expectRemotePutFromLoad(remoteRegion.getCache(), localRegion.getCache());
    // Test whether the get above messes up the optimistic version
    SharedSessionContractImplementor s9 = mockedSession();
    assertTrue(remoteAccessStrategy.putFromLoad(s9, KEY, VALUE1, s9.getTimestamp(), 1));
    SharedSessionContractImplementor s10 = mockedSession();
    assertEquals(VALUE1, remoteAccessStrategy.get(s10, KEY, s10.getTimestamp()));
    assertEquals(1, remoteRegion.getCache().size());
    assertTrue(lastPutFromLoadLatch.await(1, TimeUnit.SECONDS));
    SharedSessionContractImplementor s11 = mockedSession();
    assertEquals((isUsingInvalidation() ? null : VALUE1), localAccessStrategy.get(s11, KEY, s11.getTimestamp()));
    SharedSessionContractImplementor s12 = mockedSession();
    assertEquals(VALUE1, remoteAccessStrategy.get(s12, KEY, s12.getTimestamp()));
}
Also used : Arrays(java.util.Arrays) Connection(java.sql.Connection) BatchModeJtaPlatform(org.hibernate.test.cache.infinispan.util.BatchModeJtaPlatform) Cache(org.infinispan.Cache) Transaction(org.hibernate.Transaction) AdvancedCache(org.infinispan.AdvancedCache) After(org.junit.After) Mockito.doAnswer(org.mockito.Mockito.doAnswer) CacheDataDescriptionImpl(org.hibernate.cache.internal.CacheDataDescriptionImpl) TestingUtil(org.infinispan.test.TestingUtil) AccessType(org.hibernate.cache.spi.access.AccessType) Predicate(java.util.function.Predicate) TombstoneUpdate(org.hibernate.cache.infinispan.util.TombstoneUpdate) JdbcResourceTransactionAccess(org.hibernate.resource.transaction.backend.jdbc.spi.JdbcResourceTransactionAccess) TestSynchronization(org.hibernate.test.cache.infinispan.util.TestSynchronization) Matchers.any(org.mockito.Matchers.any) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) SoftLock(org.hibernate.cache.spi.access.SoftLock) JdbcSessionOwner(org.hibernate.resource.jdbc.spi.JdbcSessionOwner) AfterClassOnce(org.hibernate.testing.AfterClassOnce) FutureUpdate(org.hibernate.cache.infinispan.util.FutureUpdate) PutKeyValueCommand(org.infinispan.commands.write.PutKeyValueCommand) TransactionImpl(org.hibernate.engine.transaction.internal.TransactionImpl) PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) Mockito.mock(org.mockito.Mockito.mock) JdbcConnectionAccess(org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess) TestResourceTracker(org.infinispan.test.fwk.TestResourceTracker) Logger(org.jboss.logging.Logger) TransactionCoordinator(org.hibernate.resource.transaction.spi.TransactionCoordinator) Session(org.hibernate.Session) Caches(org.hibernate.cache.infinispan.util.Caches) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Mockito.spy(org.mockito.Mockito.spy) ArrayList(java.util.ArrayList) RegionAccessStrategy(org.hibernate.cache.spi.access.RegionAccessStrategy) SQLException(java.sql.SQLException) TestTimeService(org.hibernate.test.cache.infinispan.util.TestTimeService) RollbackException(javax.transaction.RollbackException) TransactionCoordinatorOwner(org.hibernate.resource.transaction.spi.TransactionCoordinatorOwner) ExpectingInterceptor(org.hibernate.test.cache.infinispan.util.ExpectingInterceptor) ComparableComparator(org.hibernate.internal.util.compare.ComparableComparator) BatchModeTransactionCoordinator(org.hibernate.test.cache.infinispan.util.BatchModeTransactionCoordinator) JdbcResourceTransactionMock(org.hibernate.test.cache.infinispan.util.JdbcResourceTransactionMock) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) AssertionFailedError(junit.framework.AssertionFailedError) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) JdbcSessionContext(org.hibernate.resource.jdbc.spi.JdbcSessionContext) TestInfinispanRegionFactory(org.hibernate.test.cache.infinispan.util.TestInfinispanRegionFactory) Mockito.when(org.mockito.Mockito.when) BaseRegion(org.hibernate.cache.infinispan.impl.BaseRegion) ServiceRegistry(org.hibernate.service.ServiceRegistry) TimeUnit(java.util.concurrent.TimeUnit) CacheDataDescription(org.hibernate.cache.spi.CacheDataDescription) InvalidateCommand(org.infinispan.commands.write.InvalidateCommand) Assert.assertNull(org.junit.Assert.assertNull) SystemException(javax.transaction.SystemException) JdbcResourceLocalTransactionCoordinatorBuilderImpl(org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl) SqlExceptionHelper(org.hibernate.engine.jdbc.spi.SqlExceptionHelper) BeforeClassOnce(org.hibernate.testing.BeforeClassOnce) Assert.assertEquals(org.junit.Assert.assertEquals) PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) CountDownLatch(java.util.concurrent.CountDownLatch) InvalidateCommand(org.infinispan.commands.write.InvalidateCommand) SoftLock(org.hibernate.cache.spi.access.SoftLock)

Example 5 with PutFromLoadValidator

use of org.hibernate.cache.infinispan.access.PutFromLoadValidator in project hibernate-orm by hibernate.

the class PutFromLoadValidatorUnitTest method nakedPutTest.

private void nakedPutTest(final boolean transactional) throws Exception {
    PutFromLoadValidator testee = new PutFromLoadValidator(cache, regionFactory(cm));
    exec(transactional, new NakedPut(testee, true));
}
Also used : PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator)

Aggregations

PutFromLoadValidator (org.hibernate.cache.infinispan.access.PutFromLoadValidator)14 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)6 CountDownLatch (java.util.concurrent.CountDownLatch)4 ExecutorService (java.util.concurrent.ExecutorService)3 TimeoutException (java.util.concurrent.TimeoutException)3 Test (org.junit.Test)3 Field (java.lang.reflect.Field)2 Method (java.lang.reflect.Method)2 Map (java.util.Map)2 RegionAccessStrategy (org.hibernate.cache.spi.access.RegionAccessStrategy)2 TestInfinispanRegionFactory (org.hibernate.test.cache.infinispan.util.TestInfinispanRegionFactory)2 Exceptions.expectException (org.infinispan.test.Exceptions.expectException)2 Connection (java.sql.Connection)1 SQLException (java.sql.SQLException)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 NavigableMap (java.util.NavigableMap)1