protected Cache<String, String> startCache() throws IOException { CacheBuilder cb = new CacheBuilder(cfgFile); EmbeddedCacheManager cacheManager = cb.getCacheManager(); Configuration dcc = cacheManager.getDefaultCacheConfiguration(); cacheManager.defineConfiguration( "wordcount", new ConfigurationBuilder() .read(dcc) .clustering() .l1() .disable() .clustering() .cacheMode(CacheMode.DIST_SYNC) .hash() .numOwners(1) .build()); Cache<String, String> cache = cacheManager.getCache(); Transport transport = cache.getAdvancedCache().getRpcManager().getTransport(); if (isMaster) System.out.printf( "Node %s joined as master. View is %s.%n", transport.getAddress(), transport.getMembers()); else System.out.printf( "Node %s joined as slave. View is %s.%n", transport.getAddress(), transport.getMembers()); return cache; }
private Map<CacheCategory, CacheService> createCaches(CacheInfo cacheInfo) { Map<CacheCategory, CacheService> ciCaches = new HashMap<CacheCategory, CacheService>(); for (Map.Entry<CacheCategory, CacheConfiguration> entry : cacheInfo.getConfiguration().entrySet()) { if (entry.getValue() instanceof InfinispanConfiguration) { CacheService cacheService; CacheCategory category = entry.getKey(); InfinispanConfiguration config = (InfinispanConfiguration) entry.getValue(); if (config.isCacheEnabled()) { String configurationName = config.getConfigurationName(); if (null == configurationName) { Configuration dcc = manager.getDefaultCacheConfiguration(); Configuration infinispan = config.getInfinispanConfiguration(new ConfigurationBuilder().read(dcc)); configurationName = "$" + category.getName() + "$" + cacheInfo.getId(); manager.defineConfiguration(configurationName, infinispan); } recorder.record("infinispan", "configuration name " + configurationName); cacheService = new InfinispanCacheService(manager.<String, Object>getCache(configurationName)); } else { cacheService = noCacheFactory.create(null, category); } ciCaches.put(category, cacheService); } } return ciCaches; }
public void testBasicTargetRemoteDistributedCallable() throws Exception { long taskTimeout = TimeUnit.SECONDS.toMillis(15); EmbeddedCacheManager cacheManager1 = manager(0); final EmbeddedCacheManager cacheManager2 = manager(1); Cache<Object, Object> cache1 = cacheManager1.getCache(); Cache<Object, Object> cache2 = cacheManager2.getCache(); DistributedExecutorService des = null; try { des = new DefaultExecutorService(cache1); Address target = cache2.getAdvancedCache().getRpcManager().getAddress(); DistributedTaskBuilder<Integer> builder = des.createDistributedTaskBuilder(new SimpleCallable()) .failoverPolicy(DefaultExecutorService.RANDOM_NODE_FAILOVER) .timeout(taskTimeout, TimeUnit.MILLISECONDS); Future<Integer> future = des.submit(target, builder.build()); AssertJUnit.assertEquals((Integer) 1, future.get()); } catch (Exception ex) { AssertJUnit.fail("Task did not failover properly " + ex); } finally { des.shutdown(); } }
public void testPreloadOnStart() throws CacheLoaderException { for (int i = 0; i < NUM_KEYS; i++) { c1.put("k" + i, "v" + i); } DataContainer dc1 = c1.getAdvancedCache().getDataContainer(); assert dc1.size(null) == NUM_KEYS; DummyInMemoryCacheStore cs = (DummyInMemoryCacheStore) TestingUtil.extractComponent(c1, CacheLoaderManager.class).getCacheStore(); assert cs.loadAllKeys(Collections.emptySet()).size() == NUM_KEYS; addClusterEnabledCacheManager(); EmbeddedCacheManager cm2 = cacheManagers.get(1); cm2.defineConfiguration(cacheName, buildConfiguration()); c2 = cache(1, cacheName); waitForClusterToForm(); DataContainer dc2 = c2.getAdvancedCache().getDataContainer(); assert dc2.size(null) == NUM_KEYS : "Expected all the cache store entries to be preloaded on the second cache"; for (int i = 0; i < NUM_KEYS; i++) { assertOwnershipAndNonOwnership("k" + i, true); } }
@Test public void testBuildDiffCacheNameTimestampsRegion() { final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache"; Properties p = createProperties(); p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "unrecommended-timestamps"); InfinispanRegionFactory factory = createRegionFactory(p); try { EmbeddedCacheManager manager = factory.getCacheManager(); assertFalse(factory.getDefinedConfigurations().contains("timestamp")); assertTrue(factory.getDefinedConfigurations().contains("unrecommended-timestamps")); assertTrue( factory .getTypeOverrides() .get("timestamps") .getCacheName() .equals("unrecommended-timestamps")); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().stateTransfer().fetchInMemoryState(true); builder.clustering().cacheMode(CacheMode.REPL_SYNC); manager.defineConfiguration("unrecommended-timestamps", builder.build()); TimestampsRegionImpl region = (TimestampsRegionImpl) factory.buildTimestampsRegion(timestamps, p); AdvancedCache cache = region.getCache(); Configuration cacheCfg = cache.getCacheConfiguration(); assertEquals(EvictionStrategy.NONE, cacheCfg.eviction().strategy()); assertEquals(CacheMode.REPL_SYNC, cacheCfg.clustering().cacheMode()); assertFalse(cacheCfg.storeAsBinary().enabled()); assertFalse(cacheCfg.jmxStatistics().enabled()); } finally { factory.stop(); } }
private Cache getCache(String regionName, String typeKey, Properties properties) { TypeOverrides regionOverride = typeOverrides.get(regionName); if (!definedConfigurations.contains(regionName)) { String templateCacheName = null; Configuration regionCacheCfg = null; if (regionOverride != null) { if (log.isDebugEnabled()) log.debug("Cache region specific configuration exists: " + regionOverride); regionOverride = overrideStatisticsIfPresent(regionOverride, properties); regionCacheCfg = regionOverride.createInfinispanConfiguration(); String cacheName = regionOverride.getCacheName(); if (cacheName != null) // Region specific override with a given cache name templateCacheName = cacheName; else // Region specific override without cache name, so template cache name is generic for // data type. templateCacheName = typeOverrides.get(typeKey).getCacheName(); } else { // No region specific overrides, template cache name is generic for data type. templateCacheName = typeOverrides.get(typeKey).getCacheName(); regionCacheCfg = typeOverrides.get(typeKey).createInfinispanConfiguration(); } // Configure transaction manager regionCacheCfg = configureTransactionManager(regionCacheCfg, templateCacheName, properties); // Apply overrides manager.defineConfiguration(regionName, templateCacheName, regionCacheCfg); definedConfigurations.add(regionName); } Cache cache = manager.getCache(regionName); if (!cache.getStatus().allowInvocations()) { cache.start(); } return createCacheWrapper(cache.getAdvancedCache()); }
@Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { ModelNode newValue = operation.require(CacheContainerResource.PROTO_URL.getName()); String urlString = newValue.asString(); final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR)); final String cacheContainerName = address.getElement(address.size() - 1).getValue(); final ServiceController<?> controller = context .getServiceRegistry(false) .getService(EmbeddedCacheManagerService.getServiceName(cacheContainerName)); EmbeddedCacheManager cacheManager = (EmbeddedCacheManager) controller.getValue(); ProtobufMetadataManager protoManager = cacheManager.getGlobalComponentRegistry().getComponent(ProtobufMetadataManager.class); if (protoManager != null) { try { URL url = new URL(urlString); protoManager.registerProtofile(url.openStream()); } catch (Exception e) { throw new OperationFailedException( new ModelNode().set(MESSAGES.failedToInvokeOperation(e.getLocalizedMessage()))); } } context.stepCompleted(); }
public void testDisabledInterceptorStack() { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.storeAsBinary().disable(); cm.defineConfiguration("a", cfg.build()); Cache<?, ?> c = cm.getCache("a"); assert TestingUtil.findInterceptor(c, MarshalledValueInterceptor.class) == null; }
@Override public CompletableFuture<Object> invokeAsync() throws Throwable { GlobalComponentRegistry globalComponentRegistry = cacheManager.getGlobalComponentRegistry(); ComponentRegistry cacheComponentRegistry = globalComponentRegistry.getNamedComponentRegistry(cacheName); String name = cacheName.toString(); if (cacheComponentRegistry != null) { cacheComponentRegistry.getComponent(PersistenceManager.class).setClearOnStop(true); cacheComponentRegistry.getComponent(CacheJmxRegistration.class).setUnregisterCacheMBean(true); cacheComponentRegistry.getComponent(PassivationManager.class).skipPassivationOnStop(true); Cache<?, ?> cache = cacheManager.getCache(name, false); if (cache != null) { cache.stop(); } } globalComponentRegistry.removeCache(name); // Remove cache configuration and remove it from the computed cache name list globalComponentRegistry.getComponent(ConfigurationManager.class).removeConfiguration(name); // Remove cache from dependency graph //noinspection unchecked globalComponentRegistry .getComponent(DependencyGraph.class, CACHE_DEPENDENCY_GRAPH) .remove(cacheName); return CompletableFutures.completedNull(); }
public static boolean isCacheViewComplete( EmbeddedCacheManager cacheContainer, int memberCount, boolean barfIfTooManyMembers) { List<Address> members = cacheContainer.getMembers(); if (members == null || memberCount > members.size()) { return false; } else if (memberCount < members.size()) { if (barfIfTooManyMembers) { // This is an exceptional condition StringBuffer sb = new StringBuffer("Cache at address "); sb.append(cacheContainer.getAddress()); sb.append(" had "); sb.append(members.size()); sb.append(" members; expecting "); sb.append(memberCount); sb.append(". Members were ("); for (int j = 0; j < members.size(); j++) { if (j > 0) { sb.append(", "); } sb.append(members.get(j)); } sb.append(')'); throw new IllegalStateException(sb.toString()); } return false; } return true; }
@BeforeTest public void setUp() { // Use a clustered cache manager to be able to test global marshaller interaction too cm = TestCacheManagerFactory.createClusteredCacheManager(); cm.getDefaultConfiguration().fluent().clustering().mode(Configuration.CacheMode.DIST_SYNC); marshaller = extractCacheMarshaller(cm.getCache()); }
private HotRodServer addHotRodServer() { EmbeddedCacheManager cm = addClusterEnabledCacheManager(defaultBuilder); cm.defineConfiguration(DIST_ONE_CACHE_NAME, distOneBuilder.build()); cm.defineConfiguration(DIST_TWO_CACHE_NAME, distTwoBuilder.build()); HotRodServer server = HotRodClientTestingUtil.startHotRodServer(cm); addr2hrServer.put(new InetSocketAddress(server.getHost(), server.getPort()), server); return server; }
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(); }
public static void verifyConfiguredAsClustered(final EmbeddedCacheManager cacheManager) { final GlobalConfiguration globalConfiguration = cacheManager.getCacheManagerConfiguration(); Assert.assertTrue( "This CacheManager is not configured for clustering", globalConfiguration.isClustered()); Assert.assertNotNull( "This CacheManager is configured for clustering but the Transport was not found", cacheManager.getTransport()); }
/** Testing putIfAbsent's behaviour on a Local cache. */ protected void testonInfinispanLocal() throws Exception { EmbeddedCacheManager cm = TestCacheManagerFactory.createLocalCacheManager(false); ConcurrentMap<String, String> map = cm.getCache(); try { testConcurrentLocking(map); } finally { TestingUtil.clearContent(cm); } }
@Override public <KOut, VOut> Map<KOut, VOut> reduce(ReduceCommand<KOut, VOut> reduceCommand) throws InterruptedException { Cache<?, ?> cache = cacheManager.getCache(reduceCommand.getCacheName()); Set<KOut> keys = reduceCommand.getKeys(); String taskId = reduceCommand.getTaskId(); Reducer<KOut, VOut> reducer = reduceCommand.getReducer(); boolean useIntermediateKeys = reduceCommand.isEmitCompositeIntermediateKeys(); boolean noInputKeys = keys == null || keys.isEmpty(); Cache<Object, List<VOut>> tmpCache = cacheManager.getCache(reduceCommand.getCacheName()); Map<KOut, VOut> result = new HashMap<KOut, VOut>(); if (noInputKeys) { // illegal state, raise exception throw new IllegalStateException( "Reduce phase of MapReduceTask " + taskId + " on node " + cdl.getAddress() + " executed with empty input keys"); } else { // first hook into lifecycle MapReduceTaskLifecycleService taskLifecycleService = MapReduceTaskLifecycleService.getInstance(); log.tracef("For m/r task %s invoking %s at %s", taskId, reduceCommand, cdl.getAddress()); int interruptCount = 0; long start = log.isTraceEnabled() ? timeService.time() : 0; try { taskLifecycleService.onPreExecute(reducer, cache); for (KOut key : keys) { interruptCount++; if (checkInterrupt(interruptCount++) && Thread.currentThread().isInterrupted()) throw new InterruptedException(); // load result value from map phase List<VOut> value; if (useIntermediateKeys) { value = tmpCache.get(new IntermediateCompositeKey<KOut>(taskId, key)); } else { value = tmpCache.get(key); } // and reduce it VOut reduced = reducer.reduce(key, value.iterator()); result.put(key, reduced); log.tracef( "For m/r task %s reduced %s to %s at %s ", taskId, key, reduced, cdl.getAddress()); } } finally { if (log.isTraceEnabled()) { log.tracef( "Reduce for task %s took %s milliseconds", reduceCommand.getTaskId(), timeService.timeDuration(start, TimeUnit.MILLISECONDS)); } taskLifecycleService.onPostExecute(reducer); } } return result; }
@Override protected EmbeddedCacheManager createCacheManager() throws Exception { // start a single cache instance ConfigurationBuilder cb = getDefaultStandaloneCacheConfig(true); cb.invocationBatching().enable(); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(cb); cache = new TreeCacheImpl<Object, Object>(cm.getCache()); tm = cache.getCache().getAdvancedCache().getTransactionManager(); return cm; }
private void lookupCache(String cacheName) { // Attempt to resolve the cache container to use for the distributed registry through JNDI try { EmbeddedCacheManager cm = (EmbeddedCacheManager) new InitialContext().lookup(CACHE_CONTAINER_ROOT + cacheName); _cache = cm.getCache(); } catch (Exception ex) { _log.debug("Failed to lookup cache container for distributed registry", ex); } }
@Override protected EmbeddedCacheManager createCacheManager() throws Exception { // start a single cache instance ConfigurationBuilder c = getDefaultStandaloneCacheConfig(true); c.storeAsBinary().enable(); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(false); cm.defineConfiguration("lazy-cache-test", c.build()); cache = cm.getCache("lazy-cache-test"); return cm; }
@Stop private void stop() { if (clustered) { notifier.removeListener(cleanupService); cm.removeListener(cleanupService); cleanupService.stop(); cm.removeListener(this); currentViewId = CACHE_STOPPED_VIEW_ID; // indicate that the cache has stopped } shutDownGracefully(); }
public void testDefaultInterceptorStack() { assert TestingUtil.findInterceptor(cm.getCache(), MarshalledValueInterceptor.class) == null; ConfigurationBuilder configuration = new ConfigurationBuilder(); configuration.storeAsBinary().enable(); cm.defineConfiguration("someCache", configuration.build()); Cache<?, ?> c = cm.getCache("someCache"); assert TestingUtil.findInterceptor(c, MarshalledValueInterceptor.class) != null; TestingUtil.killCaches(c); }
@Override protected void createCacheManagers() throws Throwable { Configuration cfg = TestCacheManagerFactory.getDefaultConfiguration(true, Configuration.CacheMode.DIST_SYNC); cfg.setLockAcquisitionTimeout(100); EmbeddedCacheManager cm1 = TestCacheManagerFactory.createClusteredCacheManager(cfg); EmbeddedCacheManager cm2 = TestCacheManagerFactory.createClusteredCacheManager(cfg); registerCacheManager(cm1, cm2); c1 = cm1.getCache(); c2 = cm2.getCache(); }
@Test public void testEnableStatistics() { Properties p = createProperties(); p.setProperty("hibernate.cache.infinispan.statistics", "true"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000"); p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache"); p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO"); p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000"); p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000"); InfinispanRegionFactory factory = createRegionFactory(p); try { EmbeddedCacheManager manager = factory.getCacheManager(); assertTrue(manager.getCacheManagerConfiguration().globalJmxStatistics().enabled()); EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, MUTABLE_NON_VERSIONED); AdvancedCache cache = region.getCache(); assertTrue(factory.getTypeOverrides().get("entity").isExposeStatistics()); assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled()); region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Person", p, MUTABLE_NON_VERSIONED); cache = region.getCache(); assertTrue(factory.getTypeOverrides().get("com.acme.Person").isExposeStatistics()); assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled()); final String query = "org.hibernate.cache.internal.StandardQueryCache"; QueryResultsRegionImpl queryRegion = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(query, p); cache = queryRegion.getCache(); assertTrue(factory.getTypeOverrides().get("query").isExposeStatistics()); assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled()); final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache"; ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().stateTransfer().fetchInMemoryState(true); manager.defineConfiguration("timestamps", builder.build()); TimestampsRegionImpl timestampsRegion = (TimestampsRegionImpl) factory.buildTimestampsRegion(timestamps, p); cache = timestampsRegion.getCache(); assertTrue(factory.getTypeOverrides().get("timestamps").isExposeStatistics()); assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled()); CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion("com.acme.Person.addresses", p, MUTABLE_NON_VERSIONED); cache = collectionRegion.getCache(); assertTrue(factory.getTypeOverrides().get("collection").isExposeStatistics()); assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled()); } finally { factory.stop(); } }
private List<Cache<?, ?>> getAllCaches(Session session) { List<Cache<?, ?>> caches = new ArrayList<Cache<?, ?>>(); EmbeddedCacheManager container = session.getCacheManager(); for (String cacheName : container.getCacheNames()) { if (container.isRunning(cacheName)) { caches.add(session.getCache(cacheName)); } } caches.add(container.getCache()); return caches; }
private void testPutOperation(boolean batching, boolean inTran) throws Exception { EmbeddedCacheManager cacheManager = getCacheManager(batching); try { Cache<Object, Object> c = cacheManager.getCache(); if (inTran) c.getAdvancedCache().getTransactionManager().begin(); c.put("key1", new SEntity(1, "name1", "surname1")); if (inTran) c.getAdvancedCache().getTransactionManager().commit(); assertEquals(searchByName("name1", c).size(), 1, "should be 1, even repeating this"); } finally { cacheManager.stop(); } }
private static void removeInMemoryData(Cache cache) { EmbeddedCacheManager mgr = cache.getCacheManager(); Address a = mgr.getAddress(); String str; if (a == null) str = "a non-clustered cache manager"; else str = "a cache manager at address " + a; log.debugf("Cleaning data for cache '%s' on %s", cache.getName(), str); DataContainer dataContainer = TestingUtil.extractComponent(cache, DataContainer.class); log.debugf("removeInMemoryData(): dataContainerBefore == %s", dataContainer.entrySet()); dataContainer.clear(); log.debugf("removeInMemoryData(): dataContainerAfter == %s", dataContainer.entrySet()); }
private static boolean areCacheViewsChanged(Cache[] caches, int finalViewSize) { int memberCount = caches.length; for (int i = 0; i < memberCount; i++) { EmbeddedCacheManager cacheManager = caches[i].getCacheManager(); if (!isCacheViewChanged(cacheManager.getMembers(), finalViewSize)) { return false; } } return true; }
@Test public void testCacheManager() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.transaction().invocationBatching().enable(); EmbeddedCacheManager cm = new DefaultCacheManager(builder.build()); Cache<String, String> cache = cm.getCache(); TreeCacheFactory tcf = new TreeCacheFactory(); TreeCache<String, String> tree = tcf.createTreeCache(cache); Fqn leafFqn = Fqn.fromElements("branch", "leaf"); Node<String, String> leaf = tree.getRoot().addChild(leafFqn); leaf.put("fruit", "orange"); cm.stop(); }
@Override public void run() { try { log.info("Starting a new cache manager"); EmbeddedCacheManager cacheManager = buildCacheManager(); cacheManager.getCache("serviceGroup"); cacheManagers.addLast(cacheManager); } catch (Exception e) { log.warn("Error during node addition", e); } }
private static void viewsTimedOut(CacheContainer[] cacheContainers) { int length = cacheContainers.length; List<List<Address>> allViews = new ArrayList<List<Address>>(length); for (int i = 0; i < length; i++) { EmbeddedCacheManager cm = (EmbeddedCacheManager) cacheContainers[i]; allViews.add(cm.getMembers()); } throw new RuntimeException( String.format( "Timed out before caches had complete views. Expected %d members in each view. Views are as follows: %s", cacheContainers.length, allViews)); }