Search in sources :

Example 21 with GlobalComponentRegistry

use of org.infinispan.factories.GlobalComponentRegistry in project infinispan by infinispan.

the class ClusterTopologyManagerImplTest method testCoordinatorLostDuringRebalance.

/**
 * Assume there are already 2 nodes and the coordinator leaves during rebalance
 */
public void testCoordinatorLostDuringRebalance() throws Exception {
    // Create global component registry with dependencies
    GlobalConfiguration gc = GlobalConfigurationBuilder.defaultClusteredBuilder().build();
    EmbeddedCacheManager cacheManager = mock(EmbeddedCacheManager.class);
    GlobalComponentRegistry gcr = new GlobalComponentRegistry(gc, cacheManager, Collections.emptySet(), TestModuleRepository.defaultModuleRepository(), mock(ConfigurationManager.class));
    BasicComponentRegistry gbcr = gcr.getComponent(BasicComponentRegistry.class);
    CacheManagerNotifierImpl managerNotifier = new CacheManagerNotifierImpl();
    gbcr.replaceComponent(CacheManagerNotifier.class.getName(), managerNotifier, false);
    managerNotifier.start();
    MockTransport transport = new MockTransport(B);
    gbcr.replaceComponent(Transport.class.getName(), transport, false);
    PersistentUUIDManager persistentUUIDManager = new PersistentUUIDManagerImpl();
    gbcr.replaceComponent(PersistentUUIDManager.class.getName(), persistentUUIDManager, false);
    gbcr.replaceComponent(KnownComponentNames.NON_BLOCKING_EXECUTOR, executor, false);
    gbcr.replaceComponent(KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR, scheduledExecutor, false);
    MockLocalTopologyManager ltm = new MockLocalTopologyManager(CACHE_NAME);
    gbcr.replaceComponent(LocalTopologyManager.class.getName(), ltm, false);
    // Initial conditions (rebalance in phase 3, READ_NEW_WRITE_ALL)
    transport.init(2, asList(A, B));
    ConsistentHash stableCH = replicatedChf.create(joinInfoA.getNumOwners(), joinInfoA.getNumSegments(), singletonList(A), null);
    ConsistentHash pendingCH = replicatedChf.create(joinInfoA.getNumOwners(), joinInfoA.getNumSegments(), asList(A, B), null);
    CacheTopology initialTopology = new CacheTopology(4, 2, stableCH, pendingCH, CacheTopology.Phase.READ_NEW_WRITE_ALL, asList(A, B), asList(joinInfoA.getPersistentUUID(), joinInfoB.getPersistentUUID()));
    CacheTopology stableTopology = new CacheTopology(1, 1, stableCH, null, CacheTopology.Phase.NO_REBALANCE, singletonList(A), singletonList(joinInfoA.getPersistentUUID()));
    ltm.init(joinInfoA, initialTopology, stableTopology, AvailabilityMode.AVAILABLE);
    // Normally LocalTopologyManagerImpl.start()/doHandleTopologyUpdate() registers the persistent UUIDs
    // TODO Write test with asymmetric caches leaving the PersistentUUIDManager cache incomplete
    persistentUUIDManager.addPersistentAddressMapping(A, joinInfoA.getPersistentUUID());
    persistentUUIDManager.addPersistentAddressMapping(B, joinInfoB.getPersistentUUID());
    // Component under test: ClusterTopologyManagerImpl on the new coordinator (B)
    ClusterTopologyManagerImpl ctm = new ClusterTopologyManagerImpl();
    gbcr.replaceComponent(ClusterTopologyManager.class.getName(), ctm, false);
    gcr.rewire();
    // When CTMI starts as regular member it requests the rebalancing status from the coordinator
    runConcurrently(ctm::start, () -> transport.expectCommand(RebalanceStatusRequestCommand.class).singleResponse(A, SuccessfulResponse.create(true)));
    // Wait for the initial view update in CTMI to finish
    eventuallyEquals(ClusterTopologyManager.ClusterManagerStatus.REGULAR_MEMBER, ctm::getStatus);
    // The coordinator (node A) leaves the cluster
    transport.updateView(3, singletonList(B));
    managerNotifier.notifyViewChange(singletonList(B), asList(A, B), B, 3);
    // Node B becomes coordinator and CTMI tries to recover the cluster status
    transport.expectCommand(CacheStatusRequestCommand.class).finish();
    // CTMI gets a single cache topology with READ_NEW and broadcasts a new topology with only the read CH
    ltm.expectTopology(5, asList(A, B), null, CacheTopology.Phase.NO_REBALANCE);
    transport.expectCommand(TopologyUpdateCommand.class, c -> {
        assertEquals(5, c.getTopologyId());
        assertCHMembers(c.getCurrentCH(), A, B);
        assertNull(c.getPendingCH());
    });
    transport.expectCommand(TopologyUpdateStableCommand.class, c -> {
        assertEquals(1, c.getTopologyId());
        assertCHMembers(c.getCurrentCH(), A);
        assertNull(c.getPendingCH());
    });
    // CTMI broadcasts a new cache topology with only node B
    ltm.expectTopology(6, singletonList(B), null, CacheTopology.Phase.NO_REBALANCE);
    transport.expectCommand(TopologyUpdateCommand.class, c -> {
        assertEquals(6, c.getTopologyId());
        assertCHMembers(c.getCurrentCH(), B);
        assertNull(c.getPendingCH());
    });
    // The new topology doesn't need rebalancing, so CTMI updates the stable topology
    transport.expectCommand(TopologyUpdateStableCommand.class, c -> {
        assertEquals(6, c.getTopologyId());
        assertCHMembers(c.getCurrentCH(), B);
        assertNull(c.getPendingCH());
    });
    // Shouldn't send any more commands here
    Thread.sleep(1);
    transport.verifyNoErrors();
    // Node A restarts
    transport.updateView(4, asList(B, A));
    managerNotifier.notifyViewChange(asList(B, A), singletonList(B), A, 4);
    // CTMI confirms members are available in case it needs to starts a rebalance
    transport.expectHeartBeatCommand().finish();
    // Node A rejoins
    ctm.handleJoin(CACHE_NAME, A, joinInfoA, 4);
    verifyRebalance(transport, ltm, ctm, 7, 4, singletonList(B), asList(B, A));
    transport.verifyNoErrors();
    gcr.stop();
}
Also used : ConsistentHash(org.infinispan.distribution.ch.ConsistentHash) GlobalConfiguration(org.infinispan.configuration.global.GlobalConfiguration) CacheManagerNotifier(org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier) GlobalComponentRegistry(org.infinispan.factories.GlobalComponentRegistry) EmbeddedCacheManager(org.infinispan.manager.EmbeddedCacheManager) CacheManagerNotifierImpl(org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifierImpl) BasicComponentRegistry(org.infinispan.factories.impl.BasicComponentRegistry) MockTransport(org.infinispan.remoting.transport.MockTransport) CacheStatusRequestCommand(org.infinispan.commands.topology.CacheStatusRequestCommand) MockTransport(org.infinispan.remoting.transport.MockTransport) Transport(org.infinispan.remoting.transport.Transport) ConfigurationManager(org.infinispan.configuration.ConfigurationManager)

Example 22 with GlobalComponentRegistry

use of org.infinispan.factories.GlobalComponentRegistry in project infinispan by infinispan.

the class PersistenceMockUtil method mockCache.

private static Cache mockCache(String nodeName, Configuration configuration, TimeService timeService, ClassAllowList allowList, ScheduledExecutorService timeoutScheduledExecutor) {
    String cacheName = "mock-cache";
    AdvancedCache cache = mock(AdvancedCache.class, RETURNS_DEEP_STUBS);
    GlobalConfiguration gc = new GlobalConfigurationBuilder().transport().nodeName(nodeName).build();
    Set<String> cachesSet = new HashSet<>();
    EmbeddedCacheManager cm = mock(EmbeddedCacheManager.class);
    when(cm.getCacheManagerConfiguration()).thenReturn(gc);
    when(cm.getClassAllowList()).thenReturn(new ClassAllowList());
    GlobalComponentRegistry gcr = new GlobalComponentRegistry(gc, cm, cachesSet, TestModuleRepository.defaultModuleRepository(), mock(ConfigurationManager.class));
    BasicComponentRegistry gbcr = gcr.getComponent(BasicComponentRegistry.class);
    gbcr.replaceComponent(TimeService.class.getName(), timeService, true);
    gbcr.replaceComponent(KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR, timeoutScheduledExecutor, false);
    ComponentRegistry registry = new ComponentRegistry(cacheName, configuration, cache, gcr, configuration.getClass().getClassLoader());
    when(cache.getCacheManager().getGlobalComponentRegistry()).thenReturn(gcr);
    when(cache.getClassLoader()).thenReturn(PersistenceMockUtil.class.getClassLoader());
    when(cache.getCacheManager().getCacheManagerConfiguration()).thenReturn(gc);
    when(cache.getCacheManager().getClassAllowList()).thenReturn(allowList);
    when(cache.getName()).thenReturn(cacheName);
    when(cache.getAdvancedCache()).thenReturn(cache);
    when(cache.getComponentRegistry()).thenReturn(registry);
    when(cache.getStatus()).thenReturn(ComponentStatus.RUNNING);
    when(cache.getCacheConfiguration()).thenReturn(configuration);
    return cache;
}
Also used : GlobalConfigurationBuilder(org.infinispan.configuration.global.GlobalConfigurationBuilder) GlobalConfiguration(org.infinispan.configuration.global.GlobalConfiguration) TimeService(org.infinispan.commons.time.TimeService) GlobalComponentRegistry(org.infinispan.factories.GlobalComponentRegistry) EmbeddedCacheManager(org.infinispan.manager.EmbeddedCacheManager) BasicComponentRegistry(org.infinispan.factories.impl.BasicComponentRegistry) ComponentRegistry(org.infinispan.factories.ComponentRegistry) BasicComponentRegistry(org.infinispan.factories.impl.BasicComponentRegistry) GlobalComponentRegistry(org.infinispan.factories.GlobalComponentRegistry) ClassAllowList(org.infinispan.commons.configuration.ClassAllowList) AdvancedCache(org.infinispan.AdvancedCache) ConfigurationManager(org.infinispan.configuration.ConfigurationManager) HashSet(java.util.HashSet)

Example 23 with GlobalComponentRegistry

use of org.infinispan.factories.GlobalComponentRegistry in project infinispan by infinispan.

the class StartCacheFromListenerTest method testSingleInvocation.

public void testSingleInvocation() {
    final EmbeddedCacheManager cacheManager = manager(0);
    GlobalComponentRegistry registry = TestingUtil.extractGlobalComponentRegistry(cacheManager);
    List<ModuleLifecycle> lifecycles = new LinkedList<>();
    TestingUtil.replaceField(lifecycles, "moduleLifecycles", registry, GlobalComponentRegistry.class);
    lifecycles.add(new ModuleLifecycle() {

        @Override
        public void cacheStarting(ComponentRegistry cr, Configuration configuration, String cacheName) {
            log.debug("StartCacheFromListenerTest.cacheStarting");
            if (!cacheStartingInvoked.get()) {
                cacheStartingInvoked.set(true);
                Future<Cache> fork = fork(() -> {
                    try {
                        return cacheManager.getCache("cacheStarting");
                    } catch (Exception e) {
                        log.error("Got", e);
                        throw e;
                    }
                });
                try {
                    log.debug("About to wait in get");
                    Cache cache = fork.get();
                    cache.put("k", "v");
                    log.debug("returned from get!");
                } catch (InterruptedException e) {
                    log.error("Interrupted while waiting for the cache to start");
                } catch (ExecutionException e) {
                    log.error("Failed to start cache", e);
                }
            }
        }
    });
    log.debug("StartCacheFromListenerTest.testSingleInvocation1");
    Cache<Object, Object> some = cacheManager.getCache("some");
    log.debug("StartCacheFromListenerTest.testSingleInvocation2");
    some.put("k", "v");
    assertEquals("v", cacheManager.getCache("cacheStarting").get("k"));
}
Also used : Configuration(org.infinispan.configuration.cache.Configuration) GlobalComponentRegistry(org.infinispan.factories.GlobalComponentRegistry) EmbeddedCacheManager(org.infinispan.manager.EmbeddedCacheManager) LinkedList(java.util.LinkedList) ExecutionException(java.util.concurrent.ExecutionException) ModuleLifecycle(org.infinispan.lifecycle.ModuleLifecycle) GlobalComponentRegistry(org.infinispan.factories.GlobalComponentRegistry) ComponentRegistry(org.infinispan.factories.ComponentRegistry) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException) Cache(org.infinispan.Cache)

Example 24 with GlobalComponentRegistry

use of org.infinispan.factories.GlobalComponentRegistry in project infinispan by infinispan.

the class CountingRequestRepository method replaceDispatcher.

public static CountingRequestRepository replaceDispatcher(EmbeddedCacheManager cacheManager) {
    GlobalComponentRegistry gcr = cacheManager.getGlobalComponentRegistry();
    JGroupsTransport transport = (JGroupsTransport) gcr.getComponent(Transport.class);
    RequestRepository requestRepository = (RequestRepository) TestingUtil.extractField(JGroupsTransport.class, transport, "requests");
    CountingRequestRepository instance = new CountingRequestRepository(requestRepository);
    TestingUtil.replaceField(instance, "requests", transport, JGroupsTransport.class);
    return instance;
}
Also used : JGroupsTransport(org.infinispan.remoting.transport.jgroups.JGroupsTransport) GlobalComponentRegistry(org.infinispan.factories.GlobalComponentRegistry) Transport(org.infinispan.remoting.transport.Transport) JGroupsTransport(org.infinispan.remoting.transport.jgroups.JGroupsTransport) RequestRepository(org.infinispan.remoting.transport.impl.RequestRepository)

Example 25 with GlobalComponentRegistry

use of org.infinispan.factories.GlobalComponentRegistry in project infinispan by infinispan.

the class BackupWriter method createBackup.

/**
 * Create a backup of the specified container.
 *
 * @param containerName the name of container to backup.
 * @param cm            the container to backup.
 * @param params        the {@link BackupManager.Resources} object that determines what resources are included in the
 *                      backup for this container.
 * @return a {@link CompletionStage} that completes once the backup has finished.
 */
private CompletionStage<Void> createBackup(String containerName, EmbeddedCacheManager cm, BackupManager.Resources params) {
    Path containerRoot = rootDir.resolve(CONTAINER_KEY).resolve(containerName);
    try {
        Files.createDirectories(containerRoot);
    } catch (IOException e) {
        throw new CacheException("Unable to create directories " + containerRoot);
    }
    GlobalComponentRegistry gcr = SecurityActions.getGlobalComponentRegistry(cm);
    BlockingManager blockingManager = gcr.getComponent(BlockingManager.class);
    Collection<ContainerResource> resources = ContainerResourceFactory.getResources(params, blockingManager, cm, gcr, parserRegistry, containerRoot);
    CompletionStage<Void> prepareStage = blockingManager.runBlocking(() -> {
        // Prepare and ensure all requested resources are valid before starting the backup process
        resources.forEach(ContainerResource::prepareAndValidateBackup);
    }, "backupWriter - prepare");
    return prepareStage.thenCompose(ignore -> {
        AggregateCompletionStage<Void> stages = CompletionStages.aggregateCompletionStage();
        for (ContainerResource cr : resources) stages.dependsOn(cr.backup());
        stages.dependsOn(// Write the global configuration xml
        blockingManager.runBlocking(() -> writeGlobalConfig(SecurityActions.getGlobalConfiguration(cm), containerRoot), "backupWriter - writeGlobalConfig"));
        return blockingManager.thenRunBlocking(stages.freeze(), () -> {
            Properties manifest = new Properties();
            resources.forEach(r -> r.writeToManifest(manifest));
            storeProperties(manifest, "Container Properties", containerRoot.resolve(CONTAINERS_PROPERTIES_FILE));
        }, "backupWriter - createManifest");
    });
}
Also used : Path(java.nio.file.Path) CacheException(org.infinispan.commons.CacheException) BlockingManager(org.infinispan.util.concurrent.BlockingManager) IOException(java.io.IOException) GlobalComponentRegistry(org.infinispan.factories.GlobalComponentRegistry) Properties(java.util.Properties)

Aggregations

GlobalComponentRegistry (org.infinispan.factories.GlobalComponentRegistry)26 GlobalConfiguration (org.infinispan.configuration.global.GlobalConfiguration)7 ComponentRegistry (org.infinispan.factories.ComponentRegistry)7 BasicComponentRegistry (org.infinispan.factories.impl.BasicComponentRegistry)7 EmbeddedCacheManager (org.infinispan.manager.EmbeddedCacheManager)7 ConfigurationManager (org.infinispan.configuration.ConfigurationManager)5 Cache (org.infinispan.Cache)4 CacheException (org.infinispan.commons.CacheException)4 ConfigurationBuilder (org.infinispan.configuration.cache.ConfigurationBuilder)4 Transport (org.infinispan.remoting.transport.Transport)4 CacheMode (org.infinispan.configuration.cache.CacheMode)3 Configuration (org.infinispan.configuration.cache.Configuration)3 GlobalConfigurationBuilder (org.infinispan.configuration.global.GlobalConfigurationBuilder)3 ModuleLifecycle (org.infinispan.lifecycle.ModuleLifecycle)3 JGroupsTransport (org.infinispan.remoting.transport.jgroups.JGroupsTransport)3 Path (java.nio.file.Path)2 HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 Properties (java.util.Properties)2 AdvancedCache (org.infinispan.AdvancedCache)2