예제 #1
0
  private void shutDownGracefully() {
    if (log.isDebugEnabled())
      log.debugf(
          "Wait for on-going transactions to finish for %s.",
          Util.prettyPrintTime(
              configuration.transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS));
    long failTime = currentMillisFromNanotime() + configuration.transaction().cacheStopTimeout();
    boolean txsOnGoing = areTxsOnGoing();
    while (txsOnGoing && currentMillisFromNanotime() < failTime) {
      try {
        Thread.sleep(30);
        txsOnGoing = areTxsOnGoing();
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        if (clustered) {
          log.debugf(
              "Interrupted waiting for on-going transactions to finish. %s local transactions and %s remote transactions",
              localTransactions.size(), remoteTransactions.size());
        } else {
          log.debugf(
              "Interrupted waiting for %s on-going transactions to finish.",
              localTransactions.size());
        }
      }
    }

    if (txsOnGoing) {
      log.unfinishedTransactionsRemain(
          localTransactions == null ? 0 : localTransactions.size(),
          remoteTransactions == null ? 0 : remoteTransactions.size());
    } else {
      log.debug("All transactions terminated");
    }
  }
예제 #2
0
  public void cleanupTimedOutTransactions() {
    if (trace)
      log.tracef(
          "About to cleanup remote transactions older than %d ms",
          configuration.transaction().completedTxTimeout());
    long beginning = timeService.time();
    long cutoffCreationTime =
        beginning - TimeUnit.MILLISECONDS.toNanos(configuration.transaction().completedTxTimeout());
    List<GlobalTransaction> toKill = new ArrayList<>();

    // Check remote transactions.
    for (Map.Entry<GlobalTransaction, RemoteTransaction> e : remoteTransactions.entrySet()) {
      GlobalTransaction gtx = e.getKey();
      RemoteTransaction remoteTx = e.getValue();
      if (remoteTx != null) {
        if (trace) log.tracef("Checking transaction %s", gtx);
        // Check the time.
        if (remoteTx.getCreationTime() - cutoffCreationTime < 0) {
          long duration =
              timeService.timeDuration(
                  remoteTx.getCreationTime(), beginning, TimeUnit.MILLISECONDS);
          log.remoteTransactionTimeout(gtx, duration);
          toKill.add(gtx);
        }
      }
    }

    // Rollback the orphaned transactions and release any held locks.
    for (GlobalTransaction gtx : toKill) {
      killTransaction(gtx);
    }
  }
예제 #3
0
 /** Removes the {@link RemoteTransaction} corresponding to the given tx. */
 public void remoteTransactionCommitted(GlobalTransaction gtx, boolean onePc) {
   boolean optimisticWih1Pc =
       onePc && (configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC);
   if (Configurations.isSecondPhaseAsync(configuration)
       || configuration.transaction().transactionProtocol().isTotalOrder()
       || optimisticWih1Pc) {
     removeRemoteTransaction(gtx);
   }
 }
예제 #4
0
  ServiceController<?> installCacheConfigurationService(
      ServiceTarget target,
      String containerName,
      String cacheName,
      String defaultCache,
      ModuleIdentifier moduleId,
      ConfigurationBuilder builder,
      Configuration config,
      List<Dependency<?>> dependencies,
      ServiceVerificationHandler verificationHandler) {

    final InjectedValue<EmbeddedCacheManager> container = new InjectedValue<EmbeddedCacheManager>();
    final CacheConfigurationDependencies cacheConfigurationDependencies =
        new CacheConfigurationDependencies(container);
    final Service<Configuration> service =
        new CacheConfigurationService(cacheName, builder, moduleId, cacheConfigurationDependencies);
    final ServiceBuilder<?> configBuilder =
        target
            .addService(CacheConfigurationService.getServiceName(containerName, cacheName), service)
            .addDependency(
                EmbeddedCacheManagerService.getServiceName(containerName),
                EmbeddedCacheManager.class,
                container)
            .addDependency(
                Services.JBOSS_SERVICE_MODULE_LOADER,
                ModuleLoader.class,
                cacheConfigurationDependencies.getModuleLoaderInjector())
            .setInitialMode(ServiceController.Mode.PASSIVE);
    if (config.invocationBatching().enabled()) {
      cacheConfigurationDependencies
          .getTransactionManagerInjector()
          .inject(BatchModeTransactionManager.getInstance());
    } else if (config.transaction().transactionMode()
        == org.infinispan.transaction.TransactionMode.TRANSACTIONAL) {
      configBuilder.addDependency(
          TxnServices.JBOSS_TXN_TRANSACTION_MANAGER,
          TransactionManager.class,
          cacheConfigurationDependencies.getTransactionManagerInjector());
      if (config.transaction().useSynchronization()) {
        configBuilder.addDependency(
            TxnServices.JBOSS_TXN_SYNCHRONIZATION_REGISTRY,
            TransactionSynchronizationRegistry.class,
            cacheConfigurationDependencies.getTransactionSynchronizationRegistryInjector());
      }
    }

    // add in any additional dependencies resulting from ModelNode parsing
    for (Dependency<?> dependency : dependencies) {
      this.addDependency(configBuilder, dependency);
    }
    // add an alias for the default cache
    if (cacheName.equals(defaultCache)) {
      configBuilder.addAliases(CacheConfigurationService.getServiceName(containerName, null));
    }
    return configBuilder.install();
  }
예제 #5
0
 public void testNoRecovery() {
   Configuration noRecovery = cacheManager.getCache("noRecovery").getCacheConfiguration();
   assertFalse(
       noRecovery.transaction().recovery().enabled(), "Recovery is supposed to be disabled");
   assertNull(
       rm(cacheManager.getCache("noRecovery")),
       "RecoveryManager should be null when recovery is disabled");
   assertEquals(
       noRecovery.transaction().recovery().recoveryInfoCacheName(),
       "someName",
       "Wrong recovery cache name.");
 }
예제 #6
0
  public void cleanupCompletedTransactions() {
    if (!completedTransactions.isEmpty()) {
      try {
        log.tracef(
            "About to cleanup completed transaction. Initial size is %d",
            completedTransactions.size());
        // this iterator is weekly consistent and will never throw ConcurrentModificationException
        Iterator<Map.Entry<GlobalTransaction, Long>> iterator =
            completedTransactions.entrySet().iterator();
        long timeout = configuration.transaction().completedTxTimeout();

        int removedEntries = 0;
        long beginning = timeService.time();
        while (iterator.hasNext()) {
          Map.Entry<GlobalTransaction, Long> e = iterator.next();
          long ageMillis = timeService.timeDuration(e.getValue(), TimeUnit.MILLISECONDS);
          if (ageMillis >= timeout) {
            iterator.remove();
            removedEntries++;
          }
        }
        long duration = timeService.timeDuration(beginning, TimeUnit.MILLISECONDS);

        log.tracef(
            "Finished cleaning up completed transactions. %d transactions were removed, total duration was %d millis, "
                + "current number of completed transactions is %d",
            removedEntries, duration, completedTransactions.size());
      } catch (Exception e) {
        log.errorf(e, "Failed to cleanup completed transactions: %s", e.getMessage());
      }
    }
  }
예제 #7
0
 private void writeTransaction(XMLExtendedStreamWriter writer, Configuration configuration)
     throws XMLStreamException {
   TransactionConfiguration transaction = configuration.transaction();
   AttributeSet attributes = transaction.attributes();
   if (attributes.isModified()) {
     writer.writeStartElement(Element.TRANSACTION);
     TransactionMode mode =
         TransactionMode.fromConfiguration(
             transaction.transactionMode(),
             !transaction.useSynchronization(),
             transaction.recovery().enabled(),
             configuration.invocationBatching().enabled());
     writer.writeAttribute(Attribute.MODE, mode.toString());
     attributes.write(writer);
     if (mode != TransactionMode.NONE) {
       attributes.write(writer, TransactionConfiguration.TRANSACTION_MANAGER_LOOKUP);
     }
     if (transaction.recovery().enabled())
       transaction
           .recovery()
           .attributes()
           .write(
               writer,
               RecoveryConfiguration.RECOVERY_INFO_CACHE_NAME,
               Attribute.RECOVERY_INFO_CACHE_NAME);
     writer.writeEndElement();
   }
 }
예제 #8
0
  @Start(priority = 9) // Start before cache loader manager
  @SuppressWarnings("unused")
  private void start() {
    final int concurrencyLevel = configuration.locking().concurrencyLevel();
    localTransactions =
        CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel);
    globalToLocalTransactions =
        CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel);
    if (configuration.clustering().cacheMode().isClustered()) {
      minTopologyRecalculationLock = new ReentrantLock();
      // Only initialize this if we are clustered.
      remoteTransactions =
          CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel);
      notifier.addListener(this);
      clustered = true;
    }

    totalOrder = configuration.transaction().transactionProtocol().isTotalOrder();
    if (!totalOrder) {
      // Periodically run a task to cleanup the transaction table from completed transactions.
      ThreadFactory tf =
          new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
              String address =
                  rpcManager != null ? rpcManager.getTransport().getAddress().toString() : "local";
              Thread th = new Thread(r, "TxCleanupService," + cacheName + "," + address);
              th.setDaemon(true);
              return th;
            }
          };

      executorService = Executors.newSingleThreadScheduledExecutor(tf);

      long interval = configuration.transaction().reaperWakeUpInterval();
      executorService.scheduleAtFixedRate(
          new Runnable() {
            @Override
            public void run() {
              cleanupCompletedTransactions();
            }
          },
          interval,
          interval,
          TimeUnit.MILLISECONDS);
    }
  }
  @Inject
  public void init(
      StateTransferLock stateTransferLock,
      Configuration configuration,
      CommandsFactory commandFactory,
      StateTransferManager stateTransferManager) {
    this.stateTransferLock = stateTransferLock;
    this.commandFactory = commandFactory;
    this.stateTransferManager = stateTransferManager;

    useVersioning =
        configuration.transaction().transactionMode().isTransactional()
            && configuration.locking().writeSkewCheck()
            && configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC
            && configuration.versioning().enabled();
    transactionDataTimeout = configuration.clustering().sync().replTimeout();
  }
예제 #10
0
 public void testRecoveryWithCacheConfigured() {
   Configuration withRecoveryAndCache =
       cacheManager.getCache("withRecoveryAndCache").getCacheConfiguration();
   assertTrue(
       withRecoveryAndCache.transaction().recovery().enabled(),
       "Recovery is supposed to be enabled.");
   assertEquals(
       withRecoveryAndCache.transaction().recovery().recoveryInfoCacheName(),
       "noRecovery",
       "Wrong recovery cache name.");
   RecoveryManagerImpl recoveryManager = rm(cacheManager.getCache("withRecoveryAndCache"));
   assertNotNull(
       recoveryManager, "RecoveryManager should be *not* null when recovery is enabled.");
   Cache<RecoveryInfoKey, RecoveryAwareRemoteTransaction> preparedTransactions =
       (Cache<RecoveryInfoKey, RecoveryAwareRemoteTransaction>)
           recoveryManager.getInDoubtTransactionsMap();
   assertEquals(preparedTransactions.getName(), "noRecovery", "Wrong recovery cache name.");
 }
예제 #11
0
  @Inject
  public void init(
      Cache cache,
      @ComponentName(ASYNC_TRANSPORT_EXECUTOR)
          ExecutorService executorService, // TODO Use a dedicated ExecutorService
      StateTransferManager stateTransferManager,
      InterceptorChain interceptorChain,
      InvocationContextContainer icc,
      Configuration configuration,
      RpcManager rpcManager,
      TransactionManager transactionManager,
      CommandsFactory commandsFactory,
      CacheLoaderManager cacheLoaderManager,
      DataContainer dataContainer,
      TransactionTable transactionTable,
      StateTransferLock stateTransferLock) {
    this.cacheName = cache.getName();
    this.executorService = executorService;
    this.stateTransferManager = stateTransferManager;
    this.interceptorChain = interceptorChain;
    this.icc = icc;
    this.configuration = configuration;
    this.rpcManager = rpcManager;
    this.transactionManager = transactionManager;
    this.commandsFactory = commandsFactory;
    this.cacheLoaderManager = cacheLoaderManager;
    this.dataContainer = dataContainer;
    this.transactionTable = transactionTable;
    this.stateTransferLock = stateTransferLock;

    isTransactional = configuration.transaction().transactionMode().isTransactional();

    // we need to use a special form of PutKeyValueCommand that can apply versions too
    useVersionedPut =
        isTransactional
            && configuration.versioning().enabled()
            && configuration.locking().writeSkewCheck()
            && configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC
            && configuration.clustering().cacheMode().isClustered();

    timeout = configuration.clustering().stateTransfer().timeout();
  }
 @Test
 public void testDistSyncAutoCommit() {
   Configuration configuration =
       new ConfigurationBuilder()
           .clustering()
           .cacheMode(CacheMode.DIST_SYNC)
           .transaction()
           .autoCommit(true)
           .build();
   Assert.assertTrue(configuration.transaction().autoCommit());
   Assert.assertEquals(configuration.clustering().cacheMode(), CacheMode.DIST_SYNC);
 }
 public AbstractEnlistmentAdapter(
     CommandsFactory commandsFactory,
     RpcManager rpcManager,
     TransactionTable txTable,
     ClusteringDependentLogic clusteringLogic,
     Configuration configuration) {
   this.commandsFactory = commandsFactory;
   this.rpcManager = rpcManager;
   this.txTable = txTable;
   this.clusteringLogic = clusteringLogic;
   this.isSecondPhaseAsync = Configurations.isSecondPhaseAsync(configuration);
   this.isPessimisticLocking =
       configuration.transaction().lockingMode() == LockingMode.PESSIMISTIC;
   hashCode = 31;
 }
예제 #14
0
  private void createQueryInterceptorIfNeeded(
      ComponentRegistry cr, Configuration cfg, SearchFactoryIntegrator searchFactory) {
    QueryInterceptor queryInterceptor = cr.getComponent(QueryInterceptor.class);
    if (queryInterceptor == null) {
      queryInterceptor = buildQueryInterceptor(cfg, searchFactory);

      // Interceptor registration not needed, core configuration handling
      // already does it for all custom interceptors - UNLESS the InterceptorChain already exists in
      // the component registry!
      InterceptorChain ic = cr.getComponent(InterceptorChain.class);

      ConfigurationBuilder builder = new ConfigurationBuilder().read(cfg);
      InterceptorConfigurationBuilder interceptorBuilder =
          builder.customInterceptors().addInterceptor();
      interceptorBuilder.interceptor(queryInterceptor);

      if (!cfg.transaction().transactionMode().isTransactional()) {
        if (ic != null)
          ic.addInterceptorAfter(queryInterceptor, NonTransactionalLockingInterceptor.class);
        interceptorBuilder.after(NonTransactionalLockingInterceptor.class);
      } else if (cfg.transaction().lockingMode() == LockingMode.OPTIMISTIC) {
        if (ic != null)
          ic.addInterceptorAfter(queryInterceptor, OptimisticLockingInterceptor.class);
        interceptorBuilder.after(OptimisticLockingInterceptor.class);
      } else {
        if (ic != null)
          ic.addInterceptorAfter(queryInterceptor, PessimisticLockingInterceptor.class);
        interceptorBuilder.after(PessimisticLockingInterceptor.class);
      }
      if (ic != null) {
        cr.registerComponent(queryInterceptor, QueryInterceptor.class);
        cr.registerComponent(queryInterceptor, queryInterceptor.getClass().getName(), true);
      }
      cfg.customInterceptors().interceptors(builder.build().customInterceptors().interceptors());
    }
  }
예제 #15
0
  ServiceController<?> installCacheService(
      ServiceTarget target,
      String containerName,
      String cacheName,
      String defaultCache,
      ServiceController.Mode initialMode,
      Configuration config,
      ServiceVerificationHandler verificationHandler) {

    final InjectedValue<EmbeddedCacheManager> container = new InjectedValue<EmbeddedCacheManager>();
    final CacheDependencies cacheDependencies = new CacheDependencies(container);
    final Service<Cache<Object, Object>> service =
        new CacheService<Object, Object>(cacheName, cacheDependencies);
    final ServiceBuilder<?> builder =
        AsynchronousService.addService(
                target, CacheService.getServiceName(containerName, cacheName), service)
            .addDependency(CacheConfigurationService.getServiceName(containerName, cacheName))
            .addDependency(
                EmbeddedCacheManagerService.getServiceName(containerName),
                EmbeddedCacheManager.class,
                container)
            .addDependency(
                config.clustering().cacheMode().isClustered()
                    ? DependencyType.REQUIRED
                    : DependencyType.OPTIONAL,
                ChannelService.getServiceName(containerName))
            .setInitialMode(initialMode);
    if (config.transaction().recovery().enabled()) {
      builder.addDependency(
          TxnServices.JBOSS_TXN_ARJUNA_RECOVERY_MANAGER,
          XAResourceRecoveryRegistry.class,
          cacheDependencies.getRecoveryRegistryInjector());
    }

    // add an alias for the default cache
    if (cacheName.equals(defaultCache)) {
      builder.addAliases(CacheService.getServiceName(containerName, null));
    }

    if (initialMode == ServiceController.Mode.ACTIVE) {
      builder.addListener(verificationHandler);
    }

    return builder.install();
  }
 @Inject
 public void init(
     DataContainer<Object, Object> dataContainer,
     CacheNotifier<Object, Object> notifier,
     Configuration configuration,
     CommitManager commitManager,
     PersistenceManager persistenceManager,
     TimeService timeService,
     FunctionalNotifier<Object, Object> functionalNotifier) {
   this.dataContainer = dataContainer;
   this.notifier = notifier;
   this.totalOrder = configuration.transaction().transactionProtocol().isTotalOrder();
   this.keySpecificLogic = initKeySpecificLogic(totalOrder);
   this.commitManager = commitManager;
   this.persistenceManager = persistenceManager;
   this.timeService = timeService;
   this.functionalNotifier = functionalNotifier;
 }
 @Test
 public void testBuildImmutableEntityRegion() {
   AdvancedCache cache;
   Properties p = new Properties();
   InfinispanRegionFactory factory = createRegionFactory(p);
   try {
     factory.getCacheManager();
     EntityRegionImpl region =
         (EntityRegionImpl)
             factory.buildEntityRegion("com.acme.Address", p, IMMUTABLE_NON_VERSIONED);
     assertNull(factory.getTypeOverrides().get("com.acme.Address"));
     cache = region.getCache();
     Configuration cacheCfg = cache.getCacheConfiguration();
     assertEquals(
         "Immutable entity should get non-transactional cache",
         TransactionMode.NON_TRANSACTIONAL,
         cacheCfg.transaction().transactionMode());
   } finally {
     factory.stop();
   }
 }
 @Override
 public <L> SSOManager<A, D, L, TransactionBatch> createSSOManager(
     IdentifierFactory<String> identifierFactory, LocalContextFactory<L> localContextFactory) {
   MarshallingContext marshallingContext =
       new SimpleMarshallingContextFactory()
           .createMarshallingContext(
               new SimpleMarshallingConfigurationRepository(
                   MarshallingVersion.class,
                   MarshallingVersion.CURRENT,
                   this.configuration.getModuleLoader()),
               null);
   MarshalledValueFactory<MarshallingContext> marshalledValueFactory =
       new SimpleMarshalledValueFactory(marshallingContext);
   Marshaller<A, MarshalledValue<A, MarshallingContext>, MarshallingContext> marshaller =
       new MarshalledValueMarshaller<>(marshalledValueFactory, marshallingContext);
   Cache<Key<String>, ?> cache = this.configuration.getCache();
   Configuration config = cache.getCacheConfiguration();
   boolean lockOnRead =
       cache.getCacheConfiguration().transaction().transactionMode().isTransactional()
           && (config.transaction().lockingMode() == LockingMode.PESSIMISTIC)
           && config.locking().isolationLevel() == IsolationLevel.REPEATABLE_READ;
   SessionsFactory<Map<D, String>, D> sessionsFactory =
       new CoarseSessionsFactory<>(this.configuration.getCache());
   SSOFactory<Map.Entry<A, AtomicReference<L>>, Map<D, String>, A, D, L> factory =
       new InfinispanSSOFactory<>(
           this.configuration.getCache(),
           marshaller,
           localContextFactory,
           sessionsFactory,
           lockOnRead);
   IdentifierFactory<String> idFactory =
       new AffinityIdentifierFactory<>(
           identifierFactory, cache, this.configuration.getKeyAffinityServiceFactory());
   Batcher<TransactionBatch> batcher = new InfinispanBatcher(cache);
   return new InfinispanSSOManager<>(factory, idFactory, batcher);
 }
예제 #19
0
  private void assertNamedCacheFile(EmbeddedCacheManager cm) {
    final GlobalConfiguration gc = cm.getCacheManagerConfiguration();

    assert gc.asyncListenerExecutor().factory() instanceof DefaultExecutorFactory;
    assert gc.asyncListenerExecutor().properties().getProperty("maxThreads").equals("5");
    assert gc.asyncListenerExecutor()
        .properties()
        .getProperty("threadNamePrefix")
        .equals("AsyncListenerThread");

    assert gc.asyncTransportExecutor().factory() instanceof DefaultExecutorFactory;
    assert gc.asyncTransportExecutor().properties().getProperty("maxThreads").equals("25");
    assert gc.asyncTransportExecutor()
        .properties()
        .getProperty("threadNamePrefix")
        .equals("AsyncSerializationThread");

    assert gc.evictionScheduledExecutor().factory() instanceof DefaultScheduledExecutorFactory;
    assert gc.evictionScheduledExecutor()
        .properties()
        .getProperty("threadNamePrefix")
        .equals("EvictionThread");

    assert gc.replicationQueueScheduledExecutor().factory()
        instanceof DefaultScheduledExecutorFactory;
    assert gc.replicationQueueScheduledExecutor()
        .properties()
        .getProperty("threadNamePrefix")
        .equals("ReplicationQueueThread");

    assert gc.transport().transport() instanceof JGroupsTransport;
    assert gc.transport().clusterName().equals("infinispan-cluster");
    assert gc.transport().nodeName().equals("Jalapeno");
    assert gc.transport().distributedSyncTimeout() == 50000;

    assert gc.shutdown().hookBehavior().equals(ShutdownHookBehavior.REGISTER);

    assert gc.serialization().marshaller() instanceof VersionAwareMarshaller;
    assert gc.serialization().version() == Version.getVersionShort("1.0");
    final Map<Integer, AdvancedExternalizer<?>> externalizers =
        gc.serialization().advancedExternalizers();
    assert externalizers.size() == 3;
    assert externalizers.get(1234) instanceof AdvancedExternalizerTest.IdViaConfigObj.Externalizer;
    assert externalizers.get(5678)
        instanceof AdvancedExternalizerTest.IdViaAnnotationObj.Externalizer;
    assert externalizers.get(3456) instanceof AdvancedExternalizerTest.IdViaBothObj.Externalizer;

    Configuration defaultCfg = cm.getDefaultCacheConfiguration();

    assert defaultCfg.locking().lockAcquisitionTimeout() == 1000;
    assert defaultCfg.locking().concurrencyLevel() == 100;
    assert defaultCfg.locking().isolationLevel() == IsolationLevel.READ_COMMITTED;

    Configuration c = cm.getCacheConfiguration("transactional");
    assert !c.clustering().cacheMode().isClustered();
    assert c.transaction().transactionManagerLookup() instanceof GenericTransactionManagerLookup;
    assert c.transaction().useEagerLocking();
    assert c.transaction().eagerLockingSingleNode();
    assert !c.transaction().syncRollbackPhase();

    c = cm.getCacheConfiguration("transactional2");
    assert c.transaction().transactionManagerLookup() instanceof Lookup;
    assert c.transaction().cacheStopTimeout() == 10000;
    assert c.transaction().lockingMode().equals(LockingMode.PESSIMISTIC);
    assert !c.transaction().autoCommit();

    c = cm.getCacheConfiguration("syncRepl");

    assert c.clustering().cacheMode() == CacheMode.REPL_SYNC;
    assert !c.clustering().stateRetrieval().fetchInMemoryState();
    assert c.clustering().sync().replTimeout() == 15000;

    c = cm.getCacheConfiguration("asyncRepl");

    assert c.clustering().cacheMode() == CacheMode.REPL_ASYNC;
    assert !c.clustering().async().useReplQueue();
    assert !c.clustering().async().asyncMarshalling();
    assert !c.clustering().stateRetrieval().fetchInMemoryState();

    c = cm.getCacheConfiguration("asyncReplQueue");

    assert c.clustering().cacheMode() == CacheMode.REPL_ASYNC;
    assert c.clustering().async().useReplQueue();
    assert !c.clustering().async().asyncMarshalling();
    assert !c.clustering().stateRetrieval().fetchInMemoryState();

    c = cm.getCacheConfiguration("txSyncRepl");

    assert c.transaction().transactionManagerLookup() instanceof GenericTransactionManagerLookup;
    assert c.clustering().cacheMode() == CacheMode.REPL_SYNC;
    assert !c.clustering().stateRetrieval().fetchInMemoryState();
    assert c.clustering().sync().replTimeout() == 15000;

    c = cm.getCacheConfiguration("overriding");

    assert c.clustering().cacheMode() == CacheMode.LOCAL;
    assert c.locking().lockAcquisitionTimeout() == 20000;
    assert c.locking().concurrencyLevel() == 1000;
    assert c.locking().isolationLevel() == IsolationLevel.REPEATABLE_READ;
    assert !c.storeAsBinary().enabled();

    c = cm.getCacheConfiguration("storeAsBinary");
    assert c.storeAsBinary().enabled();

    c = cm.getCacheConfiguration("withLoader");
    assert c.loaders().preload();
    assert !c.loaders().passivation();
    assert !c.loaders().shared();
    assert c.loaders().cacheLoaders().size() == 1;

    FileCacheStoreConfiguration loaderCfg =
        (FileCacheStoreConfiguration) c.loaders().cacheLoaders().get(0);

    assert loaderCfg.fetchPersistentState();
    assert loaderCfg.ignoreModifications();
    assert loaderCfg.purgeOnStartup();
    assert loaderCfg.location().equals("/tmp/FileCacheStore-Location");
    assert loaderCfg.fsyncMode() == FileCacheStoreConfigurationBuilder.FsyncMode.PERIODIC;
    assert loaderCfg.fsyncInterval() == 2000;
    assert loaderCfg.singletonStore().pushStateTimeout() == 20000;
    assert loaderCfg.singletonStore().pushStateWhenCoordinator();
    assert loaderCfg.async().threadPoolSize() == 5;
    assert loaderCfg.async().flushLockTimeout() == 15000;
    assert loaderCfg.async().enabled();
    assert loaderCfg.async().modificationQueueSize() == 700;

    c = cm.getCacheConfiguration("withLoaderDefaults");
    loaderCfg = (FileCacheStoreConfiguration) c.loaders().cacheLoaders().get(0);
    assert loaderCfg.location().equals("/tmp/Another-FileCacheStore-Location");
    assert loaderCfg.fsyncMode() == FileCacheStoreConfigurationBuilder.FsyncMode.DEFAULT;

    c = cm.getCacheConfiguration("withouthJmxEnabled");
    assert !c.jmxStatistics().enabled();
    assert gc.globalJmxStatistics().enabled();
    assert gc.globalJmxStatistics().allowDuplicateDomains();
    assert gc.globalJmxStatistics().domain().equals("funky_domain");
    assert gc.globalJmxStatistics().mbeanServerLookup() instanceof PerThreadMBeanServerLookup;

    c = cm.getCacheConfiguration("dist");
    assert c.clustering().cacheMode() == CacheMode.DIST_SYNC;
    assert c.clustering().l1().lifespan() == 600000;
    assert c.clustering().hash().rehashRpcTimeout() == 120000;
    assert c.clustering().stateTransfer().timeout() == 120000;
    assert c.clustering().hash().consistentHash() instanceof TopologyAwareConsistentHash;
    assert c.clustering().hash().numOwners() == 3;
    assert c.clustering().l1().enabled();

    c = cm.getCacheConfiguration("groups");
    assert c.clustering().hash().groups().enabled();
    assert c.clustering().hash().groups().groupers().size() == 1;
    assert c.clustering().hash().groups().groupers().get(0).getKeyType().equals(String.class);

    c = cm.getCacheConfiguration("chunkSize");
    assert c.clustering().stateTransfer().fetchInMemoryState();
    assert c.clustering().stateTransfer().timeout() == 120000;
    assert c.clustering().stateTransfer().chunkSize() == 1000;

    c = cm.getCacheConfiguration("cacheWithCustomInterceptors");
    assert !c.customInterceptors().interceptors().isEmpty();
    assert c.customInterceptors().interceptors().size() == 5;

    c = cm.getCacheConfiguration("evictionCache");
    assert c.eviction().maxEntries() == 5000;
    assert c.eviction().strategy().equals(EvictionStrategy.FIFO);
    assert c.expiration().lifespan() == 60000;
    assert c.expiration().maxIdle() == 1000;
    assert c.eviction().threadPolicy() == EvictionThreadPolicy.PIGGYBACK;
    assert c.expiration().wakeUpInterval() == 500;

    c = cm.getCacheConfiguration("withDeadlockDetection");
    assert c.deadlockDetection().enabled();
    assert c.deadlockDetection().spinDuration() == 1221;
    assert c.clustering().cacheMode() == CacheMode.DIST_SYNC;

    c = cm.getCacheConfiguration("storeKeyValueBinary");
    assert c.storeAsBinary().enabled();
    assert c.storeAsBinary().storeKeysAsBinary();
    assert !c.storeAsBinary().storeValuesAsBinary();
  }
예제 #20
0
  @Start(priority = 9) // Start before cache loader manager
  @SuppressWarnings("unused")
  public void start() {
    final int concurrencyLevel = configuration.locking().concurrencyLevel();
    // use the IdentityEquivalence because some Transaction implementation does not have a stable
    // hash code function
    // and it can cause some leaks in the concurrent map.
    localTransactions =
        CollectionFactory.makeConcurrentMap(
            concurrencyLevel,
            0.75f,
            concurrencyLevel,
            new IdentityEquivalence<Transaction>(),
            AnyEquivalence.getInstance());
    globalToLocalTransactions =
        CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel);

    boolean transactional = configuration.transaction().transactionMode().isTransactional();
    if (clustered && transactional) {
      minTopologyRecalculationLock = new ReentrantLock();
      remoteTransactions =
          CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel);

      ThreadFactory tf =
          new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
              String address =
                  rpcManager != null ? rpcManager.getTransport().getAddress().toString() : "local";
              Thread th = new Thread(r, "TxCleanupService," + cacheName + "," + address);
              th.setDaemon(true);
              return th;
            }
          };
      executorService = Executors.newSingleThreadScheduledExecutor(tf);

      notifier.addListener(this);
      cacheManagerNotifier.addListener(this);

      boolean totalOrder = configuration.transaction().transactionProtocol().isTotalOrder();
      if (!totalOrder) {
        completedTransactionsInfo = new CompletedTransactionsInfo();

        // Periodically run a task to cleanup the transaction table of completed transactions.
        long interval = configuration.transaction().reaperWakeUpInterval();
        executorService.scheduleAtFixedRate(
            new Runnable() {
              @Override
              public void run() {
                completedTransactionsInfo.cleanupCompletedTransactions();
              }
            },
            interval,
            interval,
            TimeUnit.MILLISECONDS);

        executorService.scheduleAtFixedRate(
            new Runnable() {
              @Override
              public void run() {
                cleanupTimedOutTransactions();
              }
            },
            interval,
            interval,
            TimeUnit.MILLISECONDS);
      }
    }
  }
예제 #21
0
 @Start(priority = 1)
 // needs to happen early on
 public void start() {
   cacheName = cache.getName();
   this.totalOrderProtocol = configuration.transaction().transactionProtocol().isTotalOrder();
 }
예제 #22
0
  @Override
  protected void performRuntime(
      OperationContext context,
      ModelNode operation,
      ModelNode model,
      ServiceVerificationHandler verificationHandler,
      List<ServiceController<?>> newControllers)
      throws OperationFailedException {
    // Because we use child resources in a read-only manner to configure the cache, replace the
    // local model with the full model
    model = Resource.Tools.readModel(context.readResource(PathAddress.EMPTY_ADDRESS));

    // Configuration to hold the operation data
    ConfigurationBuilder builder =
        new ConfigurationBuilder().read(getDefaultConfiguration(this.mode));

    // create a list for dependencies which may need to be added during processing
    List<Dependency<?>> dependencies = new LinkedList<Dependency<?>>();

    // process cache configuration ModelNode describing overrides to defaults
    processModelNode(model, builder, dependencies);

    // get all required addresses, names and service names
    PathAddress cacheAddress = PathAddress.pathAddress(operation.get(OP_ADDR));
    PathAddress containerAddress = cacheAddress.subAddress(0, cacheAddress.size() - 1);
    String cacheName = cacheAddress.getLastElement().getValue();
    String containerName = containerAddress.getLastElement().getValue();
    ServiceName containerServiceName = EmbeddedCacheManagerService.getServiceName(containerName);
    ServiceName cacheServiceName = containerServiceName.append(cacheName);
    ServiceName cacheConfigurationServiceName =
        CacheConfigurationService.getServiceName(containerName, cacheName);

    // get container Model
    Resource rootResource = context.getRootResource();
    ModelNode container = rootResource.navigate(containerAddress).getModel();

    // get default cache of the container and start mode
    String defaultCache = container.require(ModelKeys.DEFAULT_CACHE).asString();
    ServiceController.Mode initialMode =
        model.hasDefined(ModelKeys.START)
            ? StartMode.valueOf(model.get(ModelKeys.START).asString()).getMode()
            : ServiceController.Mode.ON_DEMAND;

    // install the cache configuration service (configures a cache)
    ServiceTarget target = context.getServiceTarget();
    InjectedValue<EmbeddedCacheManager> containerInjection =
        new InjectedValue<EmbeddedCacheManager>();
    CacheConfigurationDependencies cacheConfigurationDependencies =
        new CacheConfigurationDependencies(containerInjection);
    CacheConfigurationService cacheConfigurationService =
        new CacheConfigurationService(cacheName, builder, cacheConfigurationDependencies);

    ServiceBuilder<Configuration> configBuilder =
        target
            .addService(cacheConfigurationServiceName, cacheConfigurationService)
            .addDependency(containerServiceName, EmbeddedCacheManager.class, containerInjection)
            .setInitialMode(ServiceController.Mode.PASSIVE);

    Configuration config = builder.build();
    if (config.invocationBatching().enabled()) {
      cacheConfigurationDependencies
          .getTransactionManagerInjector()
          .inject(BatchModeTransactionManager.getInstance());
    } else if (config.transaction().transactionMode()
        == org.infinispan.transaction.TransactionMode.TRANSACTIONAL) {
      configBuilder.addDependency(
          TxnServices.JBOSS_TXN_TRANSACTION_MANAGER,
          TransactionManager.class,
          cacheConfigurationDependencies.getTransactionManagerInjector());
      if (config.transaction().useSynchronization()) {
        configBuilder.addDependency(
            TxnServices.JBOSS_TXN_SYNCHRONIZATION_REGISTRY,
            TransactionSynchronizationRegistry.class,
            cacheConfigurationDependencies.getTransactionSynchronizationRegistryInjector());
      }
    }

    // add in any additional dependencies resulting from ModelNode parsing
    for (Dependency<?> dependency : dependencies) {
      this.addDependency(configBuilder, dependency);
    }
    // add an alias for the default cache
    if (cacheName.equals(defaultCache)) {
      configBuilder.addAliases(CacheConfigurationService.getServiceName(containerName, null));
    }
    newControllers.add(configBuilder.install());
    log.debugf(
        "Cache configuration service for %s installed for container %s", cacheName, containerName);

    // now install the corresponding cache service (starts a configured cache)
    CacheDependencies cacheDependencies = new CacheDependencies(containerInjection);
    CacheService<Object, Object> cacheService =
        new CacheService<Object, Object>(cacheName, cacheDependencies);

    ServiceBuilder<Cache<Object, Object>> cacheBuilder =
        target
            .addService(cacheServiceName, cacheService)
            .addDependency(cacheConfigurationServiceName)
            .setInitialMode(initialMode);

    if (config.transaction().recovery().enabled()) {
      cacheBuilder.addDependency(
          TxnServices.JBOSS_TXN_ARJUNA_RECOVERY_MANAGER,
          XAResourceRecoveryRegistry.class,
          cacheDependencies.getRecoveryRegistryInjector());
    }

    // add an alias for the default cache
    if (cacheName.equals(defaultCache)) {
      cacheBuilder.addAliases(CacheService.getServiceName(containerName, null));
    }

    if (initialMode == ServiceController.Mode.ACTIVE) {
      cacheBuilder.addListener(verificationHandler);
    }

    newControllers.add(cacheBuilder.install());

    String jndiName =
        (model.hasDefined(ModelKeys.JNDI_NAME)
                ? InfinispanJndiName.toJndiName(model.get(ModelKeys.JNDI_NAME).asString())
                : InfinispanJndiName.defaultCacheJndiName(containerName, cacheName))
            .getAbsoluteName();
    ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(jndiName);

    BinderService binder = new BinderService(bindInfo.getBindName());
    @SuppressWarnings("rawtypes")
    ServiceBuilder<ManagedReferenceFactory> binderBuilder =
        target
            .addService(bindInfo.getBinderServiceName(), binder)
            .addAliases(ContextNames.JAVA_CONTEXT_SERVICE_NAME.append(jndiName))
            .addDependency(
                cacheServiceName,
                Cache.class,
                new ManagedReferenceInjector<Cache>(binder.getManagedObjectInjector()))
            .addDependency(
                bindInfo.getParentContextServiceName(),
                ServiceBasedNamingStore.class,
                binder.getNamingStoreInjector())
            .setInitialMode(ServiceController.Mode.PASSIVE);
    newControllers.add(binderBuilder.install());

    log.debugf("Cache service for cache %s installed for container %s", cacheName, containerName);
  }