Skip to content

Commit

Permalink
ISPN-9174 Qualify region names in v53.InfinispanRegionFactory
Browse files Browse the repository at this point in the history
  • Loading branch information
rvansa authored and galderz committed May 23, 2018
1 parent 0575f4a commit da1f45e
Show file tree
Hide file tree
Showing 14 changed files with 117 additions and 46 deletions.
Expand Up @@ -27,18 +27,18 @@
public class CacheCommandFactory implements ModuleCommandFactory { public class CacheCommandFactory implements ModuleCommandFactory {


/** /**
* Keeps track of regions to which second-level cache specific * Keeps track of regions to which second-level cache specific commands have been plugged.
* commands have been plugged. * The regions are keyed by cache name (which is qualified), not by region name that is unqualified in Hibernate 5.3+
*/ */
private ConcurrentMap<String, InfinispanBaseRegion> allRegions = new ConcurrentHashMap<>(); private ConcurrentMap<ByteString, InfinispanBaseRegion> allRegions = new ConcurrentHashMap<>();


/** /**
* Add region so that commands can be cleared on shutdown. * Add region so that commands can be cleared on shutdown.
* *
* @param region instance to keep track of * @param region instance to keep track of
*/ */
public void addRegion(InfinispanBaseRegion region) { public void addRegion(InfinispanBaseRegion region) {
allRegions.put( region.getName(), region ); allRegions.put(ByteString.fromString(region.getCache().getName()), region);
} }


/** /**
Expand All @@ -47,7 +47,7 @@ public void addRegion(InfinispanBaseRegion region) {
* @param regions collection of regions to clear * @param regions collection of regions to clear
*/ */
public void clearRegions(Collection<? extends InfinispanBaseRegion> regions) { public void clearRegions(Collection<? extends InfinispanBaseRegion> regions) {
regions.forEach( region -> allRegions.remove( region.getName() ) ); regions.forEach(region -> allRegions.remove(ByteString.fromString(region.getCache().getName())));
} }


@Override @Override
Expand All @@ -64,7 +64,7 @@ public CacheRpcCommand fromStream(byte commandId, ByteString cacheName) {
CacheRpcCommand c; CacheRpcCommand c;
switch ( commandId ) { switch ( commandId ) {
case CacheCommandIds.EVICT_ALL: case CacheCommandIds.EVICT_ALL:
c = new EvictAllCommand( cacheName, allRegions.get( cacheName.toString() ) ); c = new EvictAllCommand(cacheName, allRegions.get(cacheName));
break; break;
case CacheCommandIds.END_INVALIDATION: case CacheCommandIds.END_INVALIDATION:
c = new EndInvalidationCommand(cacheName); c = new EndInvalidationCommand(cacheName);
Expand Down
Expand Up @@ -217,8 +217,8 @@ public static AdvancedCache failSilentReadCache(AdvancedCache cache) {


/** /**
* Broadcast an evict-all command with the given cache instance. * Broadcast an evict-all command with the given cache instance.
*
* @param cache instance used to broadcast command * @param cache instance used to broadcast command
*
*/ */
public static void broadcastEvictAll(AdvancedCache cache) { public static void broadcastEvictAll(AdvancedCache cache) {
final RpcManager rpcManager = cache.getRpcManager(); final RpcManager rpcManager = cache.getRpcManager();
Expand Down
Expand Up @@ -60,7 +60,7 @@ public abstract class AbstractRegionAccessStrategyTest<S>
extends AbstractNonFunctionalTest { extends AbstractNonFunctionalTest {
protected final Logger log = Logger.getLogger(getClass()); protected final Logger log = Logger.getLogger(getClass());


public static final String REGION_NAME = "test/com.foo.test"; public static final String REGION_NAME = "com.foo.test";
public static final String KEY_BASE = "KEY"; public static final String KEY_BASE = "KEY";
public static final TestCacheEntry VALUE1 = new TestCacheEntry("VALUE1", 1); public static final TestCacheEntry VALUE1 = new TestCacheEntry("VALUE1", 1);
public static final TestCacheEntry VALUE2 = new TestCacheEntry("VALUE2", 2); public static final TestCacheEntry VALUE2 = new TestCacheEntry("VALUE2", 2);
Expand Down Expand Up @@ -127,6 +127,7 @@ public void cleanup() {
if (remoteRegion != null) remoteRegion.getCache().clear(); if (remoteRegion != null) remoteRegion.getCache().clear();
node1Exception = node2Exception = null; node1Exception = node2Exception = null;
node1Failure = node2Failure = null; node1Failure = node2Failure = null;
TIME_SERVICE.advance(1); // There might be invalidation from the previous test
} }


@AfterClassOnce @AfterClassOnce
Expand Down
@@ -0,0 +1,46 @@
package org.infinispan.test.hibernate.cache.commons.functional;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.hibernate.cfg.AvailableSettings;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess;
import org.junit.Test;

public class QualifierTest extends AbstractFunctionalTest {
public static final String FOO_BAR = "foo.bar";

@Override
public List<Object[]> getParameters() {
return Collections.singletonList(READ_WRITE_DISTRIBUTED);
}

@Override
protected void addSettings(Map settings) {
super.addSettings(settings);
settings.put(AvailableSettings.CACHE_REGION_PREFIX, FOO_BAR);
}

@Test
public void testRegionNamesQualified() {
TestRegionFactory factory = TestRegionFactoryProvider.INSTANCE.findRegionFactory(sessionFactory().getCache());
EmbeddedCacheManager cacheManager = factory.getCacheManager();
for (String cacheName : cacheManager.getCacheNames()) {
assertTrue(cacheName.startsWith(FOO_BAR));
}
// In Hibernate < 5.3 the region factory got qualified names and couldn't use any unqualified form
if (!TestRegionFactoryProvider.INSTANCE.getRegionFactoryClass().getName().contains(".v51.")) {
for (InfinispanBaseRegion region : TestSessionAccess.findTestSessionAccess().getAllRegions(sessionFactory())) {
assertFalse(region.getName().startsWith(FOO_BAR));
}
}
}
}
Expand Up @@ -9,6 +9,7 @@
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion; import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.util.ControlledTimeService; import org.infinispan.util.ControlledTimeService;


import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.ServiceLoader; import java.util.ServiceLoader;


Expand Down Expand Up @@ -45,6 +46,8 @@ static TestSessionAccess findTestSessionAccess() {


InfinispanBaseRegion getRegion(SessionFactoryImplementor sessionFactory, String regionName); InfinispanBaseRegion getRegion(SessionFactoryImplementor sessionFactory, String regionName);


Collection<InfinispanBaseRegion> getAllRegions(SessionFactoryImplementor sessionFactory);

interface TestRegionAccessStrategy { interface TestRegionAccessStrategy {


SoftLock lockItem(Object session, Object key, Object version) throws CacheException; SoftLock lockItem(Object session, Object key, Object version) throws CacheException;
Expand Down
Expand Up @@ -462,4 +462,8 @@ else if ( ispnTmLookupClassName != null && !ispnTmLookupClassName.equals( hbTmLo
builder.transaction().useSynchronization( DEF_USE_SYNCHRONIZATION ); builder.transaction().useSynchronization( DEF_USE_SYNCHRONIZATION );
} }
} }

public SessionFactoryOptions getSettings() {
return settings;
}
} }
Expand Up @@ -85,9 +85,8 @@ public void evictAll() throws CacheException {
try { try {
// Invalidate the local region and then go remote // Invalidate the local region and then go remote
invalidateRegion(); invalidateRegion();
Caches.broadcastEvictAll( cache ); Caches.broadcastEvictAll(cache);
} } finally {
finally {
resume( tx ); resume( tx );
} }
} }
Expand Down
Expand Up @@ -74,21 +74,29 @@ public Configuration getPendingPutsCacheConfiguration() {


@Override @Override
public InfinispanBaseRegion buildCollectionRegion(String regionName, AccessType accessType) { public InfinispanBaseRegion buildCollectionRegion(String regionName, AccessType accessType) {
String prefix = delegate.getSettings().getCacheRegionPrefix();
if (prefix != null && !prefix.isEmpty()) regionName = prefix + '.' + regionName;
return (InfinispanBaseRegion) delegate.buildCollectionRegion(regionName, null, MUTABLE_VERSIONED); return (InfinispanBaseRegion) delegate.buildCollectionRegion(regionName, null, MUTABLE_VERSIONED);
} }


@Override @Override
public InfinispanBaseRegion buildEntityRegion(String regionName, AccessType accessType) { public InfinispanBaseRegion buildEntityRegion(String regionName, AccessType accessType) {
String prefix = delegate.getSettings().getCacheRegionPrefix();
if (prefix != null && !prefix.isEmpty()) regionName = prefix + '.' + regionName;
return (InfinispanBaseRegion) delegate.buildEntityRegion(regionName, null, MUTABLE_VERSIONED); return (InfinispanBaseRegion) delegate.buildEntityRegion(regionName, null, MUTABLE_VERSIONED);
} }


@Override @Override
public InfinispanBaseRegion buildTimestampsRegion(String regionName) { public InfinispanBaseRegion buildTimestampsRegion(String regionName) {
String prefix = delegate.getSettings().getCacheRegionPrefix();
if (prefix != null && !prefix.isEmpty()) regionName = prefix + '.' + regionName;
return (InfinispanBaseRegion) delegate.buildTimestampsRegion(regionName, null); return (InfinispanBaseRegion) delegate.buildTimestampsRegion(regionName, null);
} }


@Override @Override
public InfinispanBaseRegion buildQueryResultsRegion(String regionName) { public InfinispanBaseRegion buildQueryResultsRegion(String regionName) {
String prefix = delegate.getSettings().getCacheRegionPrefix();
if (prefix != null && !prefix.isEmpty()) regionName = prefix + '.' + regionName;
return (InfinispanBaseRegion) delegate.buildQueryResultsRegion(regionName, null); return (InfinispanBaseRegion) delegate.buildQueryResultsRegion(regionName, null);
} }


Expand Down
Expand Up @@ -36,6 +36,7 @@


import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Collection;
import java.util.List; import java.util.List;


import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
Expand Down Expand Up @@ -167,6 +168,11 @@ public InfinispanBaseRegion getRegion(SessionFactoryImplementor sessionFactory,
return (InfinispanBaseRegion) sessionFactory.getSecondLevelCacheRegion(regionName); return (InfinispanBaseRegion) sessionFactory.getSecondLevelCacheRegion(regionName);
} }


@Override
public Collection<InfinispanBaseRegion> getAllRegions(SessionFactoryImplementor sessionFactory) {
return sessionFactory.getAllSecondLevelCacheRegions().values();
}

private static SessionImplementor unwrap(Object session) { private static SessionImplementor unwrap(Object session) {
return (SessionImplementor) session; return (SessionImplementor) session;
} }
Expand Down
Expand Up @@ -111,15 +111,12 @@ public InfinispanRegionFactory(Properties props) {


@Override @Override
public DomainDataRegion buildDomainDataRegion(DomainDataRegionConfig regionConfig, DomainDataRegionBuildingContext buildingContext) { public DomainDataRegion buildDomainDataRegion(DomainDataRegionConfig regionConfig, DomainDataRegionBuildingContext buildingContext) {
if ( log.isDebugEnabled() ) { log.debugf("Building domain data region [%s] entities=%s collections=%s naturalIds=%s",
log.debugf( regionConfig.getRegionName(),
"Building domain data region [%s] entities=%s collections=%s naturalIds=%s", regionConfig.getEntityCaching(),
regionConfig.getRegionName(), regionConfig.getCollectionCaching(),
regionConfig.getEntityCaching(), regionConfig.getNaturalIdCaching()
regionConfig.getCollectionCaching(), );
regionConfig.getNaturalIdCaching()
);
}
// TODO: data type is probably deprecated, but we need it for backwards-compatible configuration // TODO: data type is probably deprecated, but we need it for backwards-compatible configuration
DataType dataType; DataType dataType;
int entities = regionConfig.getEntityCaching().size(); int entities = regionConfig.getEntityCaching().size();
Expand All @@ -137,31 +134,28 @@ public DomainDataRegion buildDomainDataRegion(DomainDataRegionConfig regionConfi
dataType = DataType.ENTITY; dataType = DataType.ENTITY;
} }


AdvancedCache cache = getCache(regionConfig.getRegionName(), dataType); AdvancedCache cache = getCache(qualify(regionConfig.getRegionName()), dataType);
DomainDataRegionImpl region = new DomainDataRegionImpl(cache, regionConfig, this, getCacheKeysFactory()); DomainDataRegionImpl region = new DomainDataRegionImpl(cache, regionConfig, this, getCacheKeysFactory());
startRegion(region); startRegion(region);
return region; return region;
} }


@Override @Override
public QueryResultsRegion buildQueryResultsRegion(String regionName, SessionFactoryImplementor sessionFactory) { public QueryResultsRegion buildQueryResultsRegion(String regionName, SessionFactoryImplementor sessionFactory) {
if ( log.isDebugEnabled() ) { log.debugf("Building query results cache region [%s]", regionName);
log.debug( "Building query results cache region [" + regionName + "]" );
}


AdvancedCache cache = getCache(regionName, DataType.QUERY); AdvancedCache cache = getCache(qualify(regionName), DataType.QUERY);
QueryResultsRegionImpl region = new QueryResultsRegionImpl(cache, regionName, this); QueryResultsRegionImpl region = new QueryResultsRegionImpl(cache, regionName, this);
startRegion(region); startRegion(region);
return region; return region;
} }


@Override @Override
public TimestampsRegion buildTimestampsRegion(String regionName, SessionFactoryImplementor sessionFactory) { public TimestampsRegion buildTimestampsRegion(String regionName, SessionFactoryImplementor sessionFactory) {
if ( log.isDebugEnabled() ) { log.debugf("Building timestamps cache region [%s]", regionName);
log.debug( "Building timestamps cache region [" + regionName + "]" );
} final AdvancedCache cache = getCache(qualify(regionName), DataType.TIMESTAMPS);
final AdvancedCache cache = getCache(regionName, DataType.TIMESTAMPS); TimestampsRegionImpl region = createTimestampsRegion(cache, regionName);
TimestampsRegionImpl region = createTimestampsRegion( cache, regionName );
startRegion(region); startRegion(region);
return region; return region;
} }
Expand Down Expand Up @@ -427,17 +421,17 @@ private void defineDataTypeCacheConfigurations(ServiceRegistry serviceRegistry)
} }
} }


protected AdvancedCache getCache(String regionName, DataType type) { protected AdvancedCache getCache(String cacheName, DataType type) {
if (!manager.cacheExists(regionName)) { if (!manager.cacheExists(cacheName)) {
String templateCacheName = baseConfigurations.get(regionName); String templateCacheName = baseConfigurations.get(cacheName);
Configuration configuration = null; Configuration configuration = null;
ConfigurationBuilder builder = new ConfigurationBuilder(); ConfigurationBuilder builder = new ConfigurationBuilder();
if (templateCacheName != null) { if (templateCacheName != null) {
configuration = manager.getCacheConfiguration(templateCacheName); configuration = manager.getCacheConfiguration(templateCacheName);
if (configuration == null) { if (configuration == null) {
log.customConfigForRegionNotFound(templateCacheName, regionName, type.key); log.customConfigForRegionNotFound(templateCacheName, cacheName, type.key);
} else { } else {
log.debugf("Region '%s' will use cache template '%s'", regionName, templateCacheName); log.debugf("Region '%s' will use cache template '%s'", cacheName, templateCacheName);
builder.read(configuration); builder.read(configuration);
unsetTransactions(builder); unsetTransactions(builder);
// do not apply data type overrides to regions that set special cache configuration // do not apply data type overrides to regions that set special cache configuration
Expand All @@ -451,19 +445,19 @@ protected AdvancedCache getCache(String regionName, DataType type) {
builder.read(configuration); builder.read(configuration);
// overrides for data types are already applied, but we should check custom ones // overrides for data types are already applied, but we should check custom ones
} }
ConfigurationBuilder override = configOverrides.get(regionName); ConfigurationBuilder override = configOverrides.get(cacheName);
if (override != null) { if (override != null) {
log.debugf("Region '%s' has additional configuration set through properties.", regionName); log.debugf("Region '%s' has additional configuration set through properties.", cacheName);
builder.read(override.build(false)); builder.read(override.build(false));
} }
if (globalStats != null) { if (globalStats != null) {
builder.jmxStatistics().enabled(globalStats).available(globalStats); builder.jmxStatistics().enabled(globalStats).available(globalStats);
} }
configuration = builder.build(); configuration = builder.build();
type.validate(configuration); type.validate(configuration);
manager.defineConfiguration(regionName, configuration); manager.defineConfiguration(cacheName, configuration);
} }
final AdvancedCache cache = manager.getCache( regionName ).getAdvancedCache(); final AdvancedCache cache = manager.getCache( cacheName ).getAdvancedCache();
// TODO: not sure if this is needed in recent Infinispan // TODO: not sure if this is needed in recent Infinispan
if ( !cache.getStatus().allowInvocations() ) { if ( !cache.getStatus().allowInvocations() ) {
cache.start(); cache.start();
Expand Down
Expand Up @@ -79,10 +79,9 @@ protected enum Strategy {
NONE, VALIDATION, TOMBSTONES, VERSIONED_ENTRIES NONE, VALIDATION, TOMBSTONES, VERSIONED_ENTRIES
} }


public DomainDataRegionImpl( public DomainDataRegionImpl(AdvancedCache cache, DomainDataRegionConfig config,
AdvancedCache cache, DomainDataRegionConfig config, InfinispanRegionFactory factory, CacheKeysFactory cacheKeysFactory) {
InfinispanRegionFactory factory, CacheKeysFactory cacheKeysFactory) { super(cache, config.getRegionName(), factory);
super( cache, config.getRegionName(), factory);
this.config = config; this.config = config;
this.cacheKeysFactory = cacheKeysFactory; this.cacheKeysFactory = cacheKeysFactory;


Expand Down
Expand Up @@ -61,7 +61,7 @@ public void clear() throws CacheException {
transactionContext.clear(); transactionContext.clear();
// Invalidate the local region and then go remote // Invalidate the local region and then go remote
invalidateRegion(); invalidateRegion();
Caches.broadcastEvictAll( cache ); Caches.broadcastEvictAll(cache);
} }


@Override @Override
Expand Down
Expand Up @@ -66,8 +66,8 @@ protected EmbeddedCacheManager createCacheManager(Properties properties, Service
} }


@Override @Override
protected AdvancedCache getCache(String regionName, DataType type) { protected AdvancedCache getCache(String cacheName, DataType type) {
AdvancedCache cache = super.getCache(regionName, type); AdvancedCache cache = super.getCache(cacheName, type);
return wrapCache == null ? cache : wrapCache.apply(cache); return wrapCache == null ? cache : wrapCache.apply(cache);
} }


Expand Down
Expand Up @@ -6,6 +6,7 @@
import org.hibernate.boot.spi.SessionFactoryOptions; import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException; import org.hibernate.cache.CacheException;
import org.hibernate.cache.cfg.spi.DomainDataCachingConfig; import org.hibernate.cache.cfg.spi.DomainDataCachingConfig;
import org.hibernate.cache.spi.CacheImplementor;
import org.hibernate.cache.spi.DirectAccessRegion; import org.hibernate.cache.spi.DirectAccessRegion;
import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cache.spi.access.CachedDomainDataAccess; import org.hibernate.cache.spi.access.CachedDomainDataAccess;
Expand Down Expand Up @@ -42,7 +43,9 @@


import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;


import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
Expand Down Expand Up @@ -193,6 +196,14 @@ public InfinispanBaseRegion getRegion(SessionFactoryImplementor sessionFactory,
return (InfinispanBaseRegion) sessionFactory.getCache().getRegion(regionName); return (InfinispanBaseRegion) sessionFactory.getCache().getRegion(regionName);
} }


@Override
public Collection<InfinispanBaseRegion> getAllRegions(SessionFactoryImplementor sessionFactory) {
CacheImplementor cache = sessionFactory.getCache();
return cache.getCacheRegionNames().stream()
.map(regionName -> (InfinispanBaseRegion) cache.getRegion(regionName))
.collect(Collectors.toList());
}

private static SharedSessionContractImplementor unwrap(Object session) { private static SharedSessionContractImplementor unwrap(Object session) {
return (SharedSessionContractImplementor) session; return (SharedSessionContractImplementor) session;
} }
Expand Down

0 comments on commit da1f45e

Please sign in to comment.