repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/FixInetAddress.java
package org.infinispan.quarkus.server.runtime.graal; import java.util.Collections; import java.util.List; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.RecomputeFieldValue; import com.oracle.svm.core.annotate.TargetClass; public class FixInetAddress { } @TargetClass(org.infinispan.server.hotrod.MultiHomedServerAddress.InetAddressWithNetMask.class) final class MultiHomedServerAddress { @Alias @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.Reset) static org.infinispan.server.hotrod.MultiHomedServerAddress.InetAddressWithNetMask RFC1918_CIDR_10; @Alias @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.Reset) static org.infinispan.server.hotrod.MultiHomedServerAddress.InetAddressWithNetMask RFC1918_CIDR_172; @Alias @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.Reset) static org.infinispan.server.hotrod.MultiHomedServerAddress.InetAddressWithNetMask RFC1918_CIDR_192; @Alias @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.Reset) static org.infinispan.server.hotrod.MultiHomedServerAddress.InetAddressWithNetMask RFC3927_LINK_LOCAL; @Alias @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.Reset) static org.infinispan.server.hotrod.MultiHomedServerAddress.InetAddressWithNetMask RFC1112_RESERVED; @Alias @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.Reset) static org.infinispan.server.hotrod.MultiHomedServerAddress.InetAddressWithNetMask RFC6598_SHARED_SPACE; @Alias @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.Reset) static org.infinispan.server.hotrod.MultiHomedServerAddress.InetAddressWithNetMask RFC4193_ULA; @Alias @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.Reset) static org.infinispan.server.hotrod.MultiHomedServerAddress.InetAddressWithNetMask RFC4193_LINK_LOCAL; @Alias @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.FromAlias) static List<org.infinispan.server.hotrod.MultiHomedServerAddress.InetAddressWithNetMask> PRIVATE_NETWORKS = Collections.emptyList(); }
2,066
39.529412
135
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/FixModuleClasses.java
package org.infinispan.quarkus.server.runtime.graal; import org.infinispan.commons.configuration.io.ConfigurationReader; import org.infinispan.server.configuration.ServerConfigurationBuilder; import org.infinispan.server.configuration.ServerConfigurationParser; import org.infinispan.server.configuration.security.LdapRealmConfigurationBuilder; import org.infinispan.server.configuration.security.TrustStoreRealmConfigurationBuilder; import org.infinispan.util.logging.Log; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.Delete; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; public class FixModuleClasses { } @Delete @TargetClass(org.wildfly.security.manager.action.GetModuleClassLoaderAction.class) final class Delete_orgwildflysecuritymanageractionGetModuleClassLoaderAction { } @TargetClass(ServerConfigurationParser.class) final class Target_ServerConfigurationParser { @Alias private static Log coreLog; @Substitute private void parseLdapRealm(ConfigurationReader reader, ServerConfigurationBuilder builder, LdapRealmConfigurationBuilder ldapRealmConfigBuilder) { coreLog.debug("LDAP Realm is not supported in native mode - ignoring element"); // Just read until end of token while (reader.inTag()) { } } @Substitute private void parseTrustStoreRealm(ConfigurationReader reader, TrustStoreRealmConfigurationBuilder trustStoreBuilder) { coreLog.debug("TrustStore Realm is not supported in native mode - ignoring element"); // Just read until end of token while (reader.inTag()) { } } }
1,654
35.777778
150
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/FixAlpnClasses.java
package org.infinispan.quarkus.server.runtime.graal; public class FixAlpnClasses { } // The following requires https://github.com/quarkusio/quarkus/pull/3628 to be integrated //@Delete //// We use AlpnHackedJdkApplicationProtocolNegotiator, so no need to use this one //@TargetClass(className = "io.netty.handler.ssl.JdkAlpnApplicationProtocolNegotiator") //final class Delete_JdkAlpnApplicationProtocolNegotiator { } // //// Have to make name unique - as quarkus has this same class //@TargetClass(className = "io.netty.handler.ssl.JdkDefaultApplicationProtocolNegotiator") //final class Target_io_netty_handler_ssl_JdkDefaultApplicationProtocolNegotiator { // // @Alias // public static Target_io_netty_handler_ssl_JdkDefaultApplicationProtocolNegotiator INSTANCE; //} // //@TargetClass(className = "io.netty.handler.ssl.JdkSslContext") //final class Target_io_netty_handler_ssl_JdkSslContext { // // @Substitute // static JdkApplicationProtocolNegotiator toNegotiator(ApplicationProtocolConfig config, boolean isServer) { // if (config == null) { // return (JdkApplicationProtocolNegotiator) (Object) Target_io_netty_handler_ssl_JdkDefaultApplicationProtocolNegotiator.INSTANCE; // } // // switch (config.protocol()) { // case NONE: // return (JdkApplicationProtocolNegotiator) (Object) Target_io_netty_handler_ssl_JdkDefaultApplicationProtocolNegotiator.INSTANCE; // case ALPN: // if (isServer) { // // GRAAL RC9 bug: https://github.com/oracle/graal/issues/813 // // switch(config.selectorFailureBehavior()) { // // case FATAL_ALERT: // // return new JdkAlpnApplicationProtocolNegotiator(true, config.supportedProtocols()); // // case NO_ADVERTISE: // // return new JdkAlpnApplicationProtocolNegotiator(false, config.supportedProtocols()); // // default: // // throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ") // // .append(config.selectorFailureBehavior()).append(" failure behavior").toString()); // // } // ApplicationProtocolConfig.SelectorFailureBehavior behavior = config.selectorFailureBehavior(); // if (behavior == ApplicationProtocolConfig.SelectorFailureBehavior.FATAL_ALERT) // return new AlpnHackedJdkApplicationProtocolNegotiator(true, config.supportedProtocols()); // else if (behavior == ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE) // return new AlpnHackedJdkApplicationProtocolNegotiator(false, config.supportedProtocols()); // else { // throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ") // .append(config.selectorFailureBehavior()).append(" failure behavior").toString()); // } // } else { // switch (config.selectedListenerFailureBehavior()) { // case ACCEPT: // return new AlpnHackedJdkApplicationProtocolNegotiator(false, config.supportedProtocols()); // case FATAL_ALERT: // return new AlpnHackedJdkApplicationProtocolNegotiator(true, config.supportedProtocols()); // default: // throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ") // .append(config.selectedListenerFailureBehavior()).append(" failure behavior").toString()); // } // } // default: // throw new UnsupportedOperationException( // new StringBuilder("JDK provider does not support ").append(config.protocol()).append(" protocol") // .toString()); // } // } // //}
4,058
54.60274
142
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/DisableServerInitialContextFactoryBuilder.java
package org.infinispan.quarkus.server.runtime.graal; import org.infinispan.server.Server; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; public class DisableServerInitialContextFactoryBuilder { } @TargetClass(Server.class) final class Target_org_infinispan_server_Server { @Substitute private void registerInitialContextFactoryBuilder() { // Do nothing } }
426
22.722222
56
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/SubstituteDnsLookup.java
package org.infinispan.quarkus.server.runtime.graal; import java.util.Hashtable; import java.util.concurrent.ConcurrentMap; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.spi.InitialContextFactory; import org.infinispan.server.context.ServerInitialContextFactory; import org.infinispan.server.context.ServerInitialContextFactoryBuilder; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; public class SubstituteDnsLookup { } @TargetClass(ServerInitialContextFactoryBuilder.class) final class Target_ServerInitialContextFactoryBuilder { @Alias private ConcurrentMap<String, Object> namedObjects; @Substitute public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException { String className = environment != null ? (String) environment.get(Context.INITIAL_CONTEXT_FACTORY) : null; if (className == null) { return new ServerInitialContextFactory(namedObjects); } switch (className) { case "com.sun.jndi.dns.DnsContextFactory": return new com.sun.jndi.dns.DnsContextFactory(); case "com.sun.jndi.ldap.LdapCtxFactory": return new com.sun.jndi.ldap.LdapCtxFactory(); default: throw new NamingException("Native Infinispan Server does not support " + className + " as an InitialContextFactory"); } } }
1,492
35.414634
129
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/SubstituteClientClasses.java
package org.infinispan.quarkus.server.runtime.graal; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.Delete; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.InternalRemoteCache; import org.infinispan.client.hotrod.impl.RemoteCacheImpl; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.commons.marshall.Marshaller; import javax.management.ObjectName; import java.util.concurrent.ExecutorService; @Substitute @TargetClass(className = "org.infinispan.client.hotrod.impl.transport.netty.DefaultTransportFactory") final class SubstituteTransportHelper { @Substitute public Class<? extends SocketChannel> socketChannelClass() { return NioSocketChannel.class; } @Substitute public EventLoopGroup createEventLoopGroup(int maxExecutors, ExecutorService executorService) { return new NioEventLoopGroup(maxExecutors, executorService); } } @TargetClass(RemoteCacheManager.class) final class SubstituteRemoteCacheManager { @Alias private Marshaller marshaller; @Alias private Configuration configuration; @Substitute private void initRemoteCache(InternalRemoteCache<?, ?> remoteCache, OperationsFactory operationsFactory) { // Invoke the init method that doesn't have the JMX ObjectName argument remoteCache.init(operationsFactory, configuration); } @Substitute private void registerMBean() { } @Substitute private void unregisterMBean() { } } @TargetClass(RemoteCacheImpl.class) final class SubstituteRemoteCacheImpl { @Delete private ObjectName mbeanObjectName; @Substitute private void registerMBean(ObjectName jmxParent) { } @Substitute private void unregisterMBean() { } // Sadly this method is public, so technically a user could get a Runtime error if they were referencing // it before - but it is the only way to make graal happy @Delete public void init(OperationsFactory operationsFactory, Configuration configuration, ObjectName jmxParent) { } } // TODO sort out duplication with quarkus infinispan-client extension public class SubstituteClientClasses { }
2,624
30.626506
110
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/SubstituteJBossMarshallingClasses.java
package org.infinispan.quarkus.server.runtime.graal; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.graalvm.substitutions.graal.Util; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.remote.LifecycleCallbacks; import org.infinispan.persistence.remote.upgrade.MigrationTask; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; // We need to remove all the MigrationTask and related classes as they load up JBoss Marshalling public class SubstituteJBossMarshallingClasses { } @TargetClass(MigrationTask.class) final class Target_MigrationTask { @Substitute public Integer apply(EmbeddedCacheManager embeddedCacheManager) { throw Util.unsupportedOperationException("Migration Task"); } } @TargetClass(LifecycleCallbacks.class) final class Target_org_infinispan_persistence_remote_LifecycleCallbacks { @Substitute public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalCfg) { } }
1,113
36.133333
99
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/SubstituteStandardConversions.java
package org.infinispan.quarkus.server.runtime.graal; import static java.nio.charset.StandardCharsets.UTF_8; import org.infinispan.commons.dataconversion.EncodingException; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.StandardConversions; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; @TargetClass(StandardConversions.class) final class SubstituteStandardConversions { // Method substituted so it doesn't have to use Class.forName for well known types - uses switch instead @Substitute public static Object decodeObjectContent(Object content, MediaType contentMediaType) { if (content == null) return null; if (contentMediaType == null) { throw new NullPointerException("contentMediaType cannot be null!"); } String strContent; String type = contentMediaType.getClassType(); if (type == null) return content; if (type.equals("ByteArray")) { if (content instanceof byte[]) return content; if (content instanceof String) return hexToBytes(content.toString()); throw new EncodingException("Cannot read ByteArray!"); } if (content instanceof byte[]) { strContent = new String((byte[]) content, UTF_8); } else { strContent = content.toString(); } switch (type) { case "java.lang.String": return strContent; case "java.lang.Boolean": return Boolean.parseBoolean(strContent); case "java.lang.Short": return Short.parseShort(strContent); case "java.lang.Byte": return Byte.parseByte(strContent); case "java.lang.Integer": return Integer.parseInt(strContent); case "java.lang.Long": return Long.parseLong(strContent); case "java.lang.Float": return Float.parseFloat(strContent); case "java.lang.Double": return Double.parseDouble(strContent); } return content; } @Alias public static byte[] hexToBytes(String hex) { return null; } }
2,215
33.092308
107
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/DisableAuthentication.java
package org.infinispan.quarkus.server.runtime.graal; import static org.wildfly.security.x500._private.ElytronMessages.log; import java.lang.invoke.MethodHandle; import java.security.Principal; import javax.security.auth.x500.X500Principal; import org.wildfly.security.x500.util.X500PrincipalUtil; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.Delete; import com.oracle.svm.core.annotate.RecomputeFieldValue; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; public class DisableAuthentication { } @TargetClass(X500PrincipalUtil.class) final class Target_org_wildfly_security_x500_util_X500PrincipalUtil { @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.Reset) @Alias static Class<?> X500_NAME_CLASS; @Delete static MethodHandle AS_X500_PRINCIPAL_HANDLE; /** * Only handle the case of converting a {@linkplain Principal#getName()} to {@linkplain X500Principal} * * @param principal - Principal with name that maps to valid DN * @param convert - whether one should convert to X500Principal * @return X500Principal if convert is true and valid DN is seen, null otherwise */ @Substitute public static X500Principal asX500Principal(Principal principal, boolean convert) { if (convert) { try { return new X500Principal(principal.getName()); } catch (IllegalArgumentException ignored) { log.trace("Unable to convert to X500Principal", ignored); } } return null; } }
1,572
31.770833
105
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/SubstituteLoggingClasses.java
package org.infinispan.quarkus.server.runtime.graal; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.rest.RestServer; import org.infinispan.rest.framework.ResourceManager; import org.infinispan.rest.resources.LoggingResource; import org.infinispan.server.Bootstrap; import org.infinispan.server.BootstrapLogging; import org.infinispan.server.Server; import org.infinispan.server.core.admin.AdminServerTask; import org.infinispan.server.tasks.admin.LoggingRemoveTask; import org.infinispan.server.tasks.admin.LoggingSetTask; import org.infinispan.server.tasks.admin.ServerAdminOperationsHandler; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.Delete; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; public class SubstituteLoggingClasses { } @TargetClass(RestServer.class) final class Target_RestServer { @Substitute private void registerLoggingResource(ResourceManager resourceManager, String restContext) { // Do nothing } } @Delete @TargetClass(LoggingResource.class) final class Target_LoggingResource { } @TargetClass(Server.class) final class Target_Server { @Substitute private void shutdownLog4jLogManager() { // Do nothing } } @TargetClass(Bootstrap.class) final class Target_Bootstrap { @Substitute private static void staticInitializer() { // Do nothing } @Substitute protected void configureLogging() { // Do nothing } } @Delete @TargetClass(BootstrapLogging.class) final class Target_BootstrapLogging { } @TargetClass(ServerAdminOperationsHandler.class) final class Target_ServerAdminOperationsHandler { @Substitute private static AdminServerTask<?>[] generateTasks(ConfigurationBuilderHolder defaultsHolder) { return generateTasksWithoutLogging(defaultsHolder); } @Alias private static AdminServerTask<?>[] generateTasksWithoutLogging(ConfigurationBuilderHolder defaultsHolder) { return null; } } @Delete @TargetClass(LoggingRemoveTask.class) final class Target_LoggingRemoveTask { } @Delete @TargetClass(LoggingSetTask.class) final class Target_LoggingSetTask { }
2,208
26.271605
111
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/SubstituteIndexClasses.java
package org.infinispan.quarkus.server.runtime.graal; import java.lang.invoke.MethodHandles; import java.util.Collections; import java.util.Map; import java.util.Set; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.IndexingConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.factories.impl.ModuleMetadataBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.objectfilter.impl.ql.PropertyPath; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.objectfilter.impl.syntax.parser.ReflectionEntityNamesResolver; import org.infinispan.graalvm.substitutions.graal.Util; import org.infinispan.query.concurrent.QueryPackageImpl; import org.infinispan.query.dsl.embedded.impl.ObjectReflectionMatcher; import org.infinispan.query.dsl.embedded.impl.QueryEngine; import org.infinispan.query.dsl.embedded.impl.SearchQueryMaker; import org.infinispan.query.dsl.embedded.impl.SearchQueryParsingResult; import org.infinispan.query.impl.LifecycleManager; import org.infinispan.query.impl.massindex.IndexWorker; import org.infinispan.query.remote.impl.LazySearchMapping; import org.infinispan.registry.InternalCacheRegistry; import org.infinispan.search.mapper.mapping.SearchMappingBuilder; import org.infinispan.search.mapper.model.impl.InfinispanBootstrapIntrospector; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.Delete; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; //import org.infinispan.lucene.LifecycleCallbacks; class SubstituteIndexClasses { } @TargetClass(IndexWorker.class) final class Target_IndexWorker { @Substitute public Void apply(EmbeddedCacheManager embeddedCacheManager) { throw Util.unsupportedOperationException("Indexing"); } } @TargetClass(LifecycleManager.class) final class Target_org_infinispan_query_impl_LifecycleManager { @Substitute public void cacheStarted(ComponentRegistry cr, String cacheName) { // Do nothing - this method used to setup indexing parts and JMX (neither which are supported) } @Substitute public void cacheStarting(ComponentRegistry cr, Configuration cfg, String cacheName) { if (cfg.indexing().enabled()) { Util.unsupportedOperationException("Indexing", "Cache " + cacheName + " has it enabled!"); } InternalCacheRegistry icr = cr.getGlobalComponentRegistry().getComponent(InternalCacheRegistry.class); if (!icr.isInternalCache(cacheName) || icr.internalCacheHasFlag(cacheName, InternalCacheRegistry.Flag.QUERYABLE)) { AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache(); cr.registerComponent(ObjectReflectionMatcher.create(cache, new ReflectionEntityNamesResolver(getClass().getClassLoader()),null), ObjectReflectionMatcher.class); cr.registerComponent(new QueryEngine<>(cache, false), QueryEngine.class); } } } @TargetClass(org.infinispan.query.remote.impl.LifecycleManager.class) final class Target_org_infinispan_query_remote_impl_LifecycleManager { @Substitute public void cacheManagerStarted(GlobalComponentRegistry gcr) { // no-op } @Substitute public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalCfg) { // no-op } @Substitute public void cacheStarting(ComponentRegistry cr, Configuration cfg, String cacheName) { } } @TargetClass(IndexingConfigurationBuilder.class) final class Target_IndexingConfigurationBuilder { @Alias private AttributeSet attributes; @Substitute public Object addIndexedEntity(Class<?> indexedEntity) { throw Util.unsupportedOperationException("Indexing"); } @Substitute private Set<Class<?>> indexedEntities() { return Collections.emptySet(); } } @TargetClass(SearchQueryMaker.class) final class Target_SearchQueryMaker { @Substitute private boolean isMultiTermText(PropertyPath<?> propertyPath, String text) { return false; } @Substitute public SearchQueryParsingResult transform(IckleParsingResult<?> parsingResult, Map<String, Object> namedParameters, Class<?> targetedType, String targetedTypeName) { return null; } } @TargetClass(SearchMappingBuilder.class) final class Target_SearchMappingBuilder { @Substitute public static InfinispanBootstrapIntrospector introspector(MethodHandles.Lookup lookup) { return null; } } @TargetClass(QueryPackageImpl.class) final class Target_QueryPackageImpl { @Substitute public static void registerMetadata(ModuleMetadataBuilder.ModuleBuilder builder) { // no-op } } @TargetClass(LazySearchMapping.class) @Delete final class Target_LazySearchMapping { }
5,133
35.15493
169
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/SubstituteNettyClasses.java
package org.infinispan.quarkus.server.runtime.graal; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.Delete; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; import io.netty.channel.MultithreadEventLoopGroup; import io.netty.channel.ServerChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import org.infinispan.server.core.configuration.ProtocolServerConfiguration; import org.infinispan.server.core.logging.Log; import org.infinispan.server.core.transport.NettyTransport; import java.util.concurrent.ThreadFactory; public class SubstituteNettyClasses { } @Delete @TargetClass(className = "org.infinispan.server.core.transport.NativeTransport") final class Delete_org_infinispan_server_core_transport_NativeTransport { } @TargetClass(NettyTransport.class) final class Substitute_NettyTransport { @Alias static private Log log; @Alias private ProtocolServerConfiguration configuration; @Substitute private Class<? extends ServerChannel> getServerSocketChannel() { Class<? extends ServerChannel> channel = NioServerSocketChannel.class; log.createdSocketChannel(channel.getName(), configuration.toString()); return channel; } @Substitute public static MultithreadEventLoopGroup buildEventLoop(int nThreads, ThreadFactory threadFactory, String configuration) { MultithreadEventLoopGroup eventLoop = new NioEventLoopGroup(nThreads, threadFactory); log.createdNettyEventLoop(eventLoop.getClass().getName(), configuration); return eventLoop; } } /* * Reinstate once we include the Hot Rod client * @Delete @TargetClass(className = "org.infinispan.client.hotrod.impl.transport.netty.NativeTransport") final class Delete_org_infinispan_client_hotrod_impl_transport_netty_NativeTransport { } */
1,914
34.462963
100
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/DisableXmlTranscoder.java
package org.infinispan.quarkus.server.runtime.graal; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.marshall.core.EncoderRegistry; import org.infinispan.server.core.LifecycleCallbacks; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; public class DisableXmlTranscoder { } @TargetClass(LifecycleCallbacks.class) final class Target_LifecycleCallbacks { @Substitute private void registerXmlTranscoder(EncoderRegistry encoderRegistry, ClassLoader classLoader, ClassAllowList classAllowList) { // Do nothing } }
609
29.5
128
java
null
infinispan-main/quarkus/server/runtime/src/main/java/org/infinispan/quarkus/server/runtime/graal/SubstituteElytronClasses.java
package org.infinispan.quarkus.server.runtime.graal; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; import org.infinispan.server.configuration.ServerConfiguration; import org.infinispan.server.configuration.security.LdapRealmConfiguration; import org.infinispan.server.configuration.security.RealmConfiguration; import org.infinispan.server.configuration.security.SecurityConfiguration; import org.infinispan.server.security.ElytronJMXAuthenticator; import org.wildfly.security.auth.realm.ldap.LdapSecurityRealmBuilder; import org.wildfly.security.auth.server.ModifiableRealmIdentity; import org.wildfly.security.auth.server.RealmIdentity; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityRealm; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import java.security.Principal; import java.util.Properties; public class SubstituteElytronClasses { } @TargetClass(LdapRealmConfiguration.class) final class Target_LdapRealmConfiguration { @Substitute public SecurityRealm build(SecurityConfiguration security, RealmConfiguration realm, SecurityDomain.Builder domainBuilder, Properties properties) { return LdapSecurityRealmBuilder.builder().build(); } } @TargetClass(ElytronJMXAuthenticator.class) final class Target_ElytronJMXAuthenticator { @Substitute public static void init(ServerConfiguration serverConfiguration) { // no-op } @Substitute public boolean test(CallbackHandler callbackHandler, Subject subject) { return false; } } @TargetClass(className = "org.wildfly.security.auth.realm.ldap.LdapSecurityRealm") final class Target_LdapSecurityRealm { @Substitute public RealmIdentity getRealmIdentity(Principal principal) { return null; } @Substitute public ModifiableRealmIdentity getRealmIdentityForUpdate(Principal principal) { return null; } }
1,978
33.719298
150
java
null
infinispan-main/quarkus/server/deployment/src/main/java/org/infinispan/quarkus/server/deployment/InfinispanServerProcessor.java
package org.infinispan.quarkus.server.deployment; import java.lang.management.MemoryType; import java.lang.management.MemoryUsage; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.ServiceLoader; import org.infinispan.anchored.configuration.AnchoredKeysConfigurationBuilder; import org.infinispan.commands.module.ModuleCommandExtensions; import org.infinispan.commons.util.JVMMemoryInfoInfo; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.counter.configuration.CounterManagerConfigurationBuilder; import org.infinispan.lock.configuration.ClusteredLockManagerConfigurationBuilder; import org.infinispan.manager.CacheManagerInfo; import org.infinispan.protostream.WrappedMessage; import org.infinispan.quarkus.embedded.deployment.InfinispanReflectionExcludedBuildItem; import org.infinispan.rest.RestServer; import org.infinispan.server.configuration.ServerConfigurationBuilder; import org.infinispan.server.core.configuration.ProtocolServerConfigurationBuilder; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.memcached.MemcachedServer; import org.infinispan.server.resp.Resp3Handler; import org.infinispan.server.resp.RespServer; import org.infinispan.server.resp.configuration.RespServerConfigurationBuilder; import org.infinispan.tasks.Task; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.IndexView; import org.wildfly.security.password.impl.PasswordFactorySpiImpl; import com.thoughtworks.xstream.security.NoTypePermission; import io.netty.handler.codec.http2.CleartextHttp2ServerUpgradeHandler; import io.netty.handler.codec.http2.Http2ServerUpgradeCodec; import io.quarkus.arc.deployment.AdditionalBeanBuildItem; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.CombinedIndexBuildItem; import io.quarkus.deployment.builditem.ExtensionSslNativeSupportBuildItem; import io.quarkus.deployment.builditem.FeatureBuildItem; import io.quarkus.deployment.builditem.IndexDependencyBuildItem; import io.quarkus.deployment.builditem.SystemPropertyBuildItem; import io.quarkus.deployment.builditem.nativeimage.ExcludeConfigBuildItem; import io.quarkus.deployment.builditem.nativeimage.NativeImageResourceBuildItem; import io.quarkus.deployment.builditem.nativeimage.NativeImageSystemPropertyBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem; import io.quarkus.deployment.builditem.nativeimage.RuntimeInitializedClassBuildItem; import io.quarkus.deployment.builditem.nativeimage.ServiceProviderBuildItem; class InfinispanServerProcessor { private static final String FEATURE_NAME = "infinispan-server"; @BuildStep void setSystemProperties(BuildProducer<NativeImageSystemPropertyBuildItem> buildSystemProperties, BuildProducer<SystemPropertyBuildItem> systemProperties) { // We disable the replacement of JdkSslContext in the NettyExtensions - this shouldn't be needed once we move to Java 11 buildSystemProperties.produce(new NativeImageSystemPropertyBuildItem("substratevm.replacement.jdksslcontext", "false")); // Make sure to disable the logging endpoint in JVM mode as it won't work as Quarkus replaces log4j classes systemProperties.produce(new SystemPropertyBuildItem("infinispan.server.resource.logging", "false")); } @BuildStep void extensionFeatureStuff(BuildProducer<FeatureBuildItem> feature, BuildProducer<AdditionalBeanBuildItem> additionalBeans, BuildProducer<IndexDependencyBuildItem> indexedDependencies, BuildProducer<ExtensionSslNativeSupportBuildItem> sslNativeSupport) { feature.produce(new FeatureBuildItem(FEATURE_NAME)); sslNativeSupport.produce(new ExtensionSslNativeSupportBuildItem(FEATURE_NAME)); for (String infinispanArtifact : Arrays.asList( "infinispan-server-runtime", "infinispan-server-hotrod", "infinispan-server-core", "infinispan-server-rest", "infinispan-server-memcached", "infinispan-server-router", // Why is client-hotrod in dependency tree?? "infinispan-client-hotrod", "infinispan-cachestore-jdbc", "infinispan-cachestore-remote", "infinispan-clustered-counter", "infinispan-clustered-lock" )) { indexedDependencies.produce(new IndexDependencyBuildItem("org.infinispan", infinispanArtifact)); } } @BuildStep void loadServices(BuildProducer<ServiceProviderBuildItem> serviceProvider) { // Need to register all the module command extensions as service providers so they can be picked up at runtime ServiceLoader<?> serviceLoader = ServiceLoader.load(ModuleCommandExtensions.class); List<String> interfaceImplementations = new ArrayList<>(); serviceLoader.forEach(mmb -> interfaceImplementations.add(mmb.getClass().getName())); if (!interfaceImplementations.isEmpty()) { serviceProvider.produce(new ServiceProviderBuildItem(ModuleCommandExtensions.class.getName(), interfaceImplementations)); } } @BuildStep void addExcludedClassesFromReflection(BuildProducer<InfinispanReflectionExcludedBuildItem> excludedClasses) { // We don't support Indexing so don't these to reflection // excludedClasses.produce(new InfinispanReflectionExcludedBuildItem(DotName.createSimple(AffinityIndexManager.class.getName()))); // excludedClasses.produce(new InfinispanReflectionExcludedBuildItem(DotName.createSimple(ShardAllocationManagerImpl.class.getName()))); // This class is used by JBossMarshalling so we don't need excludedClasses.produce(new InfinispanReflectionExcludedBuildItem(DotName.createSimple("org.infinispan.persistence.remote.upgrade.MigrationTask$RemoveListener"))); // TODO: exclude all the TerminalFunctions SerializeWith references } @BuildStep void addRuntimeInitializedClasses(BuildProducer<RuntimeInitializedClassBuildItem> runtimeInitialized) { runtimeInitialized.produce(new RuntimeInitializedClassBuildItem(CleartextHttp2ServerUpgradeHandler.class.getName())); runtimeInitialized.produce(new RuntimeInitializedClassBuildItem(Http2ServerUpgradeCodec.class.getName())); runtimeInitialized.produce(new RuntimeInitializedClassBuildItem(Resp3Handler.class.getName())); } @BuildStep void addReflectionAndResources(BuildProducer<ReflectiveClassBuildItem> reflectionClass, BuildProducer<NativeImageResourceBuildItem> resources, CombinedIndexBuildItem combinedIndexBuildItem) { reflectionClass.produce(new ReflectiveClassBuildItem(false, false, PrivateGlobalConfigurationBuilder.class.getName())); reflectionClass.produce(new ReflectiveClassBuildItem(false, false, ServerConfigurationBuilder.class.getName())); // Add the various protocol server implementations reflectionClass.produce(new ReflectiveClassBuildItem(false, false, HotRodServer.class)); reflectionClass.produce(new ReflectiveClassBuildItem(false, false, MemcachedServer.class)); reflectionClass.produce(new ReflectiveClassBuildItem(false, false, RestServer.class)); reflectionClass.produce(new ReflectiveClassBuildItem(false, false, RespServer.class)); // We instantiate this during logging initialization reflectionClass.produce(new ReflectiveClassBuildItem(false, false, "org.apache.logging.log4j.message.ReusableMessageFactory")); reflectionClass.produce(new ReflectiveClassBuildItem(false, false, "org.apache.logging.log4j.message.DefaultFlowMessageFactory")); reflectionClass.produce(new ReflectiveClassBuildItem(false, false, PasswordFactorySpiImpl.class)); IndexView combinedIndex = combinedIndexBuildItem.getIndex(); addReflectionForClass(ProtocolServerConfigurationBuilder.class, false, combinedIndex, reflectionClass); // TODO: not sure why this is required for native runtime... reflectionClass.produce(new ReflectiveClassBuildItem(false, false, NoTypePermission.class.getName())); resources.produce(new NativeImageResourceBuildItem("infinispan-defaults.xml", "proto/generated/persistence.counters.proto", "proto/generated/persistence.query.proto", "proto/generated/persistence.query.core.proto", "proto/generated/persistence.remote_query.proto", "proto/generated/persistence.memcached.proto", "proto/generated/persistence.event_logger.proto", "proto/generated/persistence.multimap.proto", "proto/persistence.m.event_logger.proto", "proto/generated/persistence.server.core.proto", "proto/generated/persistence.servertasks.proto", "proto/generated/persistence.scripting.proto", "proto/generated/persistence.server_state.proto", "proto/generated/persistence.distribution.proto", "org/infinispan/query/remote/client/query.proto", WrappedMessage.PROTO_FILE )); // Add various classes required by the REST resources registerClass(reflectionClass, JVMMemoryInfoInfo.class, true, false, false); registerClass(reflectionClass, MemoryType.class, true, false, true); registerClass(reflectionClass, MemoryUsage.class, true, false, true); registerClass(reflectionClass, CacheManagerInfo.class, true, false, false); addReflectionForName(Task.class.getName(), true, combinedIndex, reflectionClass, true, false); reflectionClass.produce(new ReflectiveClassBuildItem(true, false, "org.infinispan.health.impl.CacheHealthImpl")); reflectionClass.produce(new ReflectiveClassBuildItem(true, false, "org.infinispan.health.impl.ClusterHealthImpl")); reflectionClass.produce(new ReflectiveClassBuildItem(true, false, "org.infinispan.rest.resources.CacheManagerResource$HealthInfo")); reflectionClass.produce(new ReflectiveClassBuildItem(true, false, "org.infinispan.rest.resources.CacheManagerResource$NamedCacheConfiguration")); reflectionClass.produce(new ReflectiveClassBuildItem(true, true, "org.infinispan.rest.resources.CacheManagerResource$CacheInfo")); reflectionClass.produce(new ReflectiveClassBuildItem(false, true, "org.infinispan.rest.resources.ProtobufResource$ProtoSchema")); reflectionClass.produce(new ReflectiveClassBuildItem(false, true, "org.infinispan.rest.resources.ProtobufResource$ValidationError")); // Register various Elytron classes String[] elytronClasses = new String[]{ "org.wildfly.security.http.digest.DigestMechanismFactory", "org.wildfly.security.http.basic.BasicMechanismFactory", "org.wildfly.security.password.impl.PasswordFactorySpiImpl", "org.wildfly.security.sasl.digest.DigestClientFactory", "org.wildfly.security.sasl.digest.DigestServerFactory", "org.wildfly.security.sasl.localuser.LocalUserClientFactory", "org.wildfly.security.sasl.localuser.LocalUserServerFactory", "org.wildfly.security.sasl.plain.PlainSaslClientFactory", "org.wildfly.security.sasl.plain.PlainSaslServerFactory", "org.wildfly.security.sasl.scram.ScramSaslClientFactory", "org.wildfly.security.sasl.scram.ScramSaslServerFactory", "org.wildfly.security.credential.KeyPairCredential", "org.wildfly.security.credential.PasswordCredential", "org.wildfly.security.credential.SecretKeyCredential", "org.wildfly.security.credential.X509CertificateChainPrivateCredential", }; reflectionClass.produce(new ReflectiveClassBuildItem(true, false, elytronClasses)); reflectionClass.produce(new ReflectiveClassBuildItem(false, false, CounterManagerConfigurationBuilder.class)); reflectionClass.produce(new ReflectiveClassBuildItem(false, false, AnchoredKeysConfigurationBuilder.class)); reflectionClass.produce(new ReflectiveClassBuildItem(false, false, ClusteredLockManagerConfigurationBuilder.class)); reflectionClass.produce(new ReflectiveClassBuildItem(false, false, RespServerConfigurationBuilder.class)); } @BuildStep void excludeResourcesFromDependencies(BuildProducer<ExcludeConfigBuildItem> excludeConfigBuildItemBuildProducer) { excludeConfigBuildItemBuildProducer.produce(new ExcludeConfigBuildItem("io\\.lettuce\\.lettuce-core-.+.jar", "/META-INF/native-image/io.lettuce/lettuce-core/reflect-config.json")); } private void addReflectionForClass(Class<?> classToUse, boolean isInterface, IndexView indexView, BuildProducer<ReflectiveClassBuildItem> reflectiveClass) { addReflectionForName(classToUse.getName(), isInterface, indexView, reflectiveClass, false, false); } private void addReflectionForName(String className, boolean isInterface, IndexView indexView, BuildProducer<ReflectiveClassBuildItem> reflectiveClass, boolean methods, boolean fields) { Collection<ClassInfo> classInfos; if (isInterface) { classInfos = indexView.getAllKnownImplementors(DotName.createSimple(className)); } else { classInfos = indexView.getAllKnownSubclasses(DotName.createSimple(className)); } if (!classInfos.isEmpty()) { reflectiveClass.produce(new ReflectiveClassBuildItem(methods, fields, classInfos.stream().map(ClassInfo::toString).toArray(String[]::new))); } } private void registerClass(BuildProducer<ReflectiveClassBuildItem> reflectionClass, Class<?> clazz, boolean methods, boolean fields, boolean ignoreNested) { reflectionClass.produce(new ReflectiveClassBuildItem(methods, fields, clazz)); if (!ignoreNested) { Class<?>[] declaredClasses = clazz.getDeclaredClasses(); for (Class<?> declaredClass : declaredClasses) registerClass(reflectionClass, declaredClass, methods, fields, false); } } }
14,184
58.852321
186
java
null
infinispan-main/core/src/test/java/org/infinispan/stress/PutIfAbsentStressTest.java
package org.infinispan.stress; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Verifies the atomic semantic of Infinispan's implementations of * java.util.concurrent.ConcurrentMap<K, V>.putIfAbsent(K key, V value); which is an interesting * concurrent locking case. * * @since 4.0 * @see java.util.concurrent.ConcurrentMap#putIfAbsent(Object, Object) * @author Sanne Grinovero */ @Test(groups = "stress", testName = "stress.PutIfAbsentStressTest", description = "Since this test is slow to run, it should be disabled by default and run by hand as necessary.", timeOut = 15*60*1000) public class PutIfAbsentStressTest extends AbstractInfinispanTest { private static final int NODES_NUM = 5; private static final int THREAD_PER_NODE = 12; private static final long STRESS_TIME_MINUTES = 2; private static final String SHARED_KEY = "thisIsTheKeyForConcurrentAccess"; /** * Purpose is not testing JDK's ConcurrentHashMap but ensuring the test is correct. It's also * interesting to compare performance. */ public void testonConcurrentHashMap() throws Exception { System.out.println("Running test on ConcurrentHashMap:"); ConcurrentMap<String, String> map = new ConcurrentHashMap<String, String>(); testConcurrentLocking(map); } /** * Testing putIfAbsent's behaviour on a Local cache. */ public void testonInfinispanLocal() throws Exception { System.out.println("Running test on Infinispan, LOCAL:"); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(false); ConcurrentMap<String, String> map = cm.getCache(); try { testConcurrentLocking(map); } finally { TestingUtil.killCacheManagers(cm); } } /** * Testing putIfAbsent's behaviour in DIST_SYNC cache. */ public void testonInfinispanDIST_SYNC() throws Exception { System.out.println("Running test on Infinispan, DIST_SYNC:"); ConfigurationBuilder c = new ConfigurationBuilder(); c.clustering().cacheMode(CacheMode.DIST_SYNC); testConcurrentLockingOnMultipleManagers(c); } /** * Testing putIfAbsent's behaviour in DIST_SYNC cache, disabling L1 */ public void testonInfinispanDIST_NOL1() throws Exception { System.out.println("Running test on Infinispan, DIST_SYNC, disabling L1:"); ConfigurationBuilder c = new ConfigurationBuilder(); c.clustering().cacheMode(CacheMode.DIST_SYNC).l1().disable(); testConcurrentLockingOnMultipleManagers(c); } /** * Testing putIfAbsent's behaviour in REPL_SYNC cache. */ public void testonInfinispanREPL_SYNC() throws Exception { System.out.println("Running test on Infinispan, REPL_SYNC:"); ConfigurationBuilder c = new ConfigurationBuilder(); c.clustering().cacheMode(CacheMode.REPL_SYNC); testConcurrentLockingOnMultipleManagers(c); } /** * Testing putIfAbsent's behaviour in REPL_ASYNC cache. */ public void testonInfinispanREPL_ASYNC() throws Exception { System.out.println("Running test on Infinispan, REPL_ASYNC:"); ConfigurationBuilder c = new ConfigurationBuilder(); c.clustering().cacheMode(CacheMode.REPL_ASYNC); testConcurrentLockingOnMultipleManagers(c); } /** * Adapter to run the test on any configuration */ private void testConcurrentLockingOnMultipleManagers(ConfigurationBuilder cfg) throws InterruptedException { List<EmbeddedCacheManager> cacheContainers = new ArrayList<EmbeddedCacheManager>(NODES_NUM); List<Cache<String, String>> caches = new ArrayList<Cache<String, String>>(); List<ConcurrentMap<String, String>> maps = new ArrayList<ConcurrentMap<String, String>>(NODES_NUM * THREAD_PER_NODE); for (int nodeNum = 0; nodeNum < NODES_NUM; nodeNum++) { EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(cfg); cacheContainers.add(cm); Cache<String, String> cache = cm.getCache(); caches.add(cache); for (int threadNum = 0; threadNum < THREAD_PER_NODE; threadNum++) { maps.add(cache); } } TestingUtil.blockUntilViewsReceived(10000, caches); try { testConcurrentLocking(maps); } finally { TestingUtil.killCacheManagers(cacheContainers); } } /** * Adapter for tests sharing a single Cache instance */ private void testConcurrentLocking(ConcurrentMap<String, String> map) throws InterruptedException { int size = NODES_NUM * THREAD_PER_NODE; List<ConcurrentMap<String, String>> maps = new ArrayList<ConcurrentMap<String, String>>(size); for (int i = 0; i < size; i++) { maps.add(map); } testConcurrentLocking(maps); } /** * Drives the actual test on an Executor and verifies the result * * @param maps the caches to be tested */ private void testConcurrentLocking(List<ConcurrentMap<String, String>> maps) throws InterruptedException { SharedStats stats = new SharedStats(); ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(NODES_NUM); List<StressingThread> threads = new ArrayList<StressingThread>(); int i=0; for (ConcurrentMap<String, String> map : maps) { StressingThread thread = new StressingThread(stats, map, i++); threads.add(thread); executor.execute(thread); } executor.shutdown(); Thread.sleep(5000); int putsAfter5Seconds = stats.succesfullPutsCounter.get(); System.out.println("\nSituation after 5 seconds:"); System.out.println(stats.toString()); executor.awaitTermination(STRESS_TIME_MINUTES, TimeUnit.MINUTES); stats.globalQuit = true; executor.awaitTermination(10, TimeUnit.SECONDS); // give some time to awake and quit executor.shutdownNow(); System.out.println("\nFinal situation:"); System.out.println(stats.toString()); assert !stats.seenFailures : "at least one thread has seen unexpected state"; assert stats.succesfullPutsCounter.get() > 0 : "the lock should have been taken at least once"; assert stats.succesfullPutsCounter.get() > putsAfter5Seconds : "the lock count didn't improve since the first 5 seconds. Deadlock?"; assert stats.succesfullPutsCounter.get() == stats.lockReleasedCounter.get() : "there's a mismatch in acquires and releases count"; assert stats.lockOwnersCounter.get() == 0 : "the lock is still held at test finish"; } private static class StressingThread implements Runnable { private final SharedStats stats; private final ConcurrentMap<String, String> cache; private final String ourValue; public StressingThread(SharedStats stats, ConcurrentMap<String, String> cache, int threadId) { this.stats = stats; this.cache = cache; this.ourValue = "v" + threadId; } @Override public void run() { while (!(stats.seenFailures || stats.globalQuit || Thread.interrupted())) { doCycle(); } } private void doCycle() { String beforePut = cache.putIfAbsent(SHARED_KEY, ourValue); if (beforePut != null) { stats.canceledPutsCounter.incrementAndGet(); } else { final String currentCacheValue = cache.get(SHARED_KEY); boolean lockIsFine = stats.lockOwnersCounter.compareAndSet(0, 1) && ourValue.equals(currentCacheValue); stats.succesfullPutsCounter.incrementAndGet(); checkIsTrue(lockIsFine, "I got the lock, some other thread is owning the lock AS WELL."); lockIsFine = stats.lockOwnersCounter.compareAndSet(1, 0); checkIsTrue(lockIsFine, "Some other thread changed the lock count while I was having it!"); cache.remove(SHARED_KEY); stats.lockReleasedCounter.incrementAndGet(); } } private void checkIsTrue(boolean assertion, String message) { if (assertion == false) { stats.seenFailures = true; System.out.println(message); } } } /** * Common state to verify cache behaviour */ public static class SharedStats { final AtomicInteger canceledPutsCounter = new AtomicInteger(0); final AtomicInteger succesfullPutsCounter = new AtomicInteger(0); final AtomicInteger lockReleasedCounter = new AtomicInteger(0); final AtomicInteger lockOwnersCounter = new AtomicInteger(0); Throwable throwable = null; volatile boolean globalQuit = false; // when it's true the threads quit volatile boolean seenFailures = false; // set to true by a thread if it has experienced // illegal state @Override public String toString() { return "\n\tCanceled puts count:\t" + canceledPutsCounter.get() + "\n\tSuccesfull puts count:\t" + succesfullPutsCounter.get() + "\n\tRemoved count:\t" + lockReleasedCounter.get() + "\n\tIllegal state detected:\t" + seenFailures; } } }
9,852
39.547325
139
java
null
infinispan-main/core/src/test/java/org/infinispan/stress/LargeClusterStressTest.java
package org.infinispan.stress; import static org.infinispan.configuration.cache.CacheMode.DIST_SYNC; import static org.infinispan.configuration.cache.CacheMode.INVALIDATION_SYNC; import static org.infinispan.configuration.cache.CacheMode.LOCAL; import static org.infinispan.configuration.cache.CacheMode.REPL_SYNC; import static org.infinispan.test.TestingUtil.waitForNoRebalance; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.infinispan.Cache; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterTest; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Test that we're able to start a large cluster in a single JVM. * * @author Dan Berindei * @since 5.3 */ @CleanupAfterTest @Test(groups = "stress", testName = "stress.LargeClusterStressTest", timeOut = 15*60*1000) public class LargeClusterStressTest extends MultipleCacheManagersTest { private static final int NUM_NODES = 40; private static final int NUM_CACHES = 20; private static final int NUM_THREADS = NUM_NODES; private static final int NUM_SEGMENTS = 256; private static final EnumSet<CacheMode> cacheModes = EnumSet.of(CacheMode.LOCAL, CacheMode.INVALIDATION_SYNC, DIST_SYNC, REPL_SYNC); @Override protected void createCacheManagers() throws Throwable { // start the cache managers in the test itself } public void testLargeClusterStart() throws Exception { Map<CacheMode, Configuration> configurations = new HashMap<>(); configurations.put(DIST_SYNC, new ConfigurationBuilder() .clustering().cacheMode(DIST_SYNC) .clustering().stateTransfer().awaitInitialTransfer(false) .clustering().hash().numSegments(NUM_SEGMENTS) .build()); configurations.put(REPL_SYNC, new ConfigurationBuilder() .clustering().cacheMode(REPL_SYNC) .clustering().hash().numSegments(NUM_SEGMENTS) .clustering().stateTransfer().awaitInitialTransfer(false) .build()); configurations.put(INVALIDATION_SYNC, new ConfigurationBuilder() .clustering().cacheMode(CacheMode.INVALIDATION_SYNC) .build()); configurations.put(LOCAL, new ConfigurationBuilder() .clustering().cacheMode(LOCAL) .build()); // Start the caches (and the JGroups channels) in separate threads ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS, getTestThreadFactory("Worker")); ExecutorCompletionService<Object> completionService = new ExecutorCompletionService<>(executor); try { for (int i = 0; i < NUM_NODES; i++) { final String nodeName = TestResourceTracker.getNameForIndex(i); // final String machineId = "m" + (i / 2); completionService.submit(() -> { GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder(); gcb.transport().defaultTransport().nodeName(nodeName); // gcb.transport().machineId(machineId); EmbeddedCacheManager cm = new DefaultCacheManager(gcb.build()); try { for (int j = 0; j < NUM_CACHES; j++) { for (CacheMode mode : cacheModes) { cm.defineConfiguration(cacheName(mode, j), configurations.get(mode)); } } for (int j = 0; j < NUM_CACHES; j++) { for (CacheMode mode : cacheModes) { Cache<Object, Object> cache = cm.getCache(cacheName(mode, j)); cache.put(cm.getAddress(), "bla"); } } } finally { registerCacheManager(cm); } log.infof("Started cache manager %s", cm.getAddress()); return null; }); } for (int i = 0; i < NUM_NODES; i++) { completionService.take(); } } finally { executor.shutdownNow(); } log.infof("All %d cache managers started, waiting for state transfer to finish for each cache", NUM_NODES); for (int j = 0; j < NUM_CACHES; j++) { for (CacheMode mode : cacheModes) { if (mode.isClustered()) { waitForClusterToForm(cacheName(mode, j)); } } } } private String cacheName(CacheMode mode, int index) { return mode.toString().toLowerCase() + "-cache-" + index; } @Test(dependsOnMethods = "testLargeClusterStart") public void testLargeClusterStop() { for (int i = 0; i < NUM_NODES; i++) { int killIndex = -1; for (int j = 0; j < cacheManagers.size(); j++) { if (address(j).equals(manager(0).getCoordinator())) { killIndex = j; break; } } log.debugf("Killing coordinator %s", address(killIndex)); manager(killIndex).stop(); cacheManagers.remove(killIndex); if (cacheManagers.size() > 0) { TestingUtil.blockUntilViewsReceived(60000, false, cacheManagers); for (int j = 0; j < NUM_CACHES; j++) { for (CacheMode mode : cacheModes) { if (mode.isClustered()) { waitForNoRebalance(caches(cacheName(mode, j))); } } } } } } @AfterMethod @Override protected void clearContent() throws Throwable { // Do nothing } }
6,196
38.221519
135
java
null
infinispan-main/core/src/test/java/org/infinispan/stress/LargeCluster2StressTest.java
package org.infinispan.stress; import static java.util.concurrent.TimeUnit.SECONDS; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.infinispan.Cache; import org.infinispan.commons.executors.BlockingThreadPoolExecutorFactory; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.distribution.ch.impl.SyncConsistentHashFactory; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.jgroups.JGroupsTransport; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterTest; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.util.concurrent.TimeoutException; import org.jgroups.conf.ConfiguratorFactory; import org.jgroups.conf.ProtocolConfiguration; import org.jgroups.conf.ProtocolStackConfigurator; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Test that we're able to start a cluster with lots of caches in a single JVM. * * @author Dan Berindei * @since 7.2 */ @CleanupAfterTest @Test(groups = "stress", testName = "stress.LargeCluster2StressTest", timeOut = 15*60*1000) public class LargeCluster2StressTest extends MultipleCacheManagersTest { private static final int NUM_NODES = 10; private static final int NUM_CACHES = 100; private static final int NUM_THREADS = 200; private static final int NUM_SEGMENTS = 1000; private static final int TIMEOUT_SECONDS = 180; public static final int JGROUPS_MAX_THREADS = 50; public static final int TRANSPORT_MAX_THREADS = 10; public static final int TRANSPORT_QUEUE_SIZE = 1000; public static final int REMOTE_MAX_THREADS = 50; public static final int REMOTE_QUEUE_SIZE = 0; public static final int STATE_TRANSFER_MAX_THREADS = 10; public static final int STATE_TRANSFER_QUEUE_SIZE = 0; @Override protected void createCacheManagers() throws Throwable { // start the cache managers in the test itself } public void testLargeClusterStart() throws Exception { if ((NUM_CACHES & 1) != 0) throw new IllegalStateException("NUM_CACHES must be even"); final ProtocolStackConfigurator configurator = ConfiguratorFactory.getStackConfigurator("default-configs/default-jgroups-udp.xml"); ProtocolConfiguration udpConfiguration = configurator.getProtocolStack().get(0); assertEquals("UDP", udpConfiguration.getProtocolName()); udpConfiguration.getProperties().put("mcast_addr", "239.0.0.15"); udpConfiguration.getProperties().put("thread_pool.min_threads", "0"); udpConfiguration.getProperties().put("thread_pool.max_threads", String.valueOf(JGROUPS_MAX_THREADS)); ProtocolConfiguration gmsConfiguration = configurator.getProtocolStack().get(9); assertEquals("pbcast.GMS", gmsConfiguration.getProtocolName()); gmsConfiguration.getProperties().put("join_timeout", "2000"); final Configuration distConfig = new ConfigurationBuilder() .clustering().cacheMode(CacheMode.DIST_SYNC) .clustering().stateTransfer().awaitInitialTransfer(false) // .hash().consistentHashFactory(new TopologyAwareSyncConsistentHashFactory()).numSegments(NUM_SEGMENTS) .hash().consistentHashFactory(new SyncConsistentHashFactory()).numSegments(NUM_SEGMENTS) .build(); final Configuration replConfig = new ConfigurationBuilder() .clustering().cacheMode(CacheMode.REPL_SYNC) .clustering().hash().numSegments(NUM_SEGMENTS) .clustering().stateTransfer().awaitInitialTransfer(false) .build(); // Start the caches (and the JGroups channels) in separate threads final CountDownLatch managersLatch = new CountDownLatch(NUM_NODES); ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS, getTestThreadFactory("Worker")); final ExecutorCompletionService<Void> managerCompletionService = new ExecutorCompletionService<>(executor); // final ExecutorCompletionService<Void> cacheCompletionService = new ExecutorCompletionService<Void>(new WithinThreadExecutor()); final ExecutorCompletionService<Void> cacheCompletionService = new ExecutorCompletionService<Void>(executor); try { for (int nodeIndex = 0; nodeIndex < NUM_NODES; nodeIndex++) { final String nodeName = TestResourceTracker.getNameForIndex(nodeIndex); final String machineId = "m" + (nodeIndex / 2); managerCompletionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder(); gcb.transport().defaultTransport().nodeName(nodeName) .addProperty(JGroupsTransport.CONFIGURATION_STRING, configurator.getProtocolStackString()); BlockingThreadPoolExecutorFactory transportExecutorFactory = new BlockingThreadPoolExecutorFactory( TRANSPORT_MAX_THREADS, TRANSPORT_MAX_THREADS, TRANSPORT_QUEUE_SIZE, 60000); gcb.transport().transportThreadPool().threadPoolFactory(transportExecutorFactory); BlockingThreadPoolExecutorFactory remoteExecutorFactory = new BlockingThreadPoolExecutorFactory( REMOTE_MAX_THREADS, REMOTE_MAX_THREADS, REMOTE_QUEUE_SIZE, 60000); gcb.transport().remoteCommandThreadPool().threadPoolFactory(remoteExecutorFactory); BlockingThreadPoolExecutorFactory stateTransferExecutorFactory = new BlockingThreadPoolExecutorFactory( STATE_TRANSFER_MAX_THREADS, STATE_TRANSFER_MAX_THREADS, STATE_TRANSFER_QUEUE_SIZE, 60000); gcb.transport().stateTransferThreadPool().threadPoolFactory(stateTransferExecutorFactory); final EmbeddedCacheManager cm = new DefaultCacheManager(gcb.build()); try { for (int i = 0; i < NUM_CACHES / 2; i++) { final int cacheIndex = i; cm.defineConfiguration("repl-cache-" + cacheIndex, replConfig); cm.defineConfiguration("dist-cache-" + cacheIndex, distConfig); cacheCompletionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { String cacheName = "repl-cache-" + cacheIndex; Thread.currentThread().setName(cacheName + "-start-thread," + nodeName); Cache<Object, Object> replCache = cm.getCache(cacheName); // replCache.put(cm.getAddress(), "bla"); return null; } }); cacheCompletionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { String cacheName = "dist-cache-" + cacheIndex; Thread.currentThread().setName(cacheName + "-start-thread," + nodeName); Cache<Object, Object> distCache = cm.getCache(cacheName); // distCache.put(cm.getAddress(), "bla"); return null; } }); managersLatch.countDown(); } } finally { registerCacheManager(cm); } log.infof("Started cache manager %s", nodeName); return null; } }); } long endTime = System.nanoTime() + SECONDS.toNanos(TIMEOUT_SECONDS); for (int i = 0; i < NUM_NODES; i++) { Future<Void> future = managerCompletionService.poll(TIMEOUT_SECONDS, SECONDS); future.get(0, SECONDS); if (System.nanoTime() - endTime > 0) { throw new TimeoutException("Took too long to start the cluster"); } } int i = 0; while (i < NUM_NODES * NUM_CACHES) { Future<Void> future = cacheCompletionService.poll(1, SECONDS); if (future != null) { future.get(0, SECONDS); i++; } if (System.nanoTime() - endTime > 0) { throw new TimeoutException("Took too long to start the cluster"); } } } finally { executor.shutdownNow(); } log.infof("All %d cache managers started, waiting for state transfer to finish for each cache", NUM_NODES); for (int j = 0; j < NUM_CACHES/2; j++) { waitForClusterToForm("repl-cache-" + j); waitForClusterToForm("dist-cache-" + j); } } @Test(dependsOnMethods = "testLargeClusterStart") public void testLargeClusterStop() { for (int i = 0; i < NUM_NODES - 1; i++) { int killIndex = -1; for (int j = 0; j < cacheManagers.size(); j++) { if (address(j).equals(manager(0).getCoordinator())) { killIndex = j; break; } } log.debugf("Killing coordinator %s", address(killIndex)); manager(killIndex).stop(); cacheManagers.remove(killIndex); if (cacheManagers.size() > 0) { TestingUtil.blockUntilViewsReceived(60000, false, cacheManagers); for (int j = 0; j < NUM_CACHES/2; j++) { TestingUtil.waitForNoRebalance(caches("repl-cache-" + j)); TestingUtil.waitForNoRebalance(caches("dist-cache-" + j)); } } } } @AfterMethod @Override protected void clearContent() throws Throwable { // Do nothing } }
10,518
47.925581
137
java
null
infinispan-main/core/src/test/java/org/infinispan/stress/ReplGetStressTest.java
package org.infinispan.stress; import static org.testng.AssertJUnit.assertNull; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * Test the performance of get operations in a replicated cache * * @author Dan Berindei * @since 7.0 */ @Test(groups = "stress", testName = "stress.ReplGetStressTest", timeOut = 15*60*1000) public class ReplGetStressTest extends MultipleCacheManagersTest { private static final int NUM_NODES = 4; private static final int NUM_ITERATIONS = Integer.getInteger("operationsCount", 10); private static final boolean explicitTxs = Boolean.getBoolean("explicitTxs"); protected void createCacheManagers() throws Throwable { // start the cache managers in the test itself } public void testStressGetEmptyCache() throws Exception { long start = System.nanoTime(); ConfigurationBuilder replConfig = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); for (int i = 0; i < NUM_NODES; i++) { EmbeddedCacheManager cm = addClusterEnabledCacheManager(); defineConfigurationOnAllManagers("repl", replConfig); cm.startCaches("repl"); } System.out.println("Caches created: " + manager(0).getMembers()); System.out.println("Explicit txs: " + explicitTxs); System.out.println("Operation count: " + NUM_ITERATIONS + "m"); // Test the performance of get operations in an empty cache Cache<Object, Object> replCache0 = cache(0, "repl"); for (int i = 0; i < NUM_ITERATIONS * 1000000; i++) { if (explicitTxs) tm(0, "repl").begin(); Object o = replCache0.get("k" + i); assertNull(o); if (explicitTxs) tm(0, "repl").commit(); } long end = System.nanoTime(); System.out.println("Test took " + TimeUnit.NANOSECONDS.toSeconds(end - start) + "s"); } }
2,118
36.839286
98
java
null
infinispan-main/core/src/test/java/org/infinispan/stress/AsyncStoreStressTest.java
package org.infinispan.stress; import static java.lang.Math.sqrt; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.commons.io.ByteBufferFactoryImpl; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.time.DefaultTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.IntSets; import org.infinispan.commons.util.ProcessorInfo; import org.infinispan.commons.util.Util; import org.infinispan.commons.util.concurrent.BlockingRejectedExecutionHandler; import org.infinispan.commons.util.concurrent.NonBlockingRejectedExecutionHandler; import org.infinispan.configuration.cache.SingleFileStoreConfiguration; import org.infinispan.configuration.cache.StoreConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.container.impl.InternalEntryFactoryImpl; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.distribution.ch.impl.SingleSegmentKeyPartitioner; import org.infinispan.factories.KnownComponentNames; import org.infinispan.factories.impl.TestComponentAccessors; import org.infinispan.factories.threads.DefaultThreadFactory; import org.infinispan.factories.threads.NonBlockingThreadFactory; import org.infinispan.marshall.TestObjectStreamMarshaller; import org.infinispan.marshall.persistence.impl.MarshalledEntryFactoryImpl; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.persistence.DummyInitializationContext; import org.infinispan.persistence.PersistenceUtil; import org.infinispan.persistence.async.AsyncNonBlockingStore; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfiguration; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.file.SingleFileStore; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.NonBlockingStore; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.util.concurrent.BlockingManagerImpl; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.concurrent.locks.impl.LockContainer; import org.infinispan.util.concurrent.locks.impl.PerKeyLockContainer; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.mockito.Mockito; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Async store stress test. * * // TODO: Add a test to verify clear() too! * * @author Galder Zamarreño * @since 5.2 */ @Test(testName = "stress.AsyncStoreStressTest", groups = "stress") public class AsyncStoreStressTest extends AbstractInfinispanTest { static final Log log = LogFactory.getLog(AsyncStoreStressTest.class); static final int CAPACITY = Integer.getInteger("size", 100000); static final int LOOP_FACTOR = 10; static final long RUNNING_TIME = Integer.getInteger("time", 1) * 60 * 1000; static final Random RANDOM = new Random(12345); private volatile CountDownLatch latch; private List<String> keys = new ArrayList<>(); private InternalEntryFactory entryFactory = new InternalEntryFactoryImpl(); private Map<Object, InternalCacheEntry> expectedState = new ConcurrentHashMap<Object, InternalCacheEntry>(); private TestObjectStreamMarshaller marshaller; private ExecutorService nonBlockingExecutor; private ExecutorService blockingExecutor; private TimeService timeService; protected String location; @BeforeClass(alwaysRun = true) void startMarshaller() { marshaller = new TestObjectStreamMarshaller(); location = CommonsTestingUtil.tmpDirectory(this.getClass()); nonBlockingExecutor = new ThreadPoolExecutor(0, ProcessorInfo.availableProcessors() * 2, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(KnownComponentNames.getDefaultQueueSize(KnownComponentNames.NON_BLOCKING_EXECUTOR)), new NonBlockingThreadFactory("ISPN-non-blocking-thread-group", Thread.NORM_PRIORITY, DefaultThreadFactory.DEFAULT_PATTERN, "Test", "non-blocking"), NonBlockingRejectedExecutionHandler.getInstance()); blockingExecutor = new ThreadPoolExecutor(0, 150, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(KnownComponentNames.getDefaultQueueSize(KnownComponentNames.BLOCKING_EXECUTOR)), getTestThreadFactory("Blocking"), BlockingRejectedExecutionHandler.getInstance()); PerKeyLockContainer lockContainer = new PerKeyLockContainer(); TestingUtil.inject(lockContainer, new DefaultTimeService()); locks = lockContainer; timeService = new DefaultTimeService(); TestingUtil.inject(locks, timeService, nonBlockingExecutor); } @AfterClass(alwaysRun = true) void stopMarshaller() throws InterruptedException { marshaller.stop(); Util.recursiveFileRemove(location); if (nonBlockingExecutor != null) { nonBlockingExecutor.shutdown(); nonBlockingExecutor.awaitTermination(10, TimeUnit.SECONDS); } if (blockingExecutor != null) { blockingExecutor.shutdown(); blockingExecutor.awaitTermination(10, TimeUnit.SECONDS); } } // Lock container that mimics per-key locking produced by the cache. // This per-key lock holder provides guarantees that the final expected // state has not been affected by ordering issues such as this: // // (Thread-200:) Enqueuing modification Store{storedEntry= // ImmortalCacheEntry{key=key165168, value=ImmortalCacheValue {value=60483}}} // (Thread-194:) Enqueuing modification Store{storedEntry= // ImmortalCacheEntry{key=key165168, value=ImmortalCacheValue {value=61456}}} // (Thread-194:) Expected state updated with key=key165168, value=61456 // (Thread-200:) Expected state updated with key=key165168, value=60483 private LockContainer locks; private AsyncNonBlockingStore<Object, Object> createDummyAsyncStore() { DummyInMemoryStoreConfiguration dummyConfiguration = TestCacheManagerFactory .getDefaultCacheConfiguration(false) .persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .segmented(false) .storeName("async2") .create(); return createAsyncStore(new DummyInMemoryStore(), dummyConfiguration); } private AsyncNonBlockingStore<Object, Object> createFileAsyncStore() { SingleFileStoreConfiguration singleFileStoreConfiguration = TestCacheManagerFactory .getDefaultCacheConfiguration(false) .persistence() .addSingleFileStore() .location(location) .segmented(false) .create(); return createAsyncStore(new SingleFileStore<>(), singleFileStoreConfiguration); } private AsyncNonBlockingStore<Object, Object> createAsyncStore(NonBlockingStore backendStore, StoreConfiguration storeConfiguration) throws PersistenceException { AsyncNonBlockingStore<Object, Object> store = new AsyncNonBlockingStore<>(backendStore); BlockingManager blockingManager = new BlockingManagerImpl(); TestingUtil.inject(blockingManager, new TestComponentAccessors.NamedComponent(KnownComponentNames.NON_BLOCKING_EXECUTOR, nonBlockingExecutor), new TestComponentAccessors.NamedComponent(KnownComponentNames.BLOCKING_EXECUTOR, blockingExecutor)); TestingUtil.startComponent(blockingManager); Cache cacheMock = Mockito.mock(Cache.class, Mockito.RETURNS_DEEP_STUBS); Mockito.when(cacheMock.getAdvancedCache().getComponentRegistry().getComponent(KeyPartitioner.class)) .thenReturn(SingleSegmentKeyPartitioner.getInstance()); CompletionStages.join(store.start(new DummyInitializationContext(storeConfiguration, cacheMock, marshaller, new ByteBufferFactoryImpl(), new MarshalledEntryFactoryImpl(marshaller), nonBlockingExecutor, new GlobalConfigurationBuilder().globalState().persistentLocation(location).build(), blockingManager, null, new DefaultTimeService()))); return store; } private Map<String, AsyncNonBlockingStore<Object, Object>> createAsyncStores() throws PersistenceException { Map<String, AsyncNonBlockingStore<Object, Object>> stores = new TreeMap<>(); stores.put("Dummy-ASYNC", createDummyAsyncStore()); stores.put("File-ASYNC", createFileAsyncStore()); return stores; } @DataProvider(name = "readWriteRemove") public Object[][] independentReadWriteRemoveParams() { return new Object[][]{ new Object[]{CAPACITY, 3 * CAPACITY, 9, 20, 1}, new Object[]{CAPACITY, 3 * CAPACITY, 90, 1, 0}, }; } @Test(dataProvider = "readWriteRemove") public void testReadWriteRemove(int capacity, int numKeys, int readerThreads, int writerThreads, int removerThreads) throws Exception { System.out.printf("Testing independent read/write/remove performance " + "with capacity %d, keys %d, readers %d, writers %d, removers %d\n", capacity, numKeys, readerThreads, writerThreads, removerThreads); generateKeyList(numKeys); Map<String, AsyncNonBlockingStore<Object, Object>> stores = createAsyncStores(); try { for (Map.Entry<String, AsyncNonBlockingStore<Object, Object>> e : stores.entrySet()) { mapTestReadWriteRemove(e.getKey(), e.getValue(), numKeys, readerThreads, writerThreads, removerThreads); } } finally { for (Iterator<AsyncNonBlockingStore<Object, Object>> it = stores.values().iterator(); it.hasNext(); ) { AsyncNonBlockingStore<Object, Object> store = it.next(); try { CompletionStages.join(store.stop()); it.remove(); } catch (Exception ex) { log.error("Failed to stop cache store", ex); } } } assertTrue("Not all stores were properly shut down", stores.isEmpty()); } private void mapTestReadWriteRemove(String name, AsyncNonBlockingStore<Object, Object> store, int numKeys, int readerThreads, int writerThreads, int removerThreads) throws Exception { NonBlockingStore<Object, Object> delegate = store.delegate(); try { // warm up for 1 second System.out.printf("[store=%s] Warming up\n", name); runMapTestReadWriteRemove(name, store, readerThreads, writerThreads, removerThreads, 1000); // real test System.out.printf("[store=%s] Testing...\n", name); TotalStats perf = runMapTestReadWriteRemove(name, store, readerThreads, writerThreads, removerThreads, RUNNING_TIME); // Wait until the cache store contains the expected state System.out.printf("[store=%s] Verify contents\n", name); eventually(() -> "Store contains: " + PersistenceUtil.toKeySet(delegate, IntSets.immutableSet(0), null) + " but expected: " + expectedState.keySet() ,() -> PersistenceUtil.toKeySet(delegate, IntSets.immutableSet(0), null).equals(expectedState.keySet())); System.out.printf("Container %-12s ", name); System.out.printf("Ops/s %10.2f ", perf.getTotalOpsPerSec()); System.out.printf("Gets/s %10.2f ", perf.getOpsPerSec("GET")); System.out.printf("Puts/s %10.2f ", perf.getOpsPerSec("PUT")); System.out.printf("Removes/s %10.2f ", perf.getOpsPerSec("REMOVE")); System.out.printf("HitRatio %10.2f ", perf.getTotalHitRatio() * 100); System.out.printf("Size %10d ", CompletionStages.join(store.size(IntSets.immutableSet(0))), null); double stdDev = computeStdDev(store, numKeys); System.out.printf("StdDev %10.2f\n", stdDev); } finally { // Clean up state, expected state and keys expectedState.clear(); CompletionStages.join(delegate.clear()); } } private TotalStats runMapTestReadWriteRemove(String name, final NonBlockingStore<Object, Object> store, int numReaders, int numWriters, int numRemovers, final long runningTimeout) throws Exception { latch = new CountDownLatch(1); final TotalStats perf = new TotalStats(); List<Thread> threads = new LinkedList<Thread>(); for (int i = 0; i < numReaders; i++) { Thread reader = new WorkerThread("worker-" + name + "-get-" + i, runningTimeout, perf, readOperation(store)); threads.add(reader); } for (int i = 0; i < numWriters; i++) { Thread writer = new WorkerThread("worker-" + name + "-put-" + i, runningTimeout, perf, writeOperation(store)); threads.add(writer); } for (int i = 0; i < numRemovers; i++) { Thread remover = new WorkerThread("worker-" + name + "-remove-" + i, runningTimeout, perf, removeOperation(store)); threads.add(remover); } for (Thread t : threads) t.start(); latch.countDown(); for (Thread t : threads) t.join(); return perf; } private void generateKeyList(int numKeys) { // without this we keep getting OutOfMemoryErrors keys = null; keys = new ArrayList<String>(numKeys * LOOP_FACTOR); for (int i = 0; i < numKeys * LOOP_FACTOR; i++) { keys.add("key" + nextIntGaussian(numKeys)); } } private int nextIntGaussian(int numKeys) { double gaussian = RANDOM.nextGaussian(); if (gaussian < -3 || gaussian > 3) return nextIntGaussian(numKeys); return (int) Math.abs((gaussian + 3) * numKeys / 6); } private void waitForStart() { try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } private Operation<String, Integer> readOperation(final NonBlockingStore<Object, Object> store) { return new Operation<String, Integer>("GET") { @Override public boolean call(String key, long run) { MarshallableEntry me = CompletionStages.join(store.load(0, key)); if (log.isTraceEnabled()) log.tracef("Loaded key=%s, value=%s", key, me != null ? me.getValue() : "null"); return me != null; } }; } private Operation<String, Integer> writeOperation(final NonBlockingStore<Object, Object> store) { return new Operation<String, Integer>("PUT") { @Override public boolean call(final String key, long run) { final int value = (int) run; final InternalCacheEntry entry = entryFactory.create(key, value, new EmbeddedMetadata.Builder().build()); // Store acquiring locks and catching exceptions return withKeyLock(key, () -> { CompletionStages.join(store.write(0, MarshalledEntryUtil.create(entry, marshaller))); expectedState.put(key, entry); if (log.isTraceEnabled()) log.tracef("Expected state updated with key=%s, value=%s", key, value); return true; }); } }; } private Operation<String, Integer> removeOperation(final NonBlockingStore<Object, Object> store) { return new Operation<String, Integer>("REMOVE") { @Override public boolean call(final String key, long run) { // Remove acquiring locks and catching exceptions return withKeyLock(key, () -> { Boolean removed = CompletionStages.join(store.delete(0, key)); assertNull(removed); expectedState.remove(key); if (log.isTraceEnabled()) log.tracef("Expected state removed key=%s", key); return true; }); } }; } private boolean withKeyLock(String key, Callable<Boolean> call) { boolean result = false; try { locks.acquire(key, Thread.currentThread(), 5, TimeUnit.SECONDS).lock(); result = call.call(); } catch (Exception e) { //ignored e.printStackTrace(); } finally { locks.release(key, Thread.currentThread()); } return result; } private double computeStdDev(NonBlockingStore store, int numKeys) throws PersistenceException { // The keys closest to the mean are suposed to be accessed more often // So we score each map by the standard deviation of the keys in the map // at the end of the test double variance = 0; Set<Object> keys = PersistenceUtil.toKeySet(store, IntSets.immutableSet(0), null); for (Object key : keys) { double value = Integer.parseInt(((String )key).substring(3)); variance += (value - numKeys / 2) * (value - numKeys / 2); } return sqrt(variance / keys.size()); } private class WorkerThread extends Thread { private final long runningTimeout; private final TotalStats perf; private Operation<String, Integer> op; public WorkerThread(String name, long runningTimeout, TotalStats perf, Operation<String, Integer> op) { super(name); this.runningTimeout = runningTimeout; this.perf = perf; this.op = op; } public void run() { waitForStart(); long startMilis = System.currentTimeMillis(); long endMillis = startMilis + runningTimeout; int keyIndex = RANDOM.nextInt(keys.size()); long runs = 0; long missCount = 0; while ((runs & 0x3FFF) != 0 || System.currentTimeMillis() < endMillis) { boolean hit = op.call(keys.get(keyIndex), runs); if (!hit) missCount++; keyIndex++; runs++; if (keyIndex >= keys.size()) { keyIndex = 0; } } perf.addStats(op.getName(), runs, System.currentTimeMillis() - startMilis, missCount); } } private static abstract class Operation<K, V> { protected final String name; public Operation(String name) { this.name = name; } /** * @return Return true for a hit, false for a miss. */ public abstract boolean call(K key, long run); public String getName() { return name; } } private static class TotalStats { private ConcurrentHashMap<String, OpStats> statsMap = new ConcurrentHashMap<String, OpStats>(); public void addStats(String opName, long opCount, long runningTime, long missCount) { OpStats s = new OpStats(opName, opCount, runningTime, missCount); OpStats old = statsMap.putIfAbsent(opName, s); boolean replaced = old == null; while (!replaced) { old = statsMap.get(opName); s = new OpStats(old, opCount, runningTime, missCount); replaced = statsMap.replace(opName, old, s); } } public double getOpsPerSec(String opName) { OpStats s = statsMap.get(opName); if (s == null) return 0; return s.opCount * 1000. / s.runningTime * s.threadCount; } public double getTotalOpsPerSec() { long totalOpCount = 0; long totalRunningTime = 0; long totalThreadCount = 0; for (Map.Entry<String, OpStats> e : statsMap.entrySet()) { OpStats s = e.getValue(); totalOpCount += s.opCount; totalRunningTime += s.runningTime; totalThreadCount += s.threadCount; } return totalOpCount * 1000. / totalRunningTime * totalThreadCount; } public double getHitRatio(String opName) { OpStats s = statsMap.get(opName); if (s == null) return 0; return 1 - 1. * s.missCount / s.opCount; } public double getTotalHitRatio() { long totalOpCount = 0; long totalMissCount = 0; for (Map.Entry<String, OpStats> e : statsMap.entrySet()) { OpStats s = e.getValue(); totalOpCount += s.opCount; totalMissCount += s.missCount; } return 1 - 1. * totalMissCount / totalOpCount; } } private static class OpStats { public final String opName; public final int threadCount; public final long opCount; public final long runningTime; public final long missCount; private OpStats(String opName, long opCount, long runningTime, long missCount) { this.opName = opName; this.threadCount = 1; this.opCount = opCount; this.runningTime = runningTime; this.missCount = missCount; } private OpStats(OpStats base, long opCount, long runningTime, long missCount) { this.opName = base.opName; this.threadCount = base.threadCount + 1; this.opCount = base.opCount + opCount; this.runningTime = base.runningTime + runningTime; this.missCount = base.missCount + missCount; } } @Test(enabled = false) // Disable explicitly to avoid TestNG thinking this is a test!! public static void main(String[] args) throws Exception { AsyncStoreStressTest test = new AsyncStoreStressTest(); test.testReadWriteRemove(100000, 300000, 90, 9, 1); test.testReadWriteRemove(10000, 30000, 9, 1, 0); System.exit(0); } }
22,544
40.98324
165
java
null
infinispan-main/core/src/test/java/org/infinispan/stress/DistWriteSkewStressTest.java
package org.infinispan.stress; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; /** * @author Pedro Ruivo * @since 7.0 */ @Test(testName = "stress.DistWriteSkewStressTest", groups = "stress") public class DistWriteSkewStressTest extends AbstractWriteSkewStressTest { @Override protected CacheMode getCacheMode() { return CacheMode.DIST_SYNC; } }
408
20.526316
74
java
null
infinispan-main/core/src/test/java/org/infinispan/stress/DistL1WriteSkewStressTest.java
package org.infinispan.stress; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author Pedro Ruivo * @since 7.0 */ @Test(testName = "stress.DistL1WriteSkewStressTest", groups = "stress") public class DistL1WriteSkewStressTest extends DistWriteSkewStressTest { @Override protected void decorate(ConfigurationBuilder builder) { // Enable L1 builder.clustering().l1().enable(); builder.clustering().remoteTimeout(100, TimeUnit.MINUTES); } }
568
24.863636
72
java
null
infinispan-main/core/src/test/java/org/infinispan/stress/MapStressTest.java
package org.infinispan.stress; import static java.lang.Math.sqrt; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.benmanes.caffeine.cache.Caffeine; /** * Stress test different maps for container implementations * * @author Manik Surtani * @author Dan Berindei &lt;dberinde@redhat.com&gt; * @since 4.0 */ @Test(testName = "stress.MapStressTest", groups = "profiling") public class MapStressTest extends SingleCacheManagerTest { private static Log log = LogFactory.getLog(MapStressTest.class); static final float MAP_LOAD_FACTOR = 0.75f; static final int LOOP_FACTOR = 10; static final long RUNNING_TIME = Integer.getInteger("time", 30) * 1000; final int CAPACITY = Integer.getInteger("size", 100000); private static final Random RANDOM = new Random(12345); private volatile CountDownLatch latch; private List<String> keys = new ArrayList<String>(); public MapStressTest() { log.tracef("MapStressTest configuration: capacity %d, test running time %d seconds\n", CAPACITY, RUNNING_TIME / 1000); } private void generateKeyList(int numKeys) { // without this we keep getting OutOfMemoryErrors keys = null; keys = new ArrayList<String>(numKeys * LOOP_FACTOR); for (int i = 0; i < numKeys * LOOP_FACTOR; i++) { keys.add("key" + nextIntGaussian(numKeys)); } } private int nextIntGaussian(int numKeys) { double gaussian = RANDOM.nextGaussian(); if (gaussian < -3 || gaussian > 3) return nextIntGaussian(numKeys); return (int) Math.abs((gaussian + 3) * numKeys / 6); } private Map<String, Integer> synchronizedLinkedHashMap(final int capacity, float loadFactor) { return Collections.synchronizedMap(new LinkedHashMap<String, Integer>(capacity, loadFactor, true) { @Override protected boolean removeEldestEntry(Entry<String, Integer> eldest) { return size() > capacity; } }); } private Cache<String, Integer> configureAndBuildCache(int capacity) { ConfigurationBuilder config = new ConfigurationBuilder(); config .memory().size(capacity) .expiration().wakeUpInterval(5000L).maxIdle(120000L); String cacheName = "cache" + capacity; cacheManager.defineConfiguration(cacheName, config.build()); return cacheManager.getCache(cacheName); } @DataProvider(name = "readWriteRemove") public Object[][] independentReadWriteRemoveParams() { return new Object[][]{ new Object[]{CAPACITY, 3 * CAPACITY, 32, 90, 9, 3}, new Object[]{CAPACITY, 3 * CAPACITY, 32, 9, 1, 1}, }; } @DataProvider(name = "readOnly") public Object[][] readOnly() { return new Object[][]{ new Object[]{CAPACITY, CAPACITY * 3 / 2, 32, 100}, new Object[]{CAPACITY, CAPACITY * 3 / 2, 32, 10}, }; } @DataProvider(name = "readWriteRatio") public Object[][] readWriteRatioParams() { return new Object[][]{ new Object[]{CAPACITY, 3 * CAPACITY, 32, 100, 9}, new Object[]{CAPACITY, 3 * CAPACITY, 32, 10, 9}, }; } @DataProvider(name = "writeOnMiss") public Object[][] writeOnMissParams() { return new Object[][]{ new Object[]{CAPACITY, 3 * CAPACITY, 32, 100}, new Object[]{CAPACITY, 3 * CAPACITY, 32, 10}, }; } private Map<String, Map<String, Integer>> createMaps(int capacity, int numKeys, int concurrency) { Map<String, Map<String, Integer>> maps = new TreeMap<String, Map<String, Integer>>(); com.github.benmanes.caffeine.cache.Cache<String, Integer> caffeineCache = Caffeine.newBuilder().maximumSize(capacity).build(); maps.put("Caffeine", caffeineCache.asMap()); // CHM doesn't have eviction, so we size it to the capacity to allow for dynamic resize maps.put("CHM", new ConcurrentHashMap<String, Integer>(capacity, MAP_LOAD_FACTOR, concurrency)); maps.put("SLHM", synchronizedLinkedHashMap(capacity, MAP_LOAD_FACTOR)); maps.put("CACHE", configureAndBuildCache(capacity)); return maps; } @Test(dataProvider = "readWriteRemove") public void testReadWriteRemove(int capacity, int numKeys, int concurrency, int readerThreads, int writerThreads, int removerThreads) throws Exception { System.out.printf("Testing independent read/write/remove performance with capacity %d, keys %d, concurrency level %d, readers %d, writers %d, removers %d\n", capacity, numKeys, concurrency, readerThreads, writerThreads, removerThreads); generateKeyList(numKeys); Map<String, Map<String, Integer>> maps = createMaps(capacity, numKeys, concurrency); for (Entry<String, Map<String, Integer>> e : maps.entrySet()) { mapTestReadWriteRemove(e.getKey(), e.getValue(), numKeys, readerThreads, writerThreads, removerThreads); e.setValue(null); } } private void mapTestReadWriteRemove(String name, Map<String, Integer> map, int numKeys, int readerThreads, int writerThreads, int removerThreads) throws Exception { // warm up for 1 second runMapTestReadWriteRemove(map, readerThreads, writerThreads, removerThreads, 1000); // real test TotalStats perf = runMapTestReadWriteRemove(map, readerThreads, writerThreads, removerThreads, RUNNING_TIME); System.out.printf("Container %-12s ", name); System.out.printf("Ops/s %10.2f ", perf.getTotalOpsPerSec()); System.out.printf("Gets/s %10.2f ", perf.getOpsPerSec("GET")); System.out.printf("Puts/s %10.2f ", perf.getOpsPerSec("PUT")); System.out.printf("Removes/s %10.2f ", perf.getOpsPerSec("REMOVE")); System.out.printf("HitRatio %10.2f ", perf.getTotalHitRatio() * 100); System.out.printf("Size %10d ", map.size()); double stdDev = computeStdDev(map, numKeys); System.out.printf("StdDev %10.2f\n", stdDev); } private TotalStats runMapTestReadWriteRemove(final Map<String, Integer> map, int numReaders, int numWriters, int numRemovers, final long runningTimeout) throws Exception { latch = new CountDownLatch(1); final TotalStats perf = new TotalStats(); List<Thread> threads = new LinkedList<Thread>(); for (int i = 0; i < numReaders; i++) { Thread reader = new WorkerThread(runningTimeout, perf, readOperation(map)); threads.add(reader); } for (int i = 0; i < numWriters; i++) { Thread writer = new WorkerThread(runningTimeout, perf, writeOperation(map)); threads.add(writer); } for (int i = 0; i < numRemovers; i++) { Thread remover = new WorkerThread(runningTimeout, perf, removeOperation(map)); threads.add(remover); } for (Thread t : threads) t.start(); latch.countDown(); for (Thread t : threads) { t.join(); } return perf; } @Test(dataProvider = "readOnly") public void testReadOnly(int capacity, int numKeys, int concurrency, int threads) throws Exception { System.out.printf("Testing read only performance with capacity %d, keys %d, concurrency level %d, threads %d\n", capacity, numKeys, concurrency, threads); generateKeyList(numKeys); Map<String, Map<String, Integer>> maps = createMaps(capacity, numKeys, concurrency); for (Entry<String, Map<String, Integer>> e : maps.entrySet()) { mapTestReadOnly(e.getKey(), e.getValue(), numKeys, threads); e.setValue(null); } } private void mapTestReadOnly(String name, Map<String, Integer> map, int numKeys, int threads) throws Exception { // warm up for 1 second - by doing reads and writes runMapTestMixedReadWrite(map, threads, 9, 1000); // real test TotalStats perf = runMapTestReadOnly(map, threads, RUNNING_TIME); System.out.printf("Container %-12s ", name); System.out.printf("Ops/s %10.2f ", perf.getTotalOpsPerSec()); System.out.printf("Gets/s %10.2f ", perf.getTotalOpsPerSec()); System.out.printf("HitRatio %10.2f ", perf.getTotalHitRatio() * 100); System.out.printf("Size %10d ", map.size()); double stdDev = computeStdDev(map, numKeys); System.out.printf("stdDev %10.2f\n", stdDev); } private TotalStats runMapTestReadOnly(final Map<String, Integer> map, int numThreads, final long runningTimeout) throws Exception { latch = new CountDownLatch(1); final TotalStats perf = new TotalStats(); List<Thread> threads = new LinkedList<Thread>(); for (int i = 0; i < numThreads; i++) { Thread thread = new WorkerThread(runningTimeout, perf, readOperation(map)); threads.add(thread); } for (Thread t : threads) t.start(); latch.countDown(); for (Thread t : threads) t.join(); return perf; } @Test(dataProvider = "readWriteRatio") public void testMixedReadWrite(int capacity, int numKeys, int concurrency, int threads, int readToWriteRatio) throws Exception { System.out.printf("Testing mixed read/write performance with capacity %d, keys %d, concurrency level %d, threads %d, read:write ratio %d:1\n", capacity, numKeys, concurrency, threads, readToWriteRatio); generateKeyList(numKeys); Map<String, Map<String, Integer>> maps = createMaps(capacity, numKeys, concurrency); for (Entry<String, Map<String, Integer>> e : maps.entrySet()) { mapTestMixedReadWrite(e.getKey(), e.getValue(), numKeys, threads, readToWriteRatio); e.setValue(null); } } private void mapTestMixedReadWrite(String name, Map<String, Integer> map, int numKeys, int threads, int readToWriteRatio) throws Exception { // warm up for 1 second runMapTestMixedReadWrite(map, threads, readToWriteRatio, 1000); // real test TotalStats perf = runMapTestMixedReadWrite(map, threads, readToWriteRatio, RUNNING_TIME); System.out.printf("Container %-12s ", name); System.out.printf("Ops/s %10.2f ", perf.getTotalOpsPerSec()); System.out.printf("Gets/s %10.2f ", perf.getTotalOpsPerSec() * readToWriteRatio / (readToWriteRatio + 1)); System.out.printf("Puts/s %10.2f ", perf.getTotalOpsPerSec() * 1 / (readToWriteRatio + 1)); System.out.printf("HitRatio %10.2f ", perf.getTotalHitRatio() * 100); System.out.printf("Size %10d ", map.size()); double stdDev = computeStdDev(map, numKeys); System.out.printf("stdDev %10.2f\n", stdDev); } private TotalStats runMapTestMixedReadWrite(final Map<String, Integer> map, int numThreads, int readToWriteRatio, final long runningTimeout) throws Exception { latch = new CountDownLatch(1); final TotalStats perf = new TotalStats(); List<Thread> threads = new LinkedList<Thread>(); for (int i = 0; i < numThreads; i++) { Thread thread = new WorkerThread(runningTimeout, perf, readWriteOperation(map, readToWriteRatio)); threads.add(thread); } for (Thread t : threads) t.start(); latch.countDown(); for (Thread t : threads) t.join(); return perf; } @Test(dataProvider = "writeOnMiss") public void testWriteOnMiss(int capacity, int numKeys, int concurrency, int threads) throws Exception { System.out.printf("Testing write on miss performance with capacity %d, keys %d, concurrency level %d, threads %d\n", capacity, numKeys, concurrency, threads); generateKeyList(numKeys); Map<String, Map<String, Integer>> maps = createMaps(capacity, numKeys, concurrency); for (Entry<String, Map<String, Integer>> e : maps.entrySet()) { mapTestWriteOnMiss(e.getKey(), e.getValue(), numKeys, threads); e.setValue(null); } } private void mapTestWriteOnMiss(String name, Map<String, Integer> map, int numKeys, int threads) throws Exception { // warm up for 1 second runMapTestWriteOnMiss(map, threads, 1000); // real test TotalStats perf = runMapTestWriteOnMiss(map, threads, RUNNING_TIME); System.out.printf("Container %-12s ", name); System.out.printf("Ops/s %10.2f ", perf.getTotalOpsPerSec()); System.out.printf("HitRatio %10.2f ", perf.getTotalHitRatio() * 100); System.out.printf("Size %10d ", map.size()); double stdDev = computeStdDev(map, numKeys); System.out.printf("stdDev %10.2f\n", stdDev); } private TotalStats runMapTestWriteOnMiss(final Map<String, Integer> map, int numThreads, final long runningTimeout) throws Exception { latch = new CountDownLatch(1); final TotalStats perf = new TotalStats(); List<Thread> threads = new LinkedList<Thread>(); for (int i = 0; i < numThreads; i++) { Thread thread = new WorkerThread(runningTimeout, perf, writeOnMissOperation(map)); threads.add(thread); } for (Thread t : threads) t.start(); latch.countDown(); for (Thread t : threads) t.join(); return perf; } private double computeStdDev(Map<String, Integer> map, int numKeys) { // The keys closest to the mean are suposed to be accessed more often // So we score each map by the standard deviation of the keys in the map // at the end of the test double variance = 0; for (String key : map.keySet()) { double value = Integer.parseInt(key.substring(3)); variance += (value - numKeys / 2) * (value - numKeys / 2); } return sqrt(variance / map.size()); } private void waitForStart() { try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } private Operation<String, Integer> readOperation(Map<String, Integer> map) { return new Operation<String, Integer>(map, "GET") { @Override public boolean call(String key, long run) { return map.get(key) != null; } }; } private Operation<String, Integer> writeOperation(Map<String, Integer> map) { return new Operation<String, Integer>(map, "PUT") { @Override public boolean call(String key, long run) { return map.put(key, (int) run) != null; } }; } private Operation<String, Integer> removeOperation(Map<String, Integer> map) { return new Operation<String, Integer>(map, "REMOVE") { @Override public boolean call(String key, long run) { return map.remove(key) != null; } }; } private Operation<String, Integer> readWriteOperation(final Map<String, Integer> map, final int readToWriteRatio) { return new Operation<String, Integer>(map, "READ/WRITE:" + readToWriteRatio + "/1") { @Override public boolean call(String key, long run) { if (run % (readToWriteRatio + 1) == 0) { return map.put(key, (int)run) != null; } else { return map.get(key) != null; } } }; } private Operation<String, Integer> writeOnMissOperation(final Map<String, Integer> map) { return new Operation<String, Integer>(map, "PUTMISSING") { @Override public boolean call(String key, long run) { boolean hit = map.get(key) != null; if (!hit) { map.put(key, (int)run); } return hit; } }; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.createCacheManager(); } private class WorkerThread extends Thread { private final long runningTimeout; private final TotalStats perf; private Operation<String, Integer> op; public WorkerThread(long runningTimeout, TotalStats perf, Operation<String, Integer> op) { this.runningTimeout = runningTimeout; this.perf = perf; this.op = op; } @Override public void run() { long startMilis = System.currentTimeMillis(); long endMillis = startMilis + runningTimeout; waitForStart(); int keyIndex = RANDOM.nextInt(keys.size()); long runs = 0; long missCount = 0; while ((runs & 0x3FFF) != 0 || System.currentTimeMillis() < endMillis) { boolean hit = op.call(keys.get(keyIndex), runs); if (!hit) missCount++; keyIndex++; runs++; if (keyIndex >= keys.size()) { keyIndex = 0; } } perf.addStats(op.getName(), runs, System.currentTimeMillis() - startMilis, missCount); } } private static abstract class Operation<K, V> { protected final Map<K, V> map; protected final String name; public Operation(Map<K, V> map, String name) { this.map = map; this.name = name; } /** * @return Return true for a hit, false for a miss. */ public abstract boolean call(K key, long run); public String getName() { return name; } } private static class TotalStats { private ConcurrentHashMap<String, OpStats> statsMap = new ConcurrentHashMap<String, OpStats>(); public void addStats(String opName, long opCount, long runningTime, long missCount) { OpStats s = new OpStats(opName, opCount, runningTime, missCount); OpStats old = statsMap.putIfAbsent(opName, s); boolean replaced = old == null; while (!replaced) { old = statsMap.get(opName); s = new OpStats(old, opCount, runningTime, missCount); replaced = statsMap.replace(opName, old, s); } } public double getOpsPerSec(String opName) { OpStats s = statsMap.get(opName); if (s == null) return 0; return s.opCount * 1000. / s.runningTime * s.threadCount; } public double getTotalOpsPerSec() { long totalOpCount = 0; long totalRunningTime = 0; long totalThreadCount = 0; for (Map.Entry<String, OpStats> e : statsMap.entrySet()) { OpStats s = e.getValue(); totalOpCount += s.opCount; totalRunningTime += s.runningTime; totalThreadCount += s.threadCount; } return totalOpCount * 1000. / totalRunningTime * totalThreadCount; } public double getHitRatio(String opName) { OpStats s = statsMap.get(opName); if (s == null) return 0; return 1 - 1. * s.missCount / s.opCount; } public double getTotalHitRatio() { long totalOpCount = 0; long totalMissCount = 0; for (Map.Entry<String, OpStats> e : statsMap.entrySet()) { OpStats s = e.getValue(); totalOpCount += s.opCount; totalMissCount += s.missCount; } return 1 - 1. * totalMissCount / totalOpCount; } } private static class OpStats { public final String opName; public final int threadCount; public final long opCount; public final long runningTime; public final long missCount; private OpStats(String opName, long opCount, long runningTime, long missCount) { this.opName = opName; this.threadCount = 1; this.opCount = opCount; this.runningTime = runningTime; this.missCount = missCount; } private OpStats(OpStats base, long opCount, long runningTime, long missCount) { this.opName = base.opName; this.threadCount = base.threadCount + 1; this.opCount = base.opCount + opCount; this.runningTime = base.runningTime + runningTime; this.missCount = base.missCount + missCount; } } }
20,843
36.221429
167
java
null
infinispan-main/core/src/test/java/org/infinispan/stress/DataContainerStressTest.java
package org.infinispan.stress; import java.util.Arrays; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.commons.time.TimeService; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.DefaultDataContainer; import org.infinispan.container.impl.InternalEntryFactoryImpl; import org.infinispan.eviction.EvictionManager; import org.infinispan.eviction.EvictionType; import org.infinispan.eviction.impl.ActivationManagerStub; import org.infinispan.eviction.impl.PassivationManagerStub; import org.infinispan.expiration.impl.InternalExpirationManager; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.metadata.Metadata; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.test.TestingUtil; import org.infinispan.util.EmbeddedTimeService; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.Test; /** * Stress test different data containers * * @author Manik Surtani * @since 4.0 */ @Test(testName = "stress.DataContainerStressTest", groups = "stress", description = "Disabled by default, designed to be run manually.", timeOut = 15*60*1000) public class DataContainerStressTest { volatile CountDownLatch latch; final int RUN_TIME_MILLIS = 45 * 1000; // 1 min final int WARMUP_TIME_MILLIS = 10 * 1000; // 10 sec final int num_loops = 10000; final int warmup_num_loops = 10000; boolean use_time = true; final int NUM_KEYS = 256; private static final Log log = LogFactory.getLog(DataContainerStressTest.class); public void testSimpleDataContainer() throws InterruptedException { DefaultDataContainer dc = DefaultDataContainer.unBoundedDataContainer(5000); initializeDefaultDataContainer(dc); doTest(dc); } public void testEntryBoundedDataContainer() throws InterruptedException { DefaultDataContainer dc = DefaultDataContainer.boundedDataContainer(5000, NUM_KEYS - NUM_KEYS / 4, EvictionType.COUNT); initializeDefaultDataContainer(dc); doTest(dc); } public void testMemoryBoundedDataContainer() throws InterruptedException { // The key length could be 4 or 5 (90% of the time it will be 5) // The value length could be 6 or 7 (90% of the time it will be 7) DefaultDataContainer dc = DefaultDataContainer.boundedDataContainer(5000, threeQuarterMemorySize(NUM_KEYS, 5, 20), EvictionType.MEMORY); initializeDefaultDataContainer(dc); doTest(dc); } private void initializeDefaultDataContainer(DefaultDataContainer dc) { InternalEntryFactoryImpl entryFactory = new InternalEntryFactoryImpl(); TimeService timeService = new EmbeddedTimeService(); TestingUtil.inject(entryFactory, timeService); // Mockito cannot be used as it will run out of memory from keeping all the invocations, thus we use blank impls TestingUtil.inject(dc, (EvictionManager) (evicted, cmd) -> CompletableFutures.completedNull(), new PassivationManagerStub(), entryFactory, new ActivationManagerStub(), null, timeService, null, new InternalExpirationManager() { @Override public void processExpiration() { } @Override public boolean isEnabled() { return false; } @Override public CompletableFuture<Boolean> entryExpiredInMemory(InternalCacheEntry entry, long currentTime, boolean writeOperation) { return null; } @Override public CompletionStage<Void> handleInStoreExpirationInternal(Object key) { return null; } @Override public CompletionStage<Void> handleInStoreExpirationInternal(MarshallableEntry marshalledEntry) { return null; } @Override public CompletionStage<Boolean> handlePossibleExpiration(InternalCacheEntry entry, int segment, boolean isWrite) { return null; } @Override public void addInternalListener(ExpirationConsumer consumer) { } @Override public void removeInternalListener(Object listener) { } }); } private long threeQuarterMemorySize(int numKeys, int keyLength, int valueLength) { // We are assuming each string base takes up 36 bytes (12 for the array, 8 for the class, 8 for the object itself // & 4 for the inner int (this aligned is 36 bytes). // We assume compressed strings are not enabled (so each character is 2 bytes (UTF-16) // We are also ignoring alignment (which the key length and value length should be aligned to the nearest 8 bytes) long total = numKeys * (32 + keyLength + valueLength); return total - total / 4; } private void doTest(final DataContainer dc) throws InterruptedException { doTest(dc, true); doTest(dc, false); } private void doTest(final DataContainer dc, boolean warmup) throws InterruptedException { latch = new CountDownLatch(1); final byte[] keyFirstBytes = new byte[4]; final Map<String, String> perf = new ConcurrentSkipListMap<String, String>(); final AtomicBoolean run = new AtomicBoolean(true); final int actual_num_loops = warmup ? warmup_num_loops : num_loops; Thread getter = new Thread() { @Override public void run() { ThreadLocalRandom R = ThreadLocalRandom.current(); waitForStart(); long start = System.nanoTime(); int runs = 0; byte[] captureByte = new byte[1]; byte[] key = Arrays.copyOf(keyFirstBytes, 5); while (use_time && run.get() || runs < actual_num_loops) { // if (runs % 100000 == 0) log.info("GET run # " + runs); // TestingUtil.sleepThread(10); R.nextBytes(captureByte); key[4] = captureByte[0]; dc.get(key); runs++; } perf.put("GET", opsPerMS(System.nanoTime() - start, runs)); } }; Thread putter = new Thread() { @Override public void run() { ThreadLocalRandom R = ThreadLocalRandom.current(); waitForStart(); long start = System.nanoTime(); int runs = 0; byte[] captureByte = new byte[1]; byte[] key = Arrays.copyOf(keyFirstBytes, 5); byte[] value = new byte[20]; Metadata metadata = new EmbeddedMetadata.Builder().build(); while (use_time && run.get() || runs < actual_num_loops) { // if (runs % 100000 == 0) log.info("PUT run # " + runs); // TestingUtil.sleepThread(10); R.nextBytes(captureByte); key[4] = captureByte[0]; R.nextBytes(value); dc.put(key, value, metadata); runs++; } perf.put("PUT", opsPerMS(System.nanoTime() - start, runs)); } }; Thread remover = new Thread() { @Override public void run() { ThreadLocalRandom R = ThreadLocalRandom.current(); waitForStart(); long start = System.nanoTime(); int runs = 0; byte[] captureByte = new byte[1]; byte[] key = Arrays.copyOf(keyFirstBytes, 5); while (use_time && run.get() || runs < actual_num_loops) { // if (runs % 100000 == 0) log.info("REM run # " + runs); // TestingUtil.sleepThread(10); R.nextBytes(captureByte); key[4] = captureByte[0]; dc.remove(key); runs++; } perf.put("REM", opsPerMS(System.nanoTime() - start, runs)); } }; Thread[] threads = {getter, putter, remover}; for (Thread t : threads) t.start(); latch.countDown(); // wait some time Thread.sleep(warmup ? WARMUP_TIME_MILLIS : RUN_TIME_MILLIS); run.set(false); for (Thread t : threads) t.join(); if (!warmup) log.warnf("%s: Performance: %s", dc.getClass().getSimpleName(), perf); } private void waitForStart() { try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } private String opsPerMS(long nanos, int ops) { long totalMillis = TimeUnit.NANOSECONDS.toMillis(nanos); if (totalMillis > 0) return ops / totalMillis + " ops/ms"; else return "NAN ops/ms"; } }
9,395
38.15
120
java
null
infinispan-main/core/src/test/java/org/infinispan/stress/MemoryCleanupTest.java
package org.infinispan.stress; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * @author Mircea.Markus@jboss.com */ @Test(groups = "stress", testName = "stress.MemoryCleanupTest", description = "Designed to be run manually") public class MemoryCleanupTest { @BeforeClass(alwaysRun = true) public void createCm() { } public void testMemoryConsumption() throws InterruptedException { final ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(config); Cache<Object, Object> cache = cm.getCache(); long freeMemBefore = freeMemKb(); System.out.println("freeMemBefore = " + freeMemBefore); for (int i = 0; i < 1024 * 300; i++) { cache.put(i, i); } System.out.println("Free memory after: " + freeMemKb()); System.out.println("Consumed memory: " + (freeMemBefore - freeMemKb())); cm.stop(); for (int i = 0; i < 10; i++) { System.gc(); if (isOkay(freeMemBefore)) { break; } else { Thread.sleep(1000); } } System.out.println("Free memory at the end:" + freeMemKb()); assert isOkay(freeMemBefore); } private boolean isOkay(long freeMemBefore) { return freeMemBefore < freeMemKb() + 0.1 * freeMemKb(); } public long freeMemKb() { return Runtime.getRuntime().freeMemory() / 1024; } }
1,717
30.236364
108
java
null
infinispan-main/core/src/test/java/org/infinispan/stress/AbstractWriteSkewStressTest.java
package org.infinispan.stress; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import jakarta.transaction.Status; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.LockingMode; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; /** * @author Pedro Ruivo * @since 7.0 */ @Test(testName = "stress.AbstractWriteSkewStressTest", groups = "stress") public abstract class AbstractWriteSkewStressTest extends MultipleCacheManagersTest { private static final String SHARED_COUNTER_TEST_KEY = "counter"; private static final int SHARED_COUNTER_TEST_MAX_COUNTER_VALUE = 1000; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(true); builder.clustering().cacheMode(getCacheMode()) .locking().isolationLevel(IsolationLevel.REPEATABLE_READ).lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis()) .transaction().lockingMode(LockingMode.OPTIMISTIC); decorate(builder); createCluster(builder, 2); waitForClusterToForm(); } protected void decorate(ConfigurationBuilder builder) { // No-op } protected abstract CacheMode getCacheMode(); // This test is based on a contribution by Pedro Ruivo of INESC-ID, working on the Cloud-TM project. public void testSharedCounter() { final Cache<String, Integer> c1 = cache(0); final Cache<String, Integer> c2 = cache(1); //initialize the counter c1.put(SHARED_COUNTER_TEST_KEY, 0); //check if the counter is initialized in all caches assertEquals("Initial value is different from zero in cache 1", 0, (int) c1.get(SHARED_COUNTER_TEST_KEY)); assertEquals("Initial value is different from zero in cache 2", 0, (int) c2.get(SHARED_COUNTER_TEST_KEY)); //this will keep the values put by both threads. any duplicate value will be detected because of the //return value of add() method final Set<Integer> uniqueValuesIncremented = new ConcurrentSkipListSet<>(); //create both threads (each of them incrementing the counter on one node) Future<Boolean> f1 = fork(new IncrementCounterTask(c1, uniqueValuesIncremented)); Future<Boolean> f2 = fork(new IncrementCounterTask(c2, uniqueValuesIncremented)); try { // wait to finish and check is any duplicate value has been detected assertTrue("Cache 1 [" + address(c1) + "] has put a duplicate value", f1.get(5, TimeUnit.MINUTES)); assertTrue("Cache 2 [" + address(c2) + "] has put a duplicate value", f2.get(5, TimeUnit.MINUTES)); } catch (InterruptedException e) { fail("Interrupted exception while running the test"); } catch (ExecutionException e) { log.error("Exception in running updater threads", e); fail("Exception running updater threads"); } catch (TimeoutException e) { fail("Timed out waiting for updater threads"); } finally { f1.cancel(true); f2.cancel(true); } //check if all caches obtains the counter_max_values assertTrue("Cache 1 [" + address(c1) + "] fina value is less than " + SHARED_COUNTER_TEST_MAX_COUNTER_VALUE, c1.get(SHARED_COUNTER_TEST_KEY) >= SHARED_COUNTER_TEST_MAX_COUNTER_VALUE); assertTrue("Cache 2 [" + address(c2) + "] fina value is less than " + SHARED_COUNTER_TEST_MAX_COUNTER_VALUE, c2.get(SHARED_COUNTER_TEST_KEY) >= SHARED_COUNTER_TEST_MAX_COUNTER_VALUE); } private class IncrementCounterTask implements Callable<Boolean> { private final Cache<String, Integer> cache; private final Set<Integer> uniqueValuesSet; private final TransactionManager transactionManager; private int lastValue; public IncrementCounterTask(Cache<String, Integer> cache, Set<Integer> uniqueValuesSet) { this.cache = cache; this.transactionManager = cache.getAdvancedCache().getTransactionManager(); this.uniqueValuesSet = uniqueValuesSet; this.lastValue = 0; } @Override public Boolean call() throws InterruptedException { boolean unique = true; while (lastValue < SHARED_COUNTER_TEST_MAX_COUNTER_VALUE && !Thread.interrupted()) { boolean success = false; try { //start transaction, get the counter value, increment and put it again //check for duplicates in case of success transactionManager.begin(); Integer value = cache.get(SHARED_COUNTER_TEST_KEY); value = value + 1; lastValue = value; cache.put(SHARED_COUNTER_TEST_KEY, value); transactionManager.commit(); unique = uniqueValuesSet.add(value); success = true; } catch (Exception e) { // expected exception } finally { if (!success) { try { //lets rollback if (transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION) transactionManager.rollback(); } catch (Throwable t) { //the only possible exception is thrown by the rollback. just ignore it log.trace("Exception during rollback", t); } } assertTrue("Duplicate value found in " + address(cache) + " (value=" + lastValue + ")", unique); } } return unique; } } }
6,330
39.583333
126
java
null
infinispan-main/core/src/test/java/org/infinispan/stress/ReplWriteSkewStressTest.java
package org.infinispan.stress; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; /** * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "stress", testName = "stress.ReplWriteSkewStressTest", timeOut = 15*60*1000) public class ReplWriteSkewStressTest extends AbstractWriteSkewStressTest { @Override protected CacheMode getCacheMode() { return CacheMode.REPL_SYNC; } }
429
22.888889
91
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/ConfigurationUnitTest.java
package org.infinispan.configuration; import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.infinispan.test.fwk.TestCacheManagerFactory.createCacheManager; import static org.infinispan.transaction.TransactionMode.NON_TRANSACTIONAL; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.SchemaFactory; import org.infinispan.Cache; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.FileLookup; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.commons.util.Version; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.MemoryConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.TestObjectStreamMarshaller; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.infinispan.transaction.TransactionMode; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.Test; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.InputSource; @Test(groups = "functional", testName = "configuration.ConfigurationUnitTest") public class ConfigurationUnitTest extends AbstractInfinispanTest { @Test public void testBuild() { // Simple test to ensure we can actually build a config ConfigurationBuilder cb = new ConfigurationBuilder(); cb.build(); } @Test public void testCreateCache() { withCacheManager(new CacheManagerCallable(createCacheManager())); } @Test public void testEvictionSize() { Configuration configuration = new ConfigurationBuilder() .memory().size(20) .build(); Assert.assertEquals(configuration.memory().size(), 20); } @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); } @Test public void testDummyTMGetCache() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.transaction().use1PcForAutoCommitTransactions(true) .transactionManagerLookup(new EmbeddedTransactionManagerLookup()); withCacheManager(new CacheManagerCallable(createCacheManager(new ConfigurationBuilder())) { @Override public void call() { cm.getCache(); } }); } @Test public void testGetCache() { withCacheManager(new CacheManagerCallable(createCacheManager(new ConfigurationBuilder())) { @Override public void call() { cm.getCache(); } }); } @Test public void testDefineNamedCache() { withCacheManager(new CacheManagerCallable(createCacheManager()) { @Override public void call() { cm.defineConfiguration("foo", new ConfigurationBuilder().build()); } }); } @Test public void testGetAndPut() { withCacheManager(new CacheManagerCallable(createCacheManager(new ConfigurationBuilder())) { @Override public void call() { Cache<String, String> cache = cm.getCache(); cache.put("Foo", "2"); cache.put("Bar", "4"); Assert.assertEquals(cache.get("Foo"), "2"); Assert.assertEquals(cache.get("Bar"), "4"); } }); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN(\\d)*: Cannot enable Invocation Batching when the Transaction Mode is NON_TRANSACTIONAL, set the transaction mode to TRANSACTIONAL") public void testInvocationBatchingAndNonTransactional() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.transaction() .transactionMode(NON_TRANSACTIONAL) .invocationBatching() .enable(); withCacheManager(new CacheManagerCallable(createCacheManager(cb))); } @Test public void testDisableL1() { withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.createClusteredCacheManager( new ConfigurationBuilder(), new TransportFlags())) { @Override public void call() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC).l1().disable(); cm.defineConfiguration("testConfigCache", cb.build()); Cache<Object, Object> cache = cm.getCache("testConfigCache"); assert !cache.getCacheConfiguration().clustering().l1().enabled(); } }); } @Test public void testClearStores() { Configuration c = new ConfigurationBuilder() .persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .persistence() .clearStores() .build(); assertEquals(c.persistence().stores().size(), 0); } @Test(expectedExceptions = CacheConfigurationException.class) public void testClusterNameNull() { GlobalConfigurationBuilder gc = new GlobalConfigurationBuilder(); gc.transport().clusterName(null).build(); } @Test(enabled = false, description = "JGRP-2590") public void testSchema() throws Exception { FileLookup lookup = FileLookupFactory.newInstance(); String schemaFilename = String.format("schema/infinispan-config-%s.xsd", Version.getMajorMinor()); URL schemaFile = lookup.lookupFileLocation(schemaFilename, Thread.currentThread().getContextClassLoader()); if (schemaFile == null) { throw new NullPointerException("Failed to find a schema file " + schemaFilename); } Source xmlFile = new StreamSource(lookup.lookupFile(String.format("configs/all/%s.xml", Version.getMajorMinor()), Thread.currentThread().getContextClassLoader())); try { SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver(new TestResolver()); factory.newSchema(schemaFile).newValidator().validate(xmlFile); } catch (IllegalArgumentException e) { Assert.fail("Unable to validate schema", e); } } @Test(expectedExceptions = IllegalArgumentException.class) public void testNumOwners() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC); cb.clustering().hash().numOwners(5); Configuration c = cb.build(); Assert.assertEquals(5, c.clustering().hash().numOwners()); // negative test cb.clustering().hash().numOwners(0); } @Test(expectedExceptions = IllegalArgumentException.class) public void numVirtualNodes() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC); cb.clustering().hash().numSegments(5); Configuration c = cb.build(); Assert.assertEquals(5, c.clustering().hash().numSegments()); // negative test cb.clustering().hash().numSegments(0); } public void testNoneIsolationLevel() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.locking().isolationLevel(IsolationLevel.NONE); withCacheManager(new CacheManagerCallable( createCacheManager(builder)) { @Override public void call() { Configuration cfg = cm.getCache().getCacheConfiguration(); assertEquals(IsolationLevel.NONE, cfg.locking().isolationLevel()); } }); } public void testNoneIsolationLevelInCluster() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.locking().isolationLevel(IsolationLevel.NONE) .clustering().cacheMode(CacheMode.REPL_SYNC).build(); withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.createClusteredCacheManager(builder)) { @Override public void call() { Configuration cfg = cm.getCache().getCacheConfiguration(); assertEquals(IsolationLevel.READ_COMMITTED, cfg.locking().isolationLevel()); } }); } public void testConfigureMarshaller() { GlobalConfigurationBuilder gc = new GlobalConfigurationBuilder(); TestObjectStreamMarshaller marshaller = new TestObjectStreamMarshaller(); gc.serialization().marshaller(marshaller); withCacheManager(new CacheManagerCallable( createCacheManager(gc, new ConfigurationBuilder())) { @Override public void call() { cm.getCache(); } }); marshaller.stop(); } @Test(expectedExceptions = CacheConfigurationException.class) public void testWrongCacheModeConfiguration() { ConfigurationBuilder config = new ConfigurationBuilder(); config.clustering().cacheMode(CacheMode.REPL_ASYNC); TestCacheManagerFactory.createCacheManager(config); } public void testCacheModeConfiguration() { withCacheManager(new CacheManagerCallable(createTestCacheManager()) { @Override public void call() { cm.getCache("local").put("key", "value"); } }); } private EmbeddedCacheManager createTestCacheManager() { ConfigurationBuilder config = new ConfigurationBuilder(); config.clustering().cacheMode(CacheMode.REPL_ASYNC); EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(config); config = new ConfigurationBuilder(); cm.defineConfiguration("local", config.build()); return cm; } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN(\\d)*: Indexing can not be enabled on caches in Invalidation mode") public void testIndexingOnInvalidationCache() { ConfigurationBuilder c = new ConfigurationBuilder(); c.clustering().cacheMode(CacheMode.INVALIDATION_SYNC); c.indexing().enable(); c.validate(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN(\\d)*: Indexing can only be enabled if infinispan-query.jar is available on your classpath, and this jar has not been detected.") public void testIndexingRequiresOptionalModule() { ConfigurationBuilder c = new ConfigurationBuilder(); c.indexing().enable(); c.validate(GlobalConfigurationBuilder.defaultClusteredBuilder().build()); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN(\\d)*: A cache configured with invocation batching can't have recovery enabled") public void testInvalidBatchingAndTransactionConfiguration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.invocationBatching().enable(); builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL); builder.transaction().useSynchronization(false); builder.transaction().recovery().enable(); withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.createCacheManager(builder)) { @Override public void call() { cm.getCache(); } }); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN(\\d)*: Recovery not supported with non transactional cache") public void testInvalidRecoveryWithNonTransactional() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL); builder.transaction().useSynchronization(false); builder.transaction().recovery().enable(); withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.createCacheManager(builder)) { @Override public void call() { cm.getCache(); } }); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN(\\d)*: Recovery not supported with Synchronization") public void testInvalidRecoveryWithSynchronization() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL); builder.transaction().useSynchronization(true); builder.transaction().recovery().enable(); withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.createCacheManager(builder)) { @Override public void call() { cm.getCache(); } }); } public void testValidRecoveryConfiguration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL); builder.transaction().useSynchronization(false); builder.transaction().recovery().enable(); withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.createCacheManager(builder)) { @Override public void call() { AssertJUnit.assertTrue(cm.getCache().getCacheConfiguration().transaction().recovery().enabled()); } }); } public void testTransactionConfigurationUnmodified() { ConfigurationBuilder builder = new ConfigurationBuilder(); Configuration configuration = builder.build(); assertFalse(configuration.transaction().attributes().isModified()); } public void testMemoryConfigurationUnmodified() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory().maxCount(1000); Configuration configuration = builder.build(); assertFalse(configuration.memory().attributes().attribute(MemoryConfiguration.STORAGE).isModified()); assertFalse(configuration.memory().attributes().attribute(MemoryConfiguration.WHEN_FULL).isModified()); } public void testMultipleValidationErrors() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.transaction().reaperWakeUpInterval(-1); builder.addModule(NonValidatingBuilder.class); try { builder.validate(); fail("Expected CacheConfigurationException"); } catch (CacheConfigurationException e) { assertEquals(e.getSuppressed().length, 2); assertTrue(e.getMessage().startsWith("ISPN000919")); assertTrue(e.getSuppressed()[0].getMessage().startsWith("ISPN000344")); assertEquals("MODULE ERROR", e.getSuppressed()[1].getMessage()); } GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); global.security().authorization().enable().principalRoleMapper(null); global.addModule(NonValidatingBuilder.class); try { global.validate(); fail("Expected CacheConfigurationException"); } catch (CacheConfigurationException e) { assertEquals(e.getSuppressed().length, 2); assertTrue(e.getMessage(), e.getMessage().startsWith("ISPN000919")); assertTrue(e.getSuppressed()[0].getMessage().startsWith("ISPN000288")); assertEquals("MODULE ERROR", e.getSuppressed()[1].getMessage()); } } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN(\\d)*: .*preload and purgeOnStartup") public void testPreloadAndPurgeOnStartupPersistence() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class) .preload(true) .purgeOnStartup(true) .validate(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN(\\d)*: .*passivation if it is read only!") public void testPassivationAndIgnoreModificationsPersistence() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.persistence().passivation(true) .addStore(DummyInMemoryStoreConfigurationBuilder.class) .ignoreModifications(true) .validate(); } public static class NonValidatingBuilder implements Builder<Object> { public NonValidatingBuilder(GlobalConfigurationBuilder builder) { } public NonValidatingBuilder(ConfigurationBuilder builder) { } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } @Override public void validate() { throw new RuntimeException("MODULE ERROR"); } @Override public Object create() { return null; } @Override public Builder<?> read(Object template, Combine combine) { return this; } } public static class TestResolver implements LSResourceResolver { Map<String, String> entities = new HashMap<>(); public TestResolver() { entities.put("urn:org:jgroups", "jgroups-5.2.xsd"); entities.put("urn:jgroups:relay:1.0", "relay.xsd"); entities.put("fork", "fork-stacks.xsd"); } @Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { String entity = entities.get(namespaceURI); if (entity != null) { InputStream is = this.loadResource(entity); if (is != null) { InputSource inputSource = new InputSource(is); inputSource.setSystemId(systemId); return new LSInputImpl(type, namespaceURI, publicId, systemId, baseURI, inputSource); } } return null; } private InputStream loadResource(String resource) { ClassLoader classLoader = this.getClass().getClassLoader(); InputStream inputStream = loadResource(classLoader, resource); if (inputStream == null) { classLoader = Thread.currentThread().getContextClassLoader(); inputStream = this.loadResource(classLoader, resource); } return inputStream; } private InputStream loadResource(ClassLoader loader, String resource) { URL url = loader.getResource(resource); if (url == null) { if (resource.endsWith(".dtd")) { resource = "dtd/" + resource; } else if (resource.endsWith(".xsd")) { resource = "schema/" + resource; } url = loader.getResource(resource); } InputStream inputStream = null; if (url != null) { try { inputStream = url.openStream(); } catch (IOException e) { } } return inputStream; } } public static class LSInputImpl implements LSInput { private final String type; private final String namespaceURI; private final String publicId; private final String systemId; private final String baseURI; private final InputSource inputSource; public LSInputImpl(String type, String namespaceURI, String publicId, String systemId, String baseURI, InputSource inputSource) { this.type = type; this.namespaceURI = namespaceURI; this.publicId = publicId; this.systemId = systemId; this.baseURI = baseURI; this.inputSource = inputSource; } @Override public Reader getCharacterStream() { return null; } @Override public void setCharacterStream(Reader characterStream) { } @Override public InputStream getByteStream() { return this.inputSource.getByteStream(); } @Override public void setByteStream(InputStream byteStream) { } @Override public String getStringData() { return null; } @Override public void setStringData(String stringData) { } @Override public String getSystemId() { return systemId; } @Override public void setSystemId(String systemId) { } @Override public String getPublicId() { return publicId; } @Override public void setPublicId(String publicId) { } @Override public String getBaseURI() { return baseURI; } @Override public void setBaseURI(String baseURI) { } @Override public String getEncoding() { return null; } @Override public void setEncoding(String encoding) { } @Override public boolean getCertifiedText() { return false; } @Override public void setCertifiedText(boolean certifiedText) { } } }
22,182
35.187602
181
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/ConfigurationOverrideTest.java
package org.infinispan.configuration; import org.infinispan.Cache; import org.infinispan.commons.configuration.Combine; import org.infinispan.configuration.cache.ClusteringConfiguration; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.infinispan.configuration.cache.CacheMode.DIST_SYNC; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; @Test(groups = "functional", testName = "configuration.ConfigurationOverrideTest") public class ConfigurationOverrideTest extends AbstractInfinispanTest { private EmbeddedCacheManager cm; @AfterMethod public void stopCacheManager() { cm.stop(); } public void testConfigurationOverride() throws Exception { ConfigurationBuilder defaultCfgBuilder = new ConfigurationBuilder(); defaultCfgBuilder.memory().size(200).storageType(StorageType.BINARY); cm = TestCacheManagerFactory.createCacheManager(defaultCfgBuilder); final ConfigurationBuilder cacheCfgBuilder = new ConfigurationBuilder().read(defaultCfgBuilder.build(), Combine.DEFAULT); cm.defineConfiguration("my-cache", cacheCfgBuilder.build()); Cache<?, ?> cache = cm.getCache("my-cache"); assertEquals(200, cache.getCacheConfiguration().memory().size()); assertEquals(StorageType.BINARY, cache.getCacheConfiguration().memory().storageType()); } public void testSimpleDistributedClusterModeDefault() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(DIST_SYNC) .hash().numOwners(3).numSegments(51); cm = TestCacheManagerFactory.createClusteredCacheManager(builder); cm.defineConfiguration("my-cache", builder.build()); Cache<?, ?> cache = cm.getCache("my-cache"); // These are all overridden values ClusteringConfiguration clusteringCfg = cache.getCacheConfiguration().clustering(); assertEquals(DIST_SYNC, clusteringCfg.cacheMode()); assertEquals(3, clusteringCfg.hash().numOwners()); assertEquals(51, clusteringCfg.hash().numSegments()); } public void testSimpleDistributedClusterModeNamedCache() throws Exception { final String cacheName = "my-cache"; final Configuration config = new ConfigurationBuilder() .clustering().cacheMode(DIST_SYNC) .hash().numOwners(3).numSegments(51).build(); cm = TestCacheManagerFactory.createClusteredCacheManager(); cm.defineConfiguration(cacheName, config); Cache<?, ?> cache = cm.getCache(cacheName); ClusteringConfiguration clusteringCfg = cache.getCacheConfiguration().clustering(); assertEquals(DIST_SYNC, clusteringCfg.cacheMode()); assertEquals(3, clusteringCfg.hash().numOwners()); assertEquals(51, clusteringCfg.hash().numSegments()); } public void testOverrideWithStore() { final ConfigurationBuilder builder1 = new ConfigurationBuilder(); builder1.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); cm = TestCacheManagerFactory.createCacheManager(builder1); ConfigurationBuilder builder2 = new ConfigurationBuilder(); builder2.read(cm.getDefaultCacheConfiguration(), Combine.DEFAULT); builder2.memory().size(1000); Configuration configuration = cm.defineConfiguration("named", builder2.build()); assertEquals(1, configuration.persistence().stores().size()); } public void testPartialOverride() { ConfigurationBuilder baseBuilder = new ConfigurationBuilder(); baseBuilder.memory().size(200).storageType(StorageType.BINARY); Configuration base = baseBuilder.build(); ConfigurationBuilder overrideBuilder = new ConfigurationBuilder(); overrideBuilder.read(base, Combine.DEFAULT).locking().concurrencyLevel(31); Configuration override = overrideBuilder.build(); assertEquals(200, base.memory().size()); assertEquals(200, override.memory().size()); assertEquals(StorageType.BINARY, base.memory().storageType()); assertEquals(StorageType.BINARY, override.memory().storageType()); assertEquals(32, base.locking().concurrencyLevel()); assertEquals(31, override.locking().concurrencyLevel()); } public void testConfigurationUndefine() { cm = TestCacheManagerFactory.createCacheManager(); cm.defineConfiguration("testConfig", new ConfigurationBuilder().build()); cm.undefineConfiguration("testConfig"); assertNull(cm.getCacheConfiguration("testConfig")); } @Test(expectedExceptions=IllegalStateException.class) public void testConfigurationUndefineWhileInUse() { cm = TestCacheManagerFactory.createCacheManager(); cm.defineConfiguration("testConfig", new ConfigurationBuilder().build()); cm.getCache("testConfig"); cm.undefineConfiguration("testConfig"); } }
5,358
44.415254
93
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/QueryableDataContainer.java
package org.infinispan.configuration; import static java.util.Collections.synchronizedCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.factories.annotations.Stop; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.metadata.Metadata; @Scope(Scopes.NAMED_CACHE) public class QueryableDataContainer implements DataContainer<Object, Object> { // Since this static field is here, we can't use generic types properly private static DataContainer<Object, Object> delegate; public static void setDelegate(DataContainer<Object, Object> delegate) { QueryableDataContainer.delegate = delegate; } private final Collection<String> loggedOperations; public void setFoo(String foo) { loggedOperations.add("setFoo(" + foo + ")"); } public QueryableDataContainer() { this.loggedOperations = synchronizedCollection(new ArrayList<String>()); } @Override public Iterator<InternalCacheEntry<Object, Object>> iterator() { loggedOperations.add("iterator()"); return delegate.iterator(); } @Override public Iterator<InternalCacheEntry<Object, Object>> iteratorIncludingExpired() { loggedOperations.add("expiredIterator()"); return delegate.iteratorIncludingExpired(); } @Override public InternalCacheEntry<Object, Object> get(Object k) { loggedOperations.add("get(" + k + ")" ); return delegate.get(k); } @Override public InternalCacheEntry<Object, Object> peek(Object k) { loggedOperations.add("peek(" + k + ")" ); return delegate.peek(k); } @Override public void put(Object k, Object v, Metadata metadata) { loggedOperations.add("put(" + k + ", " + v + ", " + metadata + ")"); delegate.put(k, v, metadata); } @Override public boolean containsKey(Object k) { loggedOperations.add("containsKey(" + k + ")" ); return delegate.containsKey(k); } @Override public InternalCacheEntry<Object, Object> remove(Object k) { loggedOperations.add("remove(" + k + ")" ); return delegate.remove(k); } @Override public int size() { loggedOperations.add("size()" ); return delegate.size(); } @Override public int sizeIncludingExpired() { loggedOperations.add("sizeIncludingExpired()" ); return delegate.sizeIncludingExpired(); } @Stop @Override public void clear() { loggedOperations.add("clear()" ); delegate.clear(); } @Override public void evict(Object key) { loggedOperations.add("evict(" + key + ")"); delegate.evict(key); } @Override public InternalCacheEntry<Object, Object> compute(Object key, ComputeAction<Object, Object> action) { loggedOperations.add("compute(" + key + "," + action + ")"); return delegate.compute(key, action); } public Collection<String> getLoggedOperations() { return loggedOperations; } }
3,156
26.938053
104
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/HashConfigurationBuilderTest.java
package org.infinispan.configuration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.ch.impl.SyncConsistentHashFactory; import org.infinispan.test.AbstractInfinispanTest; import org.testng.Assert; import org.testng.annotations.Test; @Test(groups = "functional", testName = "configuration.HashConfigurationBuilderTest") public class HashConfigurationBuilderTest extends AbstractInfinispanTest { public void testNumOwners() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC); cb.clustering().hash().numOwners(5); Configuration c = cb.build(); Assert.assertEquals(5, c.clustering().hash().numOwners()); try { cb.clustering().hash().numOwners(0); Assert.fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { } } public void testNumSegments() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC); cb.clustering().hash().numSegments(5); Configuration c = cb.build(); Assert.assertEquals(5, c.clustering().hash().numSegments()); try { cb.clustering().hash().numSegments(0); Assert.fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { } } public void testConsistentHashFactory() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC); Configuration c = cb.build(); Assert.assertNull(c.clustering().hash().consistentHashFactory()); SyncConsistentHashFactory consistentHashFactory = new SyncConsistentHashFactory(); cb.clustering().hash().consistentHashFactory(consistentHashFactory); c = cb.build(); Assert.assertSame(c.clustering().hash().consistentHashFactory(), consistentHashFactory); } }
2,061
35.821429
94
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/CustomInterceptorConfigTest.java
package org.infinispan.configuration; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.AssertJUnit.assertNotNull; import java.io.ByteArrayInputStream; import java.io.InputStream; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.InterceptorConfiguration.Position; import org.infinispan.interceptors.BaseCustomAsyncInterceptor; import org.infinispan.interceptors.impl.InvocationContextInterceptor; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(testName = "configuration.CustomInterceptorConfigTest", groups = "functional") public class CustomInterceptorConfigTest extends AbstractInfinispanTest { public void testCustomInterceptors() { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<infinispan>" + "<cache-container name=\"custom\" default-cache=\"default-cache\">" + "<transport />" + "<local-cache name=\"default-cache\"><custom-interceptors> \n" + "<interceptor after=\""+ InvocationContextInterceptor.class.getName()+"\" class=\""+DummyInterceptor.class.getName()+"\"/> \n" + "</custom-interceptors> </local-cache>" + "<local-cache name=\"x\">" + "<custom-interceptors>\n" + " <interceptor position=\"first\" class=\""+CustomInterceptor1.class.getName()+"\" />" + " <interceptor" + " position=\"last\"" + " class=\""+CustomInterceptor2.class.getName()+"\"" + " />" + "</custom-interceptors>" + "</local-cache>" + "</cache-container>" + "</infinispan>"; InputStream stream = new ByteArrayInputStream(xml.getBytes()); withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.fromStream(stream)){ @Override public void call() { Cache c = cm.getCache(); DummyInterceptor i = TestingUtil.findInterceptor(c, DummyInterceptor.class); assert i != null; Cache<Object, Object> namedCacheX = cm.getCache("x"); assert TestingUtil.findInterceptor(namedCacheX, CustomInterceptor1.class) != null; assert TestingUtil.findInterceptor(namedCacheX, CustomInterceptor2.class) != null; } }); } public static final class CustomInterceptor1 extends BaseCustomAsyncInterceptor {} public static final class CustomInterceptor2 extends BaseCustomAsyncInterceptor {} public void testCustomInterceptorsProgramatically() { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.customInterceptors().addInterceptor().interceptor(new DummyInterceptor()).position(Position.FIRST); withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager(cfg)) { @Override public void call() { Cache c = cm.getCache(); DummyInterceptor i = TestingUtil.findInterceptor(c, DummyInterceptor.class); assertNotNull(i); } }); } public void testCustomInterceptorsProgramaticallyWithOverride() { final ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.customInterceptors().addInterceptor().interceptor(new DummyInterceptor()).position(Position.FIRST); withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()) { @Override public void call() { cm.defineConfiguration("custom", cfg.build()); Cache c = cm.getCache("custom"); DummyInterceptor i = TestingUtil.findInterceptor(c, DummyInterceptor.class); assertNotNull(i); } }); } public static class DummyInterceptor extends BaseCustomAsyncInterceptor { } }
4,065
41.8
140
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/XSiteFileParsingTest.java
package org.infinispan.configuration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.Cache; import org.infinispan.configuration.cache.BackupConfiguration.BackupStrategy; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.BackupForConfiguration; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.XSiteStateTransferMode; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.infinispan.xsite.CountingCustomFailurePolicy; import org.infinispan.xsite.CustomXSiteEntryMergePolicy; import org.infinispan.xsite.spi.AlwaysRemoveXSiteEntryMergePolicy; import org.infinispan.xsite.spi.DefaultXSiteEntryMergePolicy; import org.infinispan.xsite.spi.PreferNonNullXSiteEntryMergePolicy; import org.infinispan.xsite.spi.PreferNullXSiteEntryMergePolicy; import org.infinispan.xsite.spi.XSiteEntryMergePolicy; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "functional", testName = "xsite.XSiteFileParsingTest") public class XSiteFileParsingTest extends SingleCacheManagerTest { public static final String FILE_NAME = "configs/xsite/xsite-test.xml"; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.fromXml(FILE_NAME, false, true, TransportFlags.minimalXsiteFlags()); } public void testLocalSiteName() { cacheManager.getTransport().checkCrossSiteAvailable(); assertEquals("LON-1", cacheManager.getTransport().localSiteName()); } public void testDefaultCache() { Configuration dcc = cacheManager.getDefaultCacheConfiguration(); testDefault(dcc); } public void testBackupNyc() { Configuration dcc = cacheManager.getCacheConfiguration("backupNyc"); assertEquals(0, dcc.sites().allBackups().size()); BackupForConfiguration backupForConfiguration = dcc.sites().backupFor(); assertEquals("someCache", backupForConfiguration.remoteCache()); assertEquals("NYC", backupForConfiguration.remoteSite()); } public void testInheritor() { Configuration dcc = cacheManager.getCacheConfiguration("inheritor"); testDefault(dcc); } public void testNoBackups() { Configuration dcc = cacheManager.getCacheConfiguration("noBackups"); assertEquals(0, dcc.sites().allBackups().size()); assertNull(dcc.sites().backupFor().remoteCache()); assertNull(dcc.sites().backupFor().remoteSite()); } public void testCustomBackupPolicy() { Configuration dcc = cacheManager.getCacheConfiguration("customBackupPolicy"); assertEquals(1, dcc.sites().allBackups().size()); BackupConfigurationBuilder nyc2 = new BackupConfigurationBuilder(null).site("NYC2").strategy(BackupStrategy.SYNC) .backupFailurePolicy(BackupFailurePolicy.CUSTOM) .failurePolicyClass(CountingCustomFailurePolicy.class.getName()).replicationTimeout(160000) .useTwoPhaseCommit(false); assertTrue(dcc.sites().allBackups().contains(nyc2.create())); assertNull(dcc.sites().backupFor().remoteCache()); } public void testXSiteMergePolicy() { Configuration dcc = cacheManager.getCacheConfiguration("conflictResolver"); assertEquals(1, dcc.sites().allBackups().size()); assertEquals(PreferNonNullXSiteEntryMergePolicy.getInstance(), dcc.sites().mergePolicy()); } public void testXSiteMergePolicy2() { Configuration dcc = cacheManager.getCacheConfiguration("conflictResolver2"); assertEquals(1, dcc.sites().allBackups().size()); assertEquals(PreferNullXSiteEntryMergePolicy.getInstance(), dcc.sites().mergePolicy()); } public void testXSiteMergePolicy3() { Configuration dcc = cacheManager.getCacheConfiguration("conflictResolver3"); assertEquals(1, dcc.sites().allBackups().size()); assertEquals(AlwaysRemoveXSiteEntryMergePolicy.getInstance(), dcc.sites().mergePolicy()); } public void testCustomXSiteMergePolicy() { Configuration dcc = cacheManager.getCacheConfiguration("customConflictResolver"); assertEquals(1, dcc.sites().allBackups().size()); assertEquals(CustomXSiteEntryMergePolicy.class, dcc.sites().mergePolicy().getClass()); Cache<?, ?> cache = cacheManager.getCache("customConflictResolver"); XSiteEntryMergePolicy<? ,?> resolver = cache.getAdvancedCache().getComponentRegistry().getComponent(XSiteEntryMergePolicy.class); assertEquals(CustomXSiteEntryMergePolicy.class, resolver.getClass()); } public void testAutoStateTransfer() { Configuration dcc = cacheManager.getCacheConfiguration("autoStateTransfer"); assertEquals(1, dcc.sites().allBackups().size()); assertEquals(XSiteStateTransferMode.AUTO, dcc.sites().allBackups().get(0).stateTransfer().mode()); } public void testTombstoneConfiguration() { Configuration dcc = cacheManager.getCacheConfiguration("tombstoneCleanup"); assertEquals(3000, dcc.sites().maxTombstoneCleanupDelay()); assertEquals(4000, dcc.sites().tombstoneMapSize()); } private void testDefault(Configuration dcc) { assertEquals(2, dcc.sites().allBackups().size()); assertEquals(DefaultXSiteEntryMergePolicy.getInstance(), dcc.sites().mergePolicy()); BackupConfigurationBuilder nyc = new BackupConfigurationBuilder(null).site("NYC").strategy(BackupStrategy.SYNC) .backupFailurePolicy(BackupFailurePolicy.IGNORE).failurePolicyClass(null).replicationTimeout(12003) .useTwoPhaseCommit(false); assertTrue(dcc.sites().allBackups().contains(nyc.create())); BackupConfigurationBuilder sfo = new BackupConfigurationBuilder(null).site("SFO").strategy(BackupStrategy.ASYNC) .backupFailurePolicy(BackupFailurePolicy.WARN).failurePolicyClass(null).replicationTimeout(15000) .useTwoPhaseCommit(false); assertTrue(dcc.sites().allBackups().contains(sfo.create())); } }
6,352
45.713235
135
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/CustomInterceptorInjectionTest.java
package org.infinispan.configuration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertSame; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.DataContainer; import org.infinispan.factories.annotations.Inject; import org.infinispan.interceptors.AsyncInterceptor; import org.infinispan.interceptors.BaseCustomAsyncInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.locks.LockManager; import org.testng.annotations.Test; /** * Test that injection in interceptors works as expected. * * @author Mircea Markus * @since 5.0 */ @Test(groups = "functional", testName = "configuration.CustomInterceptorInjectionTest") public class CustomInterceptorInjectionTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(false); builder.customInterceptors().addInterceptor().index(0).interceptor(new SomeAsyncInterceptor()); return TestCacheManagerFactory.createCacheManager(builder); } public void testBaseCustomAsyncInterceptorInjection() { AsyncInterceptor interceptor = cache.getAdvancedCache().getAsyncInterceptorChain().getInterceptors().get(0); assertEquals(SomeAsyncInterceptor.class, interceptor.getClass()); SomeAsyncInterceptor someAsyncInterceptor = (SomeAsyncInterceptor) interceptor; assertSame(cache.getAdvancedCache().getLockManager(), someAsyncInterceptor.lm); assertSame(cache.getAdvancedCache().getDataContainer(), someAsyncInterceptor.dc); } static class SomeAsyncInterceptor extends BaseCustomAsyncInterceptor { @Inject LockManager lm; DataContainer dc; @Override protected void start() { dc = cache.getAdvancedCache().getDataContainer(); } } }
2,055
36.381818
114
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/ConfigurationCompatibilityTest.java
package org.infinispan.configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; @Test(groups = "functional", testName= "configuration.ConfigurationCompatibilityTest") public class ConfigurationCompatibilityTest { public void testDocumentationPersistenceConfiguration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.persistence() .passivation(false) .addSingleFileStore() .fetchPersistentState(true) .shared(false) .preload(true) .ignoreModifications(false) .purgeOnStartup(false) .location(System.getProperty("java.io.tmpdir")) .async() .enabled(true); } }
777
30.12
86
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/ConfigurationConversionTest.java
package org.infinispan.configuration; import java.util.Map; import java.util.Properties; import org.infinispan.commons.configuration.io.ConfigurationReader; import org.infinispan.commons.configuration.io.ConfigurationResourceResolvers; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.configuration.io.NamingStrategy; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.io.StringBuilderWriter; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.testng.annotations.Test; @Test(groups = "functional", testName= "configuration.ConfigurationConversionTest") public class ConfigurationConversionTest { @Test public void testAuthorizationRoles() { String xml = "<distributed-cache owners=\"2\" mode=\"SYNC\" statistics=\"false\">\n" + " <security>\n" + " <authorization />\n" + " </security>\n" + " <encoding media-type=\"application/x-java-serialized-object\" />\n" + " </distributed-cache> "; String json = convert(xml, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON); convert(json, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML); } private String convert(String source, MediaType src, MediaType dst) { ParserRegistry parserRegistry = new ParserRegistry(); Properties properties = new Properties(); ConfigurationReader reader = ConfigurationReader.from(source) .withResolver(ConfigurationResourceResolvers.DEFAULT) .withType(src) .withProperties(properties) .withNamingStrategy(NamingStrategy.KEBAB_CASE).build(); ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(); parserRegistry.parse(reader, holder); Map.Entry<String, ConfigurationBuilder> entry = holder.getNamedConfigurationBuilders().entrySet().iterator().next(); Configuration configuration = entry.getValue().build(); StringBuilderWriter out = new StringBuilderWriter(); try (ConfigurationWriter writer = ConfigurationWriter.to(out).withType(dst).clearTextSecrets(true).prettyPrint(true).build()) { parserRegistry.serialize(writer, entry.getKey(), configuration); } return out.toString(); } }
2,610
50.196078
135
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/XSiteFileParsing3Test.java
package org.infinispan.configuration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupConfiguration.BackupStrategy; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.Configuration; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "functional", testName = "xsite.XSiteFileParsing3Test") public class XSiteFileParsing3Test extends SingleCacheManagerTest { public static final String FILE_NAME = "configs/xsite/xsite-offline-test.xml"; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.fromXml(FILE_NAME, false, true, TransportFlags.minimalXsiteFlags()); } public void testDefaultCache() { Configuration dcc = cacheManager.getDefaultCacheConfiguration(); assertEquals(dcc.sites().allBackups().size(), 1); testDefault(dcc); } public void testInheritor() { Configuration dcc = cacheManager.getCacheConfiguration("inheritor"); testDefault(dcc); } public void testNoTakeOffline() { Configuration dcc = cacheManager.getCacheConfiguration("noTakeOffline"); assertEquals(1, dcc.sites().allBackups().size()); BackupConfiguration nyc = new BackupConfigurationBuilder(null).site("NYC").strategy(BackupStrategy.SYNC) .backupFailurePolicy(BackupFailurePolicy.WARN).failurePolicyClass(null).replicationTimeout(12003) .useTwoPhaseCommit(false).create(); assertTrue(dcc.sites().allBackups().contains(nyc)); assertEquals("SFO", dcc.sites().backupFor().remoteSite()); assertEquals("someCache", dcc.sites().backupFor().remoteCache()); } public void testTakeOfflineDifferentConfig() { Configuration dcc = cacheManager.getCacheConfiguration("takeOfflineDifferentConfig"); assertEquals(1, dcc.sites().allBackups().size()); BackupConfigurationBuilder nyc = new BackupConfigurationBuilder(null).site("NYC").strategy(BackupStrategy.SYNC) .backupFailurePolicy(BackupFailurePolicy.IGNORE).failurePolicyClass(null).replicationTimeout(12003) .useTwoPhaseCommit(false); nyc.takeOffline().afterFailures(321).minTimeToWait(3765); assertTrue(dcc.sites().allBackups().contains(nyc.create())); } private void testDefault(Configuration dcc) { BackupConfigurationBuilder nyc = new BackupConfigurationBuilder(null).site("NYC").strategy(BackupStrategy.SYNC) .backupFailurePolicy(BackupFailurePolicy.IGNORE).failurePolicyClass(null).replicationTimeout(12003) .useTwoPhaseCommit(false); nyc.takeOffline().afterFailures(123).minTimeToWait(5673); assertTrue(dcc.sites().allBackups().contains(nyc.create())); assertEquals("someCache", dcc.sites().backupFor().remoteCache()); assertEquals("SFO", dcc.sites().backupFor().remoteSite()); } }
3,353
45.583333
117
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/XSiteStateTransferFileParsingTest.java
package org.infinispan.configuration; import static org.infinispan.configuration.cache.XSiteStateTransferConfiguration.DEFAULT_TIMEOUT; import static org.infinispan.configuration.cache.XSiteStateTransferConfiguration.DEFAULT_WAIT_TIME; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.io.ByteArrayInputStream; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupConfiguration.BackupStrategy; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.Configuration; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.testng.annotations.Test; /** * It tests if the cross site replication configuration is correctly parsed and validated. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "functional", testName = "xsite.XSiteStateTransferFileParsingTest") public class XSiteStateTransferFileParsingTest extends SingleCacheManagerTest { private static final String FILE_NAME = "configs/xsite/xsite-state-transfer-test.xml"; private static final String XML_FORMAT = "<infinispan>\n" + "<cache-container default-cache=\"default\">\n" + " <transport cluster=\"infinispan-cluster\" lock-timeout=\"50000\" stack=\"udp\" node-name=\"Jalapeno\" machine=\"m1\"\n" + " rack=\"r1\" site=\"LON\"/>\n" + " <replicated-cache name=\"default\">\n" + " <backups>\n" + " <backup site=\"NYC\" strategy=\"SYNC\" failure-policy=\"WARN\" timeout=\"12003\">\n" + " <state-transfer chunk-size=\"10\" timeout=\"%s\" max-retries=\"30\" wait-time=\"%s\" mode=\"%s\"/>\n" + " </backup>\n" + " </backups>\n" + " <backup-for remote-cache=\"someCache\" remote-site=\"SFO\"/>\n" + " </replicated-cache>\n" + "</cache-container>\n</infinispan>"; public void testDefaultCache() { Configuration dcc = cacheManager.getDefaultCacheConfiguration(); assertEquals(1, dcc.sites().allBackups().size()); testDefault(dcc); } public void testInheritor() { Configuration dcc = cacheManager.getCacheConfiguration("inheritor"); assertEquals(1, dcc.sites().allBackups().size()); testDefault(dcc); } public void testStateTransferDifferentConfig() { Configuration dcc = cacheManager.getCacheConfiguration("stateTransferDifferentConfiguration"); assertEquals(1, dcc.sites().allBackups().size()); assertTrue(dcc.sites().allBackups().contains(create(98, 7654, 321, 101))); assertEquals("someCache", dcc.sites().backupFor().remoteCache()); assertEquals("SFO", dcc.sites().backupFor().remoteSite()); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN000449:.*") public void testNegativeTimeout() { testInvalidConfiguration(String.format(XML_FORMAT, -1, DEFAULT_WAIT_TIME, "MANUAL")); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN000449:.*") public void testZeroTimeout() { testInvalidConfiguration(String.format(XML_FORMAT, 0, DEFAULT_WAIT_TIME, "MANUAL")); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN000450:.*") public void testNegativeWaitTime() { testInvalidConfiguration(String.format(XML_FORMAT, DEFAULT_TIMEOUT, -1, "MANUAL")); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN000450:.*") public void testZeroWaitTime() { testInvalidConfiguration(String.format(XML_FORMAT, DEFAULT_TIMEOUT, 0, "MANUAL")); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN000634:.*") public void testAutoStateTransferModeWithSync() { testInvalidConfiguration(String.format(XML_FORMAT, DEFAULT_TIMEOUT, DEFAULT_WAIT_TIME, "AUTO")); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.fromXml(FILE_NAME,false, true, TransportFlags.minimalXsiteFlags()); } private void testInvalidConfiguration(String xmlConfiguration) { EmbeddedCacheManager invalidCacheManager = null; try { log.infof("Creating cache manager with %s", xmlConfiguration); invalidCacheManager = TestCacheManagerFactory .fromStream(new ByteArrayInputStream(xmlConfiguration.getBytes())); } finally { if (invalidCacheManager != null) { invalidCacheManager.stop(); } } } private void testDefault(Configuration dcc) { assertTrue(dcc.sites().allBackups().contains(create(123, 4567, 890, 1011))); assertEquals("someCache", dcc.sites().backupFor().remoteCache()); assertEquals("SFO", dcc.sites().backupFor().remoteSite()); } private static BackupConfiguration create(int chunkSize, long timeout, int maxRetries, long waitingTimeBetweenRetries) { BackupConfigurationBuilder builder = new BackupConfigurationBuilder(null).site("NYC") .strategy(BackupStrategy.SYNC).backupFailurePolicy(BackupFailurePolicy.WARN).failurePolicyClass(null) .replicationTimeout(12003).useTwoPhaseCommit(false); builder.stateTransfer().chunkSize(chunkSize).timeout(timeout).maxRetries(maxRetries) .waitTime(waitingTimeBetweenRetries); return builder.create(); } private static BackupConfiguration createDefault() { BackupConfigurationBuilder builder = new BackupConfigurationBuilder(null).site("NYC") .strategy(BackupStrategy.SYNC).backupFailurePolicy(BackupFailurePolicy.WARN).failurePolicyClass(null) .replicationTimeout(12003).useTwoPhaseCommit(false); return builder.create(); } }
6,215
47.5625
133
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/EvictionConfigurationTest.java
package org.infinispan.configuration; import static org.infinispan.configuration.cache.StorageType.BINARY; import static org.infinispan.configuration.cache.StorageType.HEAP; import static org.infinispan.configuration.cache.StorageType.OBJECT; import static org.infinispan.configuration.cache.StorageType.OFF_HEAP; import static org.infinispan.eviction.EvictionStrategy.REMOVE; import static org.infinispan.eviction.EvictionType.COUNT; import static org.infinispan.eviction.EvictionType.MEMORY; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayDeque; import java.util.Queue; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.io.ConfigurationResourceResolvers; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.MemoryConfiguration; import org.infinispan.configuration.cache.MemoryStorageConfiguration; import org.infinispan.configuration.cache.StorageType; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.Test; /** * Test for different scenarios of eviction configuration. */ @Test(groups = "unit", testName = "configuration.EvictionConfigurationTest") public class EvictionConfigurationTest extends AbstractInfinispanTest { private static final ParserRegistry REGISTRY = new ParserRegistry(); @Test public void testReuseLegacyBuilder() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory().size(200); Configuration configuration = builder.build(); assertEquals(configuration.memory().maxSizeBytes(), -1); assertEquals(configuration.memory().maxCount(), 200); assertEquals(configuration.memory().storageType(), HEAP); Configuration fromSameBuilder = builder.build(); assertEquals(configuration, fromSameBuilder); } @Test public void testReuseChangeLegacy() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory().storageType(OBJECT).size(12); Configuration conf1 = builder.build(); assertEquals(conf1.memory().storageType(), OBJECT); assertEquals(conf1.memory().size(), 12); builder.memory().storageType(BINARY); Configuration build2 = builder.build(); assertEquals(build2.memory().storageType(), BINARY); assertEquals(build2.memory().size(), 12); } @Test public void testEvictionDisabled() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory().storageType(StorageType.BINARY); Configuration configuration = builder.build(); assertEquals(configuration.memory().storageType(), StorageType.BINARY); assertEquals(configuration.memory().maxSizeBytes(), -1); assertEquals(configuration.memory().maxCount(), -1); Configuration same = builder.build(); assertEquals(configuration, same); } @Test public void testLegacyConfigAvailable() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory().maxSize("1.5 GB").storage(HEAP).whenFull(REMOVE); builder.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); Configuration configuration = builder.build(); assertEquals(configuration.memory().maxSizeBytes(), 1_500_000_000); assertEquals(configuration.memory().maxCount(), -1); assertEquals(configuration.memory().whenFull(), REMOVE); assertEquals(configuration.memory().storageType(), HEAP); assertEquals(configuration.memory().evictionStrategy(), REMOVE); assertEquals(configuration.memory().size(), 1_500_000_000); assertEquals(configuration.memory().evictionType(), MEMORY); Configuration same = builder.build(); assertEquals(configuration.memory(), same.memory()); Configuration larger = builder.memory().maxSize("2.0 GB").build(); assertEquals(larger.memory().maxSizeBytes(), 2_000_000_000); assertEquals(larger.memory().maxCount(), -1); assertEquals(larger.memory().whenFull(), REMOVE); assertEquals(larger.memory().storage(), HEAP); assertEquals(larger.memory().storageType(), HEAP); assertEquals(larger.memory().evictionStrategy(), REMOVE); assertEquals(larger.memory().size(), 2_000_000_000); assertEquals(larger.memory().evictionType(), MEMORY); } public void testUseDefaultEviction() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); Configuration configuration = builder.build(); assertFalse(configuration.memory().isEvictionEnabled()); assertEquals(configuration.memory().storage(), HEAP); assertEquals(configuration.memory().storageType(), HEAP); } @Test(expectedExceptions = CacheConfigurationException.class) public void testPreventUsingLegacyAndNew() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory().size(44).evictionType(COUNT); Configuration conf = builder.build(); assertEquals(conf.memory().maxCount(), 44); builder.memory().maxCount(10).size(12); builder.build(); } @Test public void testMinimal() { Configuration configuration = new ConfigurationBuilder().build(); assertFalse(configuration.memory().isOffHeap()); assertEquals(configuration.memory().maxCount(), -1L); assertEquals(configuration.memory().maxSizeBytes(), -1L); assertEquals(configuration.memory().storageType(), HEAP); } @Test public void testChangeFromMinimal() { ConfigurationBuilder initial = new ConfigurationBuilder(); Configuration initialConfig = initial.build(); assertEquals(initialConfig.memory().storageType(), HEAP); assertEquals(initialConfig.memory().size(), -1); initial.memory().size(3); Configuration larger = initial.build(); assertEquals(larger.memory().storageType(), HEAP); assertEquals(larger.memory().size(), 3); assertEquals(larger.memory().maxCount(), 3); assertEquals(larger.memory().storage(), HEAP); } @Test public void testRuntimeConfigChanges() { Configuration countBounded = new ConfigurationBuilder().memory().maxCount(1000).build(); Configuration sizeBounded = new ConfigurationBuilder().memory().maxSize("10 MB").storage(OFF_HEAP).build(); countBounded.memory().maxCount(1200); sizeBounded.memory().maxSize("20MB"); assertEquals(countBounded.memory().maxCount(), 1200); assertEquals(sizeBounded.memory().maxSizeBytes(), 20_000_000); Exceptions.expectException(CacheConfigurationException.class, () -> countBounded.memory().maxSize("30MB")); Exceptions.expectException(CacheConfigurationException.class, () -> sizeBounded.memory().maxCount(2000)); } @Test public void testParseXML() { String xml = "<infinispan>\n" + " <cache-container>\n" + " <local-cache name=\"local\">\n" + " <memory storage=\"OFF_HEAP\" max-size=\"200 MB\" when-full=\"MANUAL\" />\n" + " </local-cache>\n" + " </cache-container>\n" + "</infinispan>"; testSerializationAndBack(xml); ConfigurationBuilderHolder parsed = new ParserRegistry().parse(xml); ConfigurationBuilder parsedBuilder = parsed.getNamedConfigurationBuilders().get("local"); Configuration afterParsing = parsedBuilder.build(); assertEquals(afterParsing.memory().maxSizeBytes(), 200_000_000); assertEquals(afterParsing.memory().maxCount(), -1); assertEquals(afterParsing.memory().storageType(), OFF_HEAP); // Remove is forced assertEquals(afterParsing.memory().evictionStrategy(), REMOVE); assertEquals(afterParsing.memory().size(), 200_000_000); assertEquals(afterParsing.memory().evictionType(), MEMORY); assertEquals(afterParsing.memory().heapConfiguration().evictionStrategy(), REMOVE); } @Test public void testParseXML2() { String xmlNew = "<infinispan>\n" + " <cache-container>\n" + " <local-cache name=\"local\">\n" + " <memory max-count=\"2000\" when-full=\"REMOVE\" />\n" + " </local-cache>\n" + " </cache-container>\n" + "</infinispan>"; testSerializationAndBack(xmlNew); ConfigurationBuilderHolder parsed = new ParserRegistry().parse(xmlNew); ConfigurationBuilder parsedBuilder = parsed.getNamedConfigurationBuilders().get("local"); Configuration afterParsing = parsedBuilder.build(); assertEquals(afterParsing.memory().maxCount(), 2000); assertEquals(afterParsing.memory().whenFull(), REMOVE); assertEquals(afterParsing.memory().storageType(), HEAP); assertEquals(afterParsing.memory().evictionStrategy(), REMOVE); assertEquals(afterParsing.memory().size(), 2000); assertEquals(afterParsing.memory().evictionType(), COUNT); assertEquals(afterParsing.memory().heapConfiguration().evictionStrategy(), REMOVE); } @Test public void testParseXML3() { String xmlNew = "<infinispan>\n" + " <cache-container>\n" + " <local-cache name=\"local\">\n" + " <encoding media-type=\"application/json\" />\n" + " <memory storage=\"HEAP\" max-size=\"1MB\" when-full=\"REMOVE\"/>\n" + " </local-cache>\n" + " </cache-container>\n" + "</infinispan>"; testSerializationAndBack(xmlNew); ConfigurationBuilderHolder parsed = new ParserRegistry().parse(xmlNew); ConfigurationBuilder parsedBuilder = parsed.getNamedConfigurationBuilders().get("local"); Configuration afterParsing = parsedBuilder.build(); assertTrue(afterParsing.memory().isEvictionEnabled()); assertEquals(afterParsing.memory().storage(), HEAP); assertEquals(afterParsing.memory().maxSizeBytes(), 1_000_000); assertEquals(afterParsing.memory().whenFull(), REMOVE); assertEquals(afterParsing.memory().storageType(), HEAP); assertEquals(afterParsing.memory().size(), 1_000_000); assertEquals(afterParsing.memory().evictionStrategy(), REMOVE); assertEquals(afterParsing.memory().evictionType(), MEMORY); } @Test public void testParseJSON() { ConfigurationBuilderHolder holder = new ParserRegistry().parse("{\"local-cache\":{ \"memory\":{\"storage\":\"HEAP\",\"when-full\":\"REMOVE\",\"max-count\":5000}}}}", MediaType.APPLICATION_JSON); Configuration fromJson = holder.getCurrentConfigurationBuilder().build(); assertEquals(fromJson.memory().maxSizeBytes(), -1); assertEquals(fromJson.memory().maxCount(), 5000); assertEquals(fromJson.memory().storageType(), HEAP); assertEquals(fromJson.memory().evictionStrategy(), REMOVE); assertEquals(fromJson.memory().size(), 5000); assertEquals(fromJson.memory().evictionType(), COUNT); assertEquals(fromJson.memory().heapConfiguration().evictionStrategy(), REMOVE); } @Test public void testParseLegacyJSON() { ConfigurationBuilderHolder holder = new ParserRegistry().parse("{\"local-cache\":{ \"memory\":{\"storage\":\"OBJECT\", \"when-full\":\"REMOVE\",\"max-count\":5000}}}", MediaType.APPLICATION_JSON); Configuration fromJson = holder.getCurrentConfigurationBuilder().build(); assertEquals(fromJson.memory().maxSizeBytes(), -1); assertEquals(fromJson.memory().maxCount(), 5000); assertEquals(fromJson.memory().storageType(), OBJECT); assertEquals(fromJson.memory().evictionStrategy(), REMOVE); assertEquals(fromJson.memory().size(), 5000); assertEquals(fromJson.memory().evictionType(), COUNT); assertEquals(fromJson.memory().heapConfiguration().evictionStrategy(), REMOVE); } @Test public void testBuildWithLegacyConfiguration() { ConfigurationBuilder configBuilder = new ConfigurationBuilder(); configBuilder.memory().storageType(OFF_HEAP).size(1_000).evictionType(COUNT); Configuration configuration = configBuilder.build(); Configuration afterRead = new ConfigurationBuilder().read(configuration, Combine.DEFAULT).build(); assertEquals(OFF_HEAP, afterRead.memory().storage()); assertEquals(REMOVE, afterRead.memory().whenFull()); assertEquals(1_000, afterRead.memory().maxCount()); assertEquals(-1, afterRead.memory().maxSizeBytes()); assertEquals(OFF_HEAP, afterRead.memory().storageType()); assertEquals(REMOVE, afterRead.memory().evictionStrategy()); assertEquals(1_000, afterRead.memory().size()); assertEquals(COUNT, afterRead.memory().evictionType()); assertEquals(REMOVE, afterRead.memory().heapConfiguration().evictionStrategy()); } @Test public void testBuildWithLegacyConfiguration2() { ConfigurationBuilder configBuilder = new ConfigurationBuilder(); configBuilder.memory().storageType(HEAP).size(120); Configuration afterRead = new ConfigurationBuilder().read(configBuilder.build(), Combine.DEFAULT).build(); assertEquals(afterRead.memory().maxSizeBytes(), -1); assertEquals(afterRead.memory().maxCount(), 120); assertEquals(afterRead.memory().storageType(), HEAP); assertEquals(afterRead.memory().size(), 120); assertEquals(afterRead.memory().evictionType(), COUNT); ConfigurationBuilder override = new ConfigurationBuilder().read(afterRead, Combine.DEFAULT); Configuration overridden = override.memory().size(400).build(); assertEquals(overridden.memory().maxSizeBytes(), -1); assertEquals(overridden.memory().maxCount(), 400); assertEquals(overridden.memory().storageType(), HEAP); assertEquals(overridden.memory().size(), 400); assertEquals(overridden.memory().evictionType(), COUNT); } public void testListenToCountChanges() { ConfigurationBuilder countBuilder = new ConfigurationBuilder(); countBuilder.memory().storage(HEAP).maxCount(20); Configuration configuration = countBuilder.build(); assertEquals(COUNT, configuration.memory().evictionType()); Queue<Object> sizeListenerQueue = new ArrayDeque<>(1); Queue<Object> maxCountListenerQueue = new ArrayDeque<>(1); Queue<Object> maxSizeListenerQueue = new ArrayDeque<>(1); setUpListeners(configuration, sizeListenerQueue, maxCountListenerQueue, maxSizeListenerQueue); configuration.memory().size(100); assertCountUpdate(configuration, 100, sizeListenerQueue, maxCountListenerQueue, maxSizeListenerQueue); configuration.memory().heapConfiguration().size(200); assertCountUpdate(configuration, 200, sizeListenerQueue, maxCountListenerQueue, maxSizeListenerQueue); configuration.memory().maxCount(300); assertCountUpdate(configuration, 300, sizeListenerQueue, maxCountListenerQueue, maxSizeListenerQueue); } public void testListenToSizeChanges() { ConfigurationBuilder sizeBuilder = new ConfigurationBuilder(); sizeBuilder.memory().storage(HEAP).maxSize("20"); sizeBuilder.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); Configuration configuration = sizeBuilder.build(); assertEquals(MEMORY, configuration.memory().evictionType()); Queue<Object> sizeListenerQueue = new ArrayDeque<>(1); Queue<Object> maxSizeListenerQueue = new ArrayDeque<>(1); Queue<Object> maxCountListenerQueue = new ArrayDeque<>(1); setUpListeners(configuration, sizeListenerQueue, maxCountListenerQueue, maxSizeListenerQueue); configuration.memory().size(100); assertSizeUpdate(configuration, 100, sizeListenerQueue, maxCountListenerQueue, maxSizeListenerQueue); configuration.memory().heapConfiguration().size(200); assertSizeUpdate(configuration, 200, sizeListenerQueue, maxCountListenerQueue, maxSizeListenerQueue); configuration.memory().maxSize("300"); assertSizeUpdate(configuration, 300, sizeListenerQueue, maxCountListenerQueue, maxSizeListenerQueue); } private void setUpListeners(Configuration configuration, Queue<Object> sizeListenerQueue, Queue<Object> maxCountListenerQueue, Queue<Object> maxSizeListenerQueue) { configuration.memory().heapConfiguration().attributes().attribute(MemoryStorageConfiguration.SIZE) .addListener((attribute, oldValue) -> sizeListenerQueue.add(attribute.get())); configuration.memory().attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((attribute, oldValue) -> maxCountListenerQueue.add(attribute.get())); configuration.memory().attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((attribute, oldValue) -> maxSizeListenerQueue.add(attribute.get())); } private void assertCountUpdate(Configuration configuration, long newValue, Queue<Object> sizeListenerQueue, Queue<Object> maxCountListenerQueue, Queue<Object> maxSizeListenerQueue) { assertEquals(newValue, configuration.memory().size()); assertEquals(newValue, sizeListenerQueue.poll()); assertEquals(newValue, configuration.memory().maxCount()); assertEquals(newValue, maxCountListenerQueue.poll()); assertEquals(-1L, configuration.memory().maxSizeBytes()); assertEquals(0, maxSizeListenerQueue.size()); } private void assertSizeUpdate(Configuration configuration, long newValue, Queue<Object> sizeListenerQueue, Queue<Object> maxCountListenerQueue, Queue<Object> maxSizeListenerQueue) { assertEquals(newValue, configuration.memory().size()); assertEquals(newValue, sizeListenerQueue.poll()); assertEquals(String.valueOf(newValue), configuration.memory().maxSize()); assertEquals(newValue, configuration.memory().maxSizeBytes()); assertEquals(String.valueOf(newValue), maxSizeListenerQueue.poll()); assertEquals(-1L, configuration.memory().maxCount()); assertEquals(0, maxCountListenerQueue.size()); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = ".*Cannot configure both maxCount and maxSize.*") public void testErrorForMultipleThresholds() { ConfigurationBuilder configBuilder = new ConfigurationBuilder(); configBuilder.memory().storage(OFF_HEAP).maxCount(10).maxSize("10TB").build(); } private void testSerializationAndBack(String xml) { // Parse config ConfigurationBuilderHolder configurationBuilderHolder = REGISTRY.parse(xml); ConfigurationBuilder builder = configurationBuilderHolder.getNamedConfigurationBuilders().get("local"); Configuration before = builder.build(); // Serialize the parsed config ByteArrayOutputStream baos = new ByteArrayOutputStream(); REGISTRY.serialize(baos, "local", before); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ConfigurationBuilderHolder holderAfter = REGISTRY.parse(bais, ConfigurationResourceResolvers.DEFAULT, MediaType.APPLICATION_XML); // Parse again from the serialized ConfigurationBuilder afterParsing = holderAfter.getNamedConfigurationBuilders().get("local"); Configuration after = afterParsing.build(); assertEquals(after.memory(), before.memory()); } }
19,998
45.401392
202
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/TxManagerLookupConfigTest.java
package org.infinispan.configuration; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import jakarta.transaction.TransactionManager; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.tm.EmbeddedBaseTransactionManager; import org.testng.annotations.Test; /** * @author Mircea.Markus@jboss.com */ @Test(groups = "functional", testName = "configuration.TxManagerLookupConfigTest") public class TxManagerLookupConfigTest extends AbstractInfinispanTest { static TmA tma = new TmA(); static TmB tmb = new TmB(); public void simpleTest() { withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()){ @Override public void call() { ConfigurationBuilder customConfiguration = TestCacheManagerFactory.getDefaultCacheConfiguration(true); customConfiguration.transaction().transactionManagerLookup(new TxManagerLookupA()); Configuration definedConfiguration = cm.defineConfiguration("aCache", customConfiguration.build()); // verify the setting was not lost: assertTrue(definedConfiguration.transaction().transactionManagerLookup() instanceof TxManagerLookupA); // verify it's actually being used: TransactionManager activeTransactionManager = cm.getCache("aCache").getAdvancedCache().getTransactionManager(); assertNotNull(activeTransactionManager); assertTrue(activeTransactionManager instanceof TmA); } }); } private static class TmA extends EmbeddedBaseTransactionManager {} private static class TmB extends EmbeddedBaseTransactionManager {} public static class TxManagerLookupA implements TransactionManagerLookup { @Override public synchronized TransactionManager getTransactionManager() throws Exception { return tma; } } public static class TxManagerLookupB implements TransactionManagerLookup { @Override public synchronized TransactionManager getTransactionManager() throws Exception { return tmb; } } }
2,522
37.227273
123
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/PersistentConfigurationMatchesTest.java
package org.infinispan.configuration; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.test.AbstractInfinispanTest; import org.testng.AssertJUnit; import org.testng.annotations.Test; /** * @author Ryan Emerson * @since 14.0 */ @Test(groups = "functional", testName= "configuration.PersistentConfigurationMatchesTest") public class PersistentConfigurationMatchesTest extends AbstractInfinispanTest { public void testOldConfigurationMatches() { String cacheName = "someCache"; ParserRegistry parserRegistry = new ParserRegistry(); ConfigurationBuilderHolder oldHolder = parserRegistry.parse("<?xml version=\"1.0\"?>\n" + "<infinispan xmlns=\"urn:infinispan:config:13.0\">\n" + " <cache-container>\n" + " <caches>\n" + " <distributed-cache name=\"someCache\" mode=\"SYNC\">\n" + " <persistence>\n" + " <file-store/>\n" + " </persistence>\n" + " </distributed-cache>\n" + " </caches>\n" + " </cache-container>\n" + "</infinispan>\n"); ConfigurationBuilderHolder newHolder = parserRegistry.parse("<?xml version=\"1.0\"?>\n" + "<infinispan xmlns=\"urn:infinispan:config:14.0\">\n" + " <cache-container>\n" + " <caches>\n" + " <distributed-cache name=\"someCache\" mode=\"SYNC\">\n" + " <persistence>\n" + " <file-store/>\n" + " </persistence>\n" + " </distributed-cache>\n" + " </caches>\n" + " </cache-container>\n" + "</infinispan>\n"); Configuration oldConfig = oldHolder.getNamedConfigurationBuilders().get(cacheName).build(); Configuration newConfig = newHolder.getNamedConfigurationBuilders().get(cacheName).build(); AssertJUnit.assertTrue(oldConfig.matches(newConfig)); } }
2,237
44.673469
97
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/UpdatableConfigurationTest.java
package org.infinispan.configuration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.fail; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.logging.Log; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; @Test(groups = "functional", testName= "configuration.UpdatableConfigurationTest") public class UpdatableConfigurationTest { public void testUpdateConfiguration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.expiration().maxIdle(1000).lifespan(2000); Configuration configuration = builder.build(); // Check that attributes are correct before the update assertEquals(1000, configuration.expiration().maxIdle()); assertEquals(2000, configuration.expiration().lifespan()); builder = new ConfigurationBuilder(); builder.expiration().maxIdle(3000); // Lifespan will be set to the default configuration.update(null, builder.build()); // Check that only the modified attributes have been updated assertEquals(-1, configuration.expiration().lifespan()); assertEquals(3000, configuration.expiration().maxIdle()); } public void testConfigurationComparison() { ConfigurationBuilder b1 = new ConfigurationBuilder(); b1.encoding().mediaType(MediaType.TEXT_PLAIN.toString()); Configuration c1 = b1.build(); ConfigurationBuilder b2 = new ConfigurationBuilder(); b2.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE.toString()); Configuration c2 = b2.build(); try { c1.validateUpdate(null, c2); fail("Expected exception"); } catch (Throwable t) { assertEquals(IllegalArgumentException.class, t.getClass()); assertEquals(Log.CONFIG.invalidConfiguration("local-cache").getMessage(), t.getMessage()); Throwable[] suppressed = t.getSuppressed(); assertEquals(1, suppressed.length); assertEquals(Log.CONFIG.incompatibleAttribute("local-cache.encoding", "media-type", "text/plain", "application/x-protostream").getMessage(), suppressed[0].getMessage()); } } }
2,269
42.653846
178
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/XSiteParsingTest.java
package org.infinispan.configuration; import static org.infinispan.commons.test.Exceptions.expectException; import static org.infinispan.test.TestingUtil.extractGlobalComponent; import static org.infinispan.test.TestingUtil.wrapXMLWithSchema; import static org.testng.AssertJUnit.assertTrue; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.remoting.transport.Transport; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.Test; /** * Parsing tests for Cross-Site * * @since 14.0 */ @Test(groups = "functional", testName = "xsite.XSiteParsingTest") public class XSiteParsingTest extends AbstractInfinispanTest { // https://issues.redhat.com/browse/ISPN-13623 reproducer public void testMultipleStackParents() throws IOException { String config = wrapXMLWithSchema( "<jgroups>" + "<stack name=\"parent\" extends=\"udp\">" + " <UDP mcast_port=\"54444\"/>" + "</stack>" + "<stack name=\"bridge\" extends=\"tcp\">" + " <MPING mcast_port=\"55555\" />" + "</stack>" + "<stack name=\"xsite\" extends=\"parent\">" + " <relay.RELAY2 site=\"a\" />" + " <remote-sites default-stack=\"bridge\">" + " <remote-site name=\"a\" />" + " <remote-site name=\"b\" />" + " </remote-sites>" + "</stack>" + "</jgroups>" + "<cache-container>" + " <transport cluster=\"multiple-parent-stack\" stack=\"xsite\"/>" + "</cache-container>" ); try (DefaultCacheManager cm = new DefaultCacheManager(new ByteArrayInputStream(config.getBytes(StandardCharsets.UTF_8)))) { // just to make sure the DefaultCacheManager starts. assertTrue(extractGlobalComponent(cm, Transport.class).isSiteCoordinator()); } } public void testInvalidMaxTombstoneCleanupDelay() { String config1 = wrapXMLWithSchema( "<cache-container>" + " <transport/>" + " <distributed-cache name=\"A\">" + " <backups max-cleanup-delay=\"-1\"/>" + " </distributed-cache>" + "</cache-container>" ); assertCacheConfigurationException(config1, "A", "ISPN000951: Invalid value -1 for attribute max-cleanup-delay: must be a number greater than zero"); String config2 = wrapXMLWithSchema( "<cache-container>" + " <transport/>" + " <distributed-cache name=\"B\">" + " <backups max-cleanup-delay=\"0\"/>" + " </distributed-cache>" + "</cache-container>" ); assertCacheConfigurationException(config2, "B", "ISPN000951: Invalid value 0 for attribute max-cleanup-delay: must be a number greater than zero"); } private void assertCacheConfigurationException(String config, String cacheName, String messageRegex) { ParserRegistry parserRegistry = new ParserRegistry(); ConfigurationBuilderHolder holder = parserRegistry.parse(config); GlobalConfiguration globalConfiguration = holder.getGlobalConfigurationBuilder().build(); ConfigurationBuilder builder = holder.getNamedConfigurationBuilders().get(cacheName); expectException(CacheConfigurationException.class, messageRegex, builder::validate); expectException(CacheConfigurationException.class, messageRegex, () -> builder.validate(globalConfiguration)); } }
4,128
44.877778
154
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/StringPropertyReplacementTest.java
package org.infinispan.configuration; import static org.testng.AssertJUnit.assertEquals; import java.util.Properties; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.factories.threads.EnhancedQueueExecutorFactory; import org.infinispan.remoting.transport.jgroups.FileJGroupsChannelConfigurator; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; /** * /** * Tests that string property replacement works properly when parsing * a config file. * * @author Mircea.Markus@jboss.com */ @Test (groups = "functional", testName = "configuration.StringPropertyReplacementTest") public class StringPropertyReplacementTest extends AbstractInfinispanTest { protected ConfigurationBuilderHolder parse() throws Exception { Properties properties = new Properties(); properties.setProperty("StringPropertyReplacementTest.asyncListenerMaxThreads","2"); properties.setProperty("StringPropertyReplacementTest.persistenceMaxThreads","4"); properties.setProperty("StringPropertyReplacementTest.IsolationLevel","READ_COMMITTED"); properties.setProperty("StringPropertyReplacementTest.writeSkewCheck","true"); properties.setProperty("StringPropertyReplacementTest.SyncCommitPhase","true"); ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader(), true, properties); return parserRegistry.parseFile("configs/string-property-replaced.xml"); } public void testGlobalConfig() throws Exception { ConfigurationBuilderHolder holder = parse(); GlobalConfiguration gc = holder.getGlobalConfigurationBuilder().build(); EnhancedQueueExecutorFactory listenerThreadPool = gc.listenerThreadPool().threadPoolFactory(); assertEquals(2, listenerThreadPool.maxThreads()); EnhancedQueueExecutorFactory blockingThreadPool = gc.blockingThreadPool().threadPoolFactory(); assertEquals(4, blockingThreadPool.maxThreads()); FileJGroupsChannelConfigurator transportConfigurator = (FileJGroupsChannelConfigurator) gc.transport().jgroups().configurator(gc.transport().stack()); assertEquals("stacks/tcp.xml", transportConfigurator.getPath()); Configuration configuration = holder.getDefaultConfigurationBuilder().build(); assertEquals(IsolationLevel.READ_COMMITTED, configuration.locking().isolationLevel()); } }
2,680
46.875
156
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/TransactionalCacheConfigTest.java
package org.infinispan.configuration; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.Assert.assertEquals; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "configuration.TransactionalCacheConfigTest") public class TransactionalCacheConfigTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.createCacheManager(getDefaultStandaloneCacheConfig(true)); } public void test() { final ConfigurationBuilder c = TestCacheManagerFactory.getDefaultCacheConfiguration(false); assert !c.build().transaction().transactionMode().isTransactional(); c.transaction().transactionMode(TransactionMode.TRANSACTIONAL); assert c.build().transaction().transactionMode().isTransactional(); c.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL); assert !c.build().transaction().transactionMode().isTransactional(); } public void testTransactionModeOverride() { ConfigurationBuilder c = new ConfigurationBuilder(); c.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL); assertEquals(TransactionMode.TRANSACTIONAL, cacheManager.getCache().getCacheConfiguration().transaction().transactionMode()); cacheManager.defineConfiguration("nonTx", c.build()); assertEquals(TransactionMode.NON_TRANSACTIONAL, cacheManager.getCache("nonTx").getCacheConfiguration().transaction().transactionMode()); } public void testDefaults() { Configuration c = new ConfigurationBuilder().build(); assert !c.transaction().transactionMode().isTransactional(); c = TestCacheManagerFactory.getDefaultCacheConfiguration(false).build(); assert !c.transaction().transactionMode().isTransactional(); c = TestCacheManagerFactory.getDefaultCacheConfiguration(true).build(); assert c.transaction().transactionMode().isTransactional(); c = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false).build(); assert !c.transaction().transactionMode().isTransactional(); c = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true).build(); assert c.transaction().transactionMode().isTransactional(); } public void testTransactionalityInduced() { ConfigurationBuilder cb = new ConfigurationBuilder(); Configuration c = cb.build(); assert !c.transaction().transactionMode().isTransactional(); c = cb.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup()).build(); assert c.transaction().transactionMode().isTransactional(); cb = new ConfigurationBuilder(); cb.invocationBatching().enable(); assert cb.build().transaction().transactionMode().isTransactional(); } public void testInvocationBatchingAndInducedTm() { final ConfigurationBuilder cb = new ConfigurationBuilder(); cb.invocationBatching().enable(); assert cb.build().transaction().transactionMode().isTransactional(); withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager(cb)){ @Override public void call() { assert cm.getCache().getAdvancedCache().getTransactionManager() != null; } }); } public void testOverride() { final ConfigurationBuilder c = new ConfigurationBuilder(); c.transaction().transactionMode(TransactionMode.TRANSACTIONAL) .transactionManagerLookup(new EmbeddedTransactionManagerLookup()); withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()){ @Override public void call() { cm.defineConfiguration("transactional", c.build()); Cache<?, ?> cache = cm.getCache("transactional"); assert cache.getCacheConfiguration().transaction().transactionMode().isTransactional(); } }); } public void testBatchingAndTransactionalCache() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.invocationBatching().enable(); final Configuration c = cb.build(); assert c.invocationBatching().enabled(); assert c.transaction().transactionMode().isTransactional(); withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder())) { @Override public void call() { assert !cm.getCache().getCacheConfiguration().transaction().transactionMode().isTransactional(); cm.defineConfiguration("a", c); final Cache<Object, Object> a = cm.getCache("a"); assert a.getCacheConfiguration().invocationBatching().enabled(); assert a.getCacheConfiguration().transaction().transactionMode().isTransactional(); } }); } }
5,461
42.349206
142
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/XSiteFileParsing2Test.java
package org.infinispan.configuration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupConfiguration.BackupStrategy; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.Configuration; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "functional", testName = "xsite.XSiteFileParsing2Test") public class XSiteFileParsing2Test extends SingleCacheManagerTest { public static final String FILE_NAME = "configs/xsite/xsite-test2.xml"; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.fromXml(FILE_NAME, false, true, TransportFlags.minimalXsiteFlags()); } public void testDefaultCache() { Configuration dcc = cacheManager.getDefaultCacheConfiguration(); assertEquals(dcc.sites().allBackups().size(), 3); testDefault(dcc); } public void testInheritor() { Configuration dcc = cacheManager.getCacheConfiguration("inheritor"); testDefault(dcc); } private void testDefault(Configuration dcc) { BackupConfiguration nyc = new BackupConfigurationBuilder(null).site("NYC").strategy(BackupStrategy.SYNC) .backupFailurePolicy(BackupFailurePolicy.IGNORE).failurePolicyClass(null).replicationTimeout(12003) .useTwoPhaseCommit(false).create(); BackupConfiguration sfo = new BackupConfigurationBuilder(null).site("SFO").strategy(BackupStrategy.ASYNC) .backupFailurePolicy(BackupFailurePolicy.WARN).failurePolicyClass(null).replicationTimeout(15000) .useTwoPhaseCommit(false).create(); BackupConfiguration lon = new BackupConfigurationBuilder(null).site("LON").strategy(BackupStrategy.SYNC) .backupFailurePolicy(BackupFailurePolicy.WARN).failurePolicyClass(null).replicationTimeout(15000) .useTwoPhaseCommit(false).create(); assertTrue(dcc.sites().allBackups().contains(nyc)); assertTrue(dcc.sites().allBackups().contains(sfo)); assertTrue(dcc.sites().allBackups().contains(lon)); assertEquals("someCache", dcc.sites().backupFor().remoteCache()); assertEquals("SFO", dcc.sites().backupFor().remoteSite()); } }
2,685
43.766667
111
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/XSiteInlineConfigFileParsingTest.java
package org.infinispan.configuration; import static org.infinispan.test.TestingUtil.extractGlobalComponent; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.configuration.cache.BackupConfiguration.BackupStrategy; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.Transport; import org.infinispan.remoting.transport.jgroups.JGroupsTransport; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.jgroups.protocols.relay.RELAY2; import org.testng.annotations.Test; @Test(groups = "functional", testName = "xsite.XSiteInlineConfigFileParsingTest") public class XSiteInlineConfigFileParsingTest extends SingleCacheManagerTest { public static final String FILE_NAME = "configs/xsite/xsite-inline-test.xml"; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilderHolder holder = TestCacheManagerFactory.parseFile(FILE_NAME, false); TransportFlags flags = new TransportFlags().withPreserveConfig(true); return TestCacheManagerFactory.createClusteredCacheManager(false, holder, flags); } public void testInlineConfiguration() { GlobalConfiguration cmc = cacheManager.getCacheManagerConfiguration(); JGroupsTransport transport = (JGroupsTransport) extractGlobalComponent(cacheManager, Transport.class); RELAY2 relay2 = transport.getChannel().getProtocolStack().findProtocol(RELAY2.class); assertEquals(3, relay2.getSites().size()); assertTrue(relay2.getSites().contains("LON")); assertTrue(relay2.getSites().contains("SFO")); assertTrue(relay2.getSites().contains("NYC")); Configuration dcc = cacheManager.getDefaultCacheConfiguration(); assertEquals(dcc.sites().allBackups().size(), 2); BackupConfigurationBuilder nyc = new BackupConfigurationBuilder(null).site("NYC").strategy(BackupStrategy.SYNC) .backupFailurePolicy(BackupFailurePolicy.IGNORE).failurePolicyClass(null).replicationTimeout(12003) .useTwoPhaseCommit(false); assertTrue(dcc.sites().allBackups().contains(nyc.create())); BackupConfigurationBuilder sfo = new BackupConfigurationBuilder(null).site("SFO").strategy(BackupStrategy.ASYNC) .backupFailurePolicy(BackupFailurePolicy.WARN).failurePolicyClass(null).replicationTimeout(15000) .useTwoPhaseCommit(false); assertTrue(dcc.sites().allBackups().contains(sfo.create())); } }
2,950
52.654545
118
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/DifferentCacheModesTest.java
package org.infinispan.configuration; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(testName = "configuration.DifferentCacheModesTest", groups = "unit") public class DifferentCacheModesTest extends AbstractInfinispanTest { public void testCacheModes() { EmbeddedCacheManager cm = null; try { String xml = "<infinispan>" + "<jgroups/>" + "<cache-container name=\"different-cache-modes\" default-cache=\"replicated\">" + "<replicated-cache name=\"replicated\" mode=\"SYNC\"></replicated-cache>" + "<local-cache name=\"local\"></local-cache>" + "<distributed-cache name=\"dist\" mode=\"SYNC\"></distributed-cache>" + "<distributed-cache name=\"distasync\" mode=\"ASYNC\"></distributed-cache>" + "<replicated-cache name=\"replicationasync\" mode=\"ASYNC\"></replicated-cache>" + "</cache-container>" + "</infinispan>"; InputStream is = new ByteArrayInputStream(xml.getBytes()); cm = TestCacheManagerFactory.fromStream(is); GlobalConfiguration gc = cm.getCacheManagerConfiguration(); Configuration defaultCfg = cm.getCache().getCacheConfiguration(); assert gc.transport().transport() != null; assert defaultCfg.clustering().cacheMode() == CacheMode.REPL_SYNC; Configuration cfg = cm.getCache("local").getCacheConfiguration(); assert cfg.clustering().cacheMode() == CacheMode.LOCAL; cfg = cm.getCache("dist").getCacheConfiguration(); assert cfg.clustering().cacheMode() == CacheMode.DIST_SYNC; cfg = cm.getCache("distasync").getCacheConfiguration(); assert cfg.clustering().cacheMode() == CacheMode.DIST_ASYNC; cfg = cm.getCache("replicationasync").getCacheConfiguration(); assert cfg.clustering().cacheMode() == CacheMode.REPL_ASYNC; } finally { TestingUtil.killCacheManagers(cm); } } public void testReplicationAndStateTransfer() throws IOException { EmbeddedCacheManager cm = null; try { String xml = "<infinispan>" + "<jgroups/>" + "<cache-container name=\"different-cache-modes\" default-cache=\"replicated\">" + "<replicated-cache name=\"replicated\" mode=\"SYNC\"/>" + "<replicated-cache name=\"explicit-state-disable\" mode=\"SYNC\">" + "<state-transfer enabled=\"false\"/>" + "</replicated-cache>" + "<replicated-cache name=\"explicit-state-enable\" mode=\"SYNC\">" + "<state-transfer enabled=\"true\"/>" + "</replicated-cache>" + "<replicated-cache name=\"explicit-state-enable-async\" mode=\"ASYNC\">" + "<state-transfer enabled=\"true\"/>" + "</replicated-cache>" + "</cache-container>" + "</infinispan>"; InputStream is = new ByteArrayInputStream(xml.getBytes()); cm = TestCacheManagerFactory.fromStream(is); GlobalConfiguration gc = cm.getCacheManagerConfiguration(); Configuration defaultCfg = cm.getCache().getCacheConfiguration(); assert defaultCfg.clustering().cacheMode() == CacheMode.REPL_SYNC; assert defaultCfg.clustering().stateTransfer().fetchInMemoryState(); Configuration explicitDisable = cm.getCache("explicit-state-disable").getCacheConfiguration(); assert explicitDisable.clustering().cacheMode() == CacheMode.REPL_SYNC; assert !explicitDisable.clustering().stateTransfer().fetchInMemoryState(); Configuration explicitEnable = cm.getCache("explicit-state-enable").getCacheConfiguration(); assert explicitEnable.clustering().cacheMode() == CacheMode.REPL_SYNC; assert explicitEnable.clustering().stateTransfer().fetchInMemoryState(); Configuration explicitEnableAsync = cm.getCache("explicit-state-enable-async").getCacheConfiguration(); assert explicitEnableAsync.clustering().cacheMode() == CacheMode.REPL_ASYNC; assert explicitEnableAsync.clustering().stateTransfer().fetchInMemoryState(); } finally { TestingUtil.killCacheManagers(cm); } } }
4,833
44.17757
99
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/cache/L1ConfigurationBuilderTest.java
package org.infinispan.configuration.cache; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.concurrent.TimeUnit; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.eviction.EvictionStrategy; import org.testng.annotations.Test; /** * Tests to ensure the L1 Configuration builder operates properly * * @author William Burns * @since 7.0 */ @Test(groups = "functional", testName = "configuration.cache.L1ConfigurationBuilderTest") public class L1ConfigurationBuilderTest { public void testDefaultsWhenEnabledOnly() { Configuration config = new ConfigurationBuilder().clustering().cacheMode(CacheMode.DIST_SYNC).l1().enable().build(); L1Configuration l1Config = config.clustering().l1(); assertTrue(l1Config.enabled()); assertEquals(l1Config.cleanupTaskFrequency(), TimeUnit.MINUTES.toMillis(1)); assertEquals(l1Config.invalidationThreshold(), 0); assertEquals(l1Config.lifespan(), TimeUnit.MINUTES.toMillis(10)); } @Test(expectedExceptions = CacheConfigurationException.class) public void testL1WithExceptionEviction() { Configuration config = new ConfigurationBuilder() .clustering() .cacheMode(CacheMode.DIST_SYNC) .l1().enable() .memory() .evictionStrategy(EvictionStrategy.EXCEPTION) .size(10) .transaction() .transactionMode(org.infinispan.transaction.TransactionMode.TRANSACTIONAL) .build(); assertNotNull(config); } }
1,656
34.255319
122
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/cache/IndexingConfigurationBuilderTest.java
package org.infinispan.configuration.cache; import static org.testng.AssertJUnit.assertFalse; import static org.wildfly.common.Assert.assertTrue; import java.util.Arrays; import org.infinispan.commons.configuration.Combine; import org.testng.annotations.Test; /** * @since 15.0 **/ @Test(testName = "configuration.cache.IndexingConfigurationBuilderTest", groups = "unit") public class IndexingConfigurationBuilderTest { public void testIndexingEntitiesMerge() { ConfigurationBuilder one = new ConfigurationBuilder(); one.indexing().enable().addIndexedEntities("a", "b"); ConfigurationBuilder two = new ConfigurationBuilder(); two.indexing().enable().addIndexedEntities("c", "d"); two.indexing().read(one.indexing().create(), new Combine(Combine.RepeatedAttributes.MERGE, Combine.Attributes.MERGE)); IndexingConfiguration cfg = two.indexing().create(); assertTrue(cfg.indexedEntityTypes().containsAll(Arrays.asList("a", "b", "c", "d"))); } public void testIndexingEntitiesOverride() { ConfigurationBuilder one = new ConfigurationBuilder(); one.indexing().enable().addIndexedEntities("a", "b"); ConfigurationBuilder two = new ConfigurationBuilder(); two.indexing().enable().addIndexedEntities("c", "d"); two.indexing().read(one.indexing().create(), new Combine(Combine.RepeatedAttributes.OVERRIDE, Combine.Attributes.MERGE)); IndexingConfiguration cfg = two.indexing().create(); assertTrue(cfg.indexedEntityTypes().contains("a")); assertTrue(cfg.indexedEntityTypes().contains("b")); assertFalse(cfg.indexedEntityTypes().contains("c")); assertFalse(cfg.indexedEntityTypes().contains("d")); } }
1,712
42.923077
127
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/parsing/UnifiedXmlFileParsingTest.java
package org.infinispan.configuration.parsing; import static org.assertj.core.api.Assertions.assertThat; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertSame; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.executors.ScheduledThreadPoolExecutorFactory; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.commons.util.Version; import org.infinispan.configuration.cache.AsyncStoreConfiguration; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ClusterLoaderConfiguration; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.EncodingConfiguration; import org.infinispan.configuration.cache.IndexStartupMode; import org.infinispan.configuration.cache.IndexStorage; import org.infinispan.configuration.cache.IndexingConfiguration; import org.infinispan.configuration.cache.IndexingMode; import org.infinispan.configuration.cache.InterceptorConfiguration; import org.infinispan.configuration.cache.MemoryConfiguration; import org.infinispan.configuration.cache.PartitionHandlingConfiguration; import org.infinispan.configuration.cache.PersistenceConfiguration; import org.infinispan.configuration.cache.QueryConfiguration; import org.infinispan.configuration.cache.SingleFileStoreConfiguration; import org.infinispan.configuration.cache.StorageType; import org.infinispan.configuration.cache.StoreConfiguration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalStateConfiguration; import org.infinispan.configuration.global.JGroupsConfiguration; import org.infinispan.configuration.global.ShutdownHookBehavior; import org.infinispan.configuration.global.TransportConfiguration; import org.infinispan.conflict.MergePolicy; import org.infinispan.distribution.ch.impl.CRC16HashFunctionPartitioner; import org.infinispan.distribution.ch.impl.HashFunctionPartitioner; import org.infinispan.distribution.ch.impl.SyncConsistentHashFactory; import org.infinispan.eviction.EvictionStrategy; import org.infinispan.eviction.EvictionType; import org.infinispan.factories.threads.AbstractThreadPoolExecutorFactory; import org.infinispan.factories.threads.DefaultThreadFactory; import org.infinispan.factories.threads.EnhancedQueueExecutorFactory; import org.infinispan.globalstate.ConfigurationStorage; import org.infinispan.interceptors.BaseCustomAsyncInterceptor; import org.infinispan.interceptors.impl.InvocationContextInterceptor; import org.infinispan.jmx.CustomMBeanServerPropertiesTest; import org.infinispan.marshall.AdvancedExternalizerTest; import org.infinispan.marshall.TestObjectStreamMarshaller; import org.infinispan.partitionhandling.PartitionHandling; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfiguration; import org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfiguration; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.TransactionMode; import org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup; import org.infinispan.util.concurrent.IsolationLevel; import org.jgroups.conf.ProtocolConfiguration; import org.jgroups.conf.ProtocolStackConfigurator; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @Test(groups = "unit", testName = "configuration.parsing.UnifiedXmlFileParsingTest") public class UnifiedXmlFileParsingTest extends AbstractInfinispanTest { public static final String TMPDIR = System.getProperty("java.io.tmpdir"); @DataProvider(name = "configurationFiles") public Object[][] configurationFiles() throws Exception { URL configDir = Thread.currentThread().getContextClassLoader().getResource("configs/all"); List<Path> paths = Files.list(Paths.get(configDir.toURI())).collect(Collectors.toList()); Object[][] configurationFiles = new Object[paths.size()][]; boolean hasCurrentSchema = false; for (int i = 0; i < paths.size(); i++) { if (paths.get(i).getFileName().toString().equals(Version.getSchemaVersion() + ".xml")) { hasCurrentSchema = true; } configurationFiles[i] = new Object[]{paths.get(i)}; } // Ensure that we contain the current schema version at the very least assertTrue("Could not find a '" + Version.getSchemaVersion() + ".xml' configuration file", hasCurrentSchema); return configurationFiles; } @Test(dataProvider = "configurationFiles") public void testParseAndConstructUnifiedXmlFile(Path config) throws IOException { String[] parts = config.getFileName().toString().split("\\."); int major = Integer.parseInt(parts[0]); int minor = Integer.parseInt(parts[1]); Properties properties = new Properties(); properties.put("jboss.server.temp.dir", TMPDIR); ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader(), false, properties); URL url = FileLookupFactory.newInstance().lookupFileLocation(config.toString(), Thread.currentThread().getContextClassLoader()); ConfigurationBuilderHolder holder = parserRegistry.parse(url); for (ParserVersionCheck check : ParserVersionCheck.values()) { if (check.isIncludedBy(major, minor)) { check.check(holder, major, minor); } } } public enum ParserVersionCheck { INFINISPAN_150(15, 0) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { IndexingConfiguration indexed = getConfiguration(holder, "indexed-manual-indexing").indexing(); assertThat(indexed.enabled()).isTrue(); assertThat(indexed.indexingMode()).isEqualTo(IndexingMode.MANUAL); assertThat(indexed.sharding()).isNotNull(); assertThat(indexed.sharding().getShards()).isEqualTo(7); QueryConfiguration query = getConfiguration(holder, "local").query(); assertThat(query.hitCountAccuracy()).isEqualTo(10_000); Configuration configuration = getConfiguration(holder, "repl"); assertThat(configuration.clustering().hash().keyPartitioner().getClass()).isEqualTo(CRC16HashFunctionPartitioner.class); configuration = getConfiguration(holder, "dist"); assertThat(configuration.clustering().hash().keyPartitioner().getClass()).isEqualTo(HashFunctionPartitioner.class); query = getConfiguration(holder, "custom-default-max-results").query(); assertThat(query.hitCountAccuracy()).isEqualTo(1000); } }, INFINISPAN_140(14, 0) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { GlobalConfiguration config = getGlobalConfiguration(holder); Collection<String> raftMembers = config.transport().raftMembers(); assertEquals(2, raftMembers.size()); assertTrue(raftMembers.contains("a-node")); assertTrue(raftMembers.contains("b-node")); QueryConfiguration query = getConfiguration(holder, "local").query(); assertThat(query.defaultMaxResults()).isEqualTo(100); IndexingConfiguration indexed = getConfiguration(holder, "indexed-reindex-at-startup").indexing(); assertThat(indexed.enabled()).isTrue(); assertThat(indexed.storage()).isEqualTo(IndexStorage.LOCAL_HEAP); assertThat(indexed.startupMode()).isEqualTo(IndexStartupMode.REINDEX); assertThat(indexed.indexedEntityTypes()).containsExactly("TheEntity"); query = getConfiguration(holder, "custom-default-max-results").query(); assertThat(query.defaultMaxResults()).isEqualTo(10); } }, INFINISPAN_130(13, 0) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { Configuration local = getConfiguration(holder, "local"); PersistenceConfiguration persistenceConfiguration = local.persistence(); StoreConfiguration storeConfiguration = persistenceConfiguration.stores().get(0); Properties storeProperties = storeConfiguration.properties(); String value = storeProperties.getProperty("test_property"); assertEquals("foo_bar", value); } }, INFINISPAN_120(12, 0) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { TransportConfiguration tc = getGlobalConfiguration(holder).transport(); assertTrue(tc.properties().size() >= 1); assertEquals("value", tc.properties().getProperty("key")); } }, INFINISPAN_110(11, 0) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { DefaultThreadFactory threadFactory; threadFactory = getGlobalConfiguration(holder).nonBlockingThreadPool().threadFactory(); assertEquals("infinispan", threadFactory.threadGroup().getName()); assertEquals("%G %i", threadFactory.threadNamePattern()); assertEquals(5, threadFactory.initialPriority()); AbstractThreadPoolExecutorFactory threadPool = getGlobalConfiguration(holder).nonBlockingThreadPool().threadPoolFactory(); assertEquals(12, threadPool.coreThreads()); assertEquals(15, threadPool.maxThreads()); assertEquals(132, threadPool.queueLength()); assertEquals(9851, threadPool.keepAlive()); threadFactory = getGlobalConfiguration(holder).blockingThreadPool().threadFactory(); assertEquals("infinispan", threadFactory.threadGroup().getName()); assertEquals("%G %i", threadFactory.threadNamePattern()); assertEquals(5, threadFactory.initialPriority()); EnhancedQueueExecutorFactory blockingPool = getGlobalConfiguration(holder).blockingThreadPool().threadPoolFactory(); assertEquals(3, blockingPool.coreThreads()); assertEquals(8, blockingPool.maxThreads()); assertEquals(121, blockingPool.queueLength()); assertEquals(9859, blockingPool.keepAlive()); IndexingConfiguration indexed = getConfiguration(holder, "indexed").indexing(); assertTrue(indexed.enabled()); Set<String> entityTypes = indexed.indexedEntityTypes(); assertEquals(2, entityTypes.size()); assertTrue(entityTypes.contains("TheEntity")); assertTrue(entityTypes.contains("AnotherEntity")); Configuration minimalOffHeap = getConfiguration(holder, "minimal-offheap"); assertEquals(StorageType.OFF_HEAP, minimalOffHeap.memory().storageType()); Configuration mediaTypeCascade = getConfiguration(holder, "media_type_cascade"); assertEquals(MediaType.APPLICATION_JSON, mediaTypeCascade.encoding().keyDataType().mediaType()); assertEquals(MediaType.APPLICATION_JSON, mediaTypeCascade.encoding().valueDataType().mediaType()); Configuration heapBinary = getConfiguration(holder, "heap_binary"); assertEquals(MediaType.APPLICATION_PROTOSTREAM, heapBinary.encoding().keyDataType().mediaType()); assertEquals(StorageType.HEAP, heapBinary.memory().storageType()); assertEquals(EvictionStrategy.REMOVE, heapBinary.memory().evictionStrategy()); assertEquals(1_500_000_000, heapBinary.memory().maxSizeBytes()); assertEquals(MediaType.APPLICATION_PROTOSTREAM, heapBinary.encoding().keyDataType().mediaType()); assertEquals(MediaType.APPLICATION_PROTOSTREAM, heapBinary.encoding().valueDataType().mediaType()); } }, INFINISPAN_100(10, 0) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { JGroupsConfiguration jgroups = holder.getGlobalConfigurationBuilder().transport().jgroups().create(); // tcp-test and mytcp should be identical aside from MERGE3.max_interval ProtocolStackConfigurator tcp = jgroups.configurator("tcp-test"); ProtocolStackConfigurator mytcp = jgroups.configurator("mytcp"); List<ProtocolConfiguration> tcpProtocolStack = tcp.getProtocolStack(); List<ProtocolConfiguration> mytcpProtocolStack = mytcp.getProtocolStack(); assertEquals(tcpProtocolStack.size(), mytcpProtocolStack.size()); for (int i = 0; i < tcpProtocolStack.size(); i++) { ProtocolConfiguration proto1 = tcpProtocolStack.get(i); ProtocolConfiguration proto2 = mytcpProtocolStack.get(i); assertEquals(proto1.getProtocolName(), proto2.getProtocolName()); if (proto1.getProtocolName().equals("FD_ALL") || proto1.getProtocolName().equals("FD_ALL3")) { assertEquals("tcp>FD_ALL>timeout", "3000", proto1.getProperties().get("timeout")); assertEquals("tcp>FD_ALL>interval", "1000", proto1.getProperties().get("interval")); assertEquals("mytcp>FD_ALL>timeout", "3500", proto2.getProperties().get("timeout")); assertEquals("mytcp>FD_ALL>interval", "1000", proto2.getProperties().get("interval")); } else { assertEquals(proto1.getProtocolName(), proto1.getProperties(), proto2.getProperties()); } } // tcp and tcpgossip should differ only in the PING protocol ProtocolStackConfigurator tcpgossip = jgroups.configurator("tcpgossip"); List<ProtocolConfiguration> tcpgossipProtocolStack = tcpgossip.getProtocolStack(); assertEquals(tcpProtocolStack.size(), tcpgossipProtocolStack.size()); for (int i = 0; i < tcpProtocolStack.size(); i++) { ProtocolConfiguration proto1 = tcpProtocolStack.get(i); ProtocolConfiguration proto2 = tcpgossipProtocolStack.get(i); if (proto1.getProtocolName().equals("MPING")) { assertEquals("TCPGOSSIP", proto2.getProtocolName()); } else { assertEquals(proto1.getProtocolName(), proto2.getProtocolName()); assertEquals(proto1.getProtocolName(), proto1.getProperties(), proto2.getProperties()); } } } }, INFINISPAN_93(9, 3) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { Configuration local = getConfiguration(holder, "local"); PersistenceConfiguration persistenceConfiguration = local.persistence(); assertEquals(5, persistenceConfiguration.connectionAttempts()); assertEquals(2000, persistenceConfiguration.availabilityInterval()); assertFalse(persistenceConfiguration.stores().isEmpty()); AsyncStoreConfiguration asyncConfig = persistenceConfiguration.stores().iterator().next().async(); assertTrue(asyncConfig.failSilently()); } }, INFINISPAN_92(9, 2) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { GlobalStateConfiguration gs = getGlobalConfiguration(holder).globalState(); assertEquals(ConfigurationStorage.OVERLAY, gs.configurationStorage()); assertEquals(Paths.get(TMPDIR, "sharedPath").toString(), gs.sharedPersistentLocation()); EncodingConfiguration encoding = getConfiguration(holder, "local").encoding(); assertEquals(MediaType.APPLICATION_OBJECT, encoding.keyDataType().mediaType()); assertEquals(MediaType.APPLICATION_OBJECT, encoding.valueDataType().mediaType()); MemoryConfiguration memory = getConfiguration(holder, "dist-template").memory(); assertEquals(EvictionStrategy.REMOVE, memory.evictionStrategy()); } }, INFINISPAN_91(9, 1) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { PartitionHandlingConfiguration ph = getConfiguration(holder, "dist").clustering().partitionHandling(); assertEquals(PartitionHandling.ALLOW_READS, ph.whenSplit()); assertEquals(MergePolicy.PREFERRED_NON_NULL, ph.mergePolicy()); ph = getConfiguration(holder, "repl").clustering().partitionHandling(); assertEquals(PartitionHandling.ALLOW_READ_WRITES, ph.whenSplit()); assertEquals(MergePolicy.NONE, ph.mergePolicy()); } }, INFINISPAN_90(9, 0) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { GlobalConfiguration globalConfiguration = getGlobalConfiguration(holder); assertEquals(4, globalConfiguration.transport().initialClusterSize()); assertEquals(30000, globalConfiguration.transport().initialClusterTimeout()); MemoryConfiguration mc = getConfiguration(holder, "off-heap-memory").memory(); assertEquals(StorageType.OFF_HEAP, mc.storageType()); assertEquals(10000000, mc.size()); assertEquals(EvictionType.MEMORY, mc.evictionType()); mc = getConfiguration(holder, "binary-memory").memory(); assertEquals(StorageType.BINARY, mc.storageType()); assertEquals(1, mc.size()); mc = getConfiguration(holder, "object-memory").memory(); assertEquals(StorageType.OBJECT, mc.storageType()); } }, INFINISPAN_85(8, 5) { @Override public boolean isIncludedBy(int major, int minor) { return (major == this.major && minor >= this.minor); } @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { GlobalStateConfiguration gs = getGlobalConfiguration(holder).globalState(); assertEquals(ConfigurationStorage.OVERLAY, gs.configurationStorage()); assertEquals(Paths.get(TMPDIR, "sharedPath").toString(), gs.sharedPersistentLocation()); EncodingConfiguration encoding = getConfiguration(holder, "local").encoding(); assertEquals(MediaType.APPLICATION_OBJECT, encoding.keyDataType().mediaType()); assertEquals(MediaType.APPLICATION_OBJECT, encoding.valueDataType().mediaType()); PartitionHandlingConfiguration ph = getConfiguration(holder, "dist").clustering().partitionHandling(); assertEquals(PartitionHandling.ALLOW_READS, ph.whenSplit()); assertEquals(MergePolicy.PREFERRED_NON_NULL, ph.mergePolicy()); ph = getConfiguration(holder, "repl").clustering().partitionHandling(); assertEquals(PartitionHandling.ALLOW_READ_WRITES, ph.whenSplit()); assertEquals(MergePolicy.NONE, ph.mergePolicy()); MemoryConfiguration mc = getConfiguration(holder, "off-heap-memory").memory(); assertEquals(StorageType.OFF_HEAP, mc.storageType()); assertEquals(10000000, mc.size()); assertEquals(EvictionType.MEMORY, mc.evictionType()); mc = getConfiguration(holder, "binary-memory").memory(); assertEquals(StorageType.BINARY, mc.storageType()); assertEquals(1, mc.size()); mc = getConfiguration(holder, "object-memory").memory(); assertEquals(StorageType.OBJECT, mc.storageType()); } }, INFINISPAN_84(8, 4) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { // Nothing new } }, INFINISPAN_83(8, 3) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { // Nothing new } }, INFINISPAN_82(8, 2) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { GlobalConfiguration globalConfiguration = getGlobalConfiguration(holder); assertEquals(4, globalConfiguration.transport().initialClusterSize()); assertEquals(30000, globalConfiguration.transport().initialClusterTimeout()); } }, INFINISPAN_81(8, 1) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { GlobalConfiguration globalConfiguration = getGlobalConfiguration(holder); assertTrue(globalConfiguration.globalState().enabled()); assertEquals(Paths.get(TMPDIR, "persistentPath").toString(), globalConfiguration.globalState().persistentLocation()); assertEquals(Paths.get(TMPDIR, "tmpPath").toString(), globalConfiguration.globalState().temporaryLocation()); } }, INFINISPAN_80(8, 0) { @Override public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { Configuration c = holder.getDefaultConfigurationBuilder().build(); assertFalse(c.memory().evictionType() == EvictionType.MEMORY); c = getConfiguration(holder, "invalid"); assertTrue(c.memory().evictionType() == EvictionType.COUNT); DefaultThreadFactory threadFactory; AbstractThreadPoolExecutorFactory threadPool; threadFactory = getGlobalConfiguration(holder).asyncThreadPool().threadFactory(); assertNull(threadFactory); threadPool = getGlobalConfiguration(holder).asyncThreadPool().threadPoolFactory(); assertNull(threadPool); threadFactory = getGlobalConfiguration(holder).stateTransferThreadPool().threadFactory(); assertNull(threadFactory); threadPool = getGlobalConfiguration(holder).stateTransferThreadPool().threadPoolFactory(); assertNull(threadPool); assertTemplateConfiguration(holder, "local-template"); assertTemplateConfiguration(holder, "invalidation-template"); assertTemplateConfiguration(holder, "repl-template"); assertTemplateConfiguration(holder, "dist-template"); assertCacheConfiguration(holder, "local-instance"); assertCacheConfiguration(holder, "invalidation-instance"); assertCacheConfiguration(holder, "repl-instance"); assertCacheConfiguration(holder, "dist-instance"); Configuration localTemplate = getConfiguration(holder, "local-template"); Configuration localConfiguration = getConfiguration(holder, "local-instance"); assertEquals(10000, localTemplate.expiration().wakeUpInterval()); assertEquals(11000, localConfiguration.expiration().wakeUpInterval()); assertEquals(10, localTemplate.expiration().lifespan()); assertEquals(10, localConfiguration.expiration().lifespan()); Configuration replTemplate = getConfiguration(holder, "repl-template"); Configuration replConfiguration = getConfiguration(holder, "repl-instance"); assertEquals(31000, replTemplate.locking().lockAcquisitionTimeout()); assertEquals(32000, replConfiguration.locking().lockAcquisitionTimeout()); assertEquals(3000, replTemplate.locking().concurrencyLevel()); assertEquals(3000, replConfiguration.locking().concurrencyLevel()); } }, INFINISPAN_70(7, 0) { public void check(ConfigurationBuilderHolder holder, int schemaMajor, int schemaMinor) { GlobalConfiguration g = getGlobalConfiguration(holder); assertEquals("maximal", g.cacheManagerName()); assertTrue(g.statistics()); assertTrue(g.jmx().enabled()); assertEquals("my-domain", g.jmx().domain()); assertTrue(g.jmx().mbeanServerLookup() instanceof CustomMBeanServerPropertiesTest.TestLookup); assertEquals(1, g.jmx().properties().size()); assertEquals("value", g.jmx().properties().getProperty("key")); // Transport assertEquals("maximal-cluster", g.transport().clusterName()); assertEquals(120000, g.transport().distributedSyncTimeout()); assertTrue("udp", holder.hasJGroupsStack("udp")); assertTrue("tcp", holder.hasJGroupsStack("tcp")); DefaultThreadFactory threadFactory; EnhancedQueueExecutorFactory threadPool; threadFactory = getGlobalConfiguration(holder).listenerThreadPool().threadFactory(); assertEquals("infinispan", threadFactory.threadGroup().getName()); assertEquals("%G %i", threadFactory.threadNamePattern()); assertEquals(5, threadFactory.initialPriority()); threadPool = getGlobalConfiguration(holder).listenerThreadPool().threadPoolFactory(); assertEquals(1, threadPool.coreThreads()); assertEquals(1, threadPool.maxThreads()); assertEquals(0, threadPool.queueLength()); assertEquals(0, threadPool.keepAlive()); assertTrue(getGlobalConfiguration(holder).expirationThreadPool().threadPoolFactory() instanceof ScheduledThreadPoolExecutorFactory); threadFactory = getGlobalConfiguration(holder).expirationThreadPool().threadFactory(); assertEquals("infinispan", threadFactory.threadGroup().getName()); assertEquals("%G %i", threadFactory.threadNamePattern()); assertEquals(5, threadFactory.initialPriority()); threadFactory = getGlobalConfiguration(holder).transport().remoteCommandThreadPool().threadFactory(); assertNull(threadFactory); threadPool = getGlobalConfiguration(holder).transport().remoteCommandThreadPool().threadPoolFactory(); assertNull(threadPool); threadFactory = getGlobalConfiguration(holder).transport().transportThreadPool().threadFactory(); assertNull(threadFactory); threadPool = getGlobalConfiguration(holder).transport().transportThreadPool().threadPoolFactory(); assertNull(threadPool); assertTrue(g.serialization().marshaller() instanceof TestObjectStreamMarshaller); Map<Integer, AdvancedExternalizer<?>> externalizers = g.serialization().advancedExternalizers(); AdvancedExternalizer<?> externalizer = externalizers.get(9001); assertTrue(externalizer instanceof AdvancedExternalizerTest.IdViaConfigObj.Externalizer); externalizer = externalizers.get(9002); assertTrue(externalizer instanceof AdvancedExternalizerTest.IdViaAnnotationObj.Externalizer); assertEquals(ShutdownHookBehavior.DONT_REGISTER, g.shutdown().hookBehavior()); // Default cache is "local" named cache Configuration c = holder.getDefaultConfigurationBuilder().build(); assertFalse(c.invocationBatching().enabled()); assertTrue(c.statistics().enabled()); assertEquals(CacheMode.LOCAL, c.clustering().cacheMode()); assertEquals(30000, c.locking().lockAcquisitionTimeout()); assertEquals(2000, c.locking().concurrencyLevel()); assertEquals(IsolationLevel.NONE, c.locking().isolationLevel()); assertTrue(c.locking().useLockStriping()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Full XA assertFalse(c.transaction().useSynchronization()); // Full XA assertTrue(c.transaction().recovery().enabled()); // Full XA assertEquals(LockingMode.OPTIMISTIC, c.transaction().lockingMode()); assertTrue(c.transaction().transactionManagerLookup() instanceof JBossStandaloneJTAManagerLookup); assertEquals(60000, c.transaction().cacheStopTimeout()); assertEquals(20000, c.memory().size()); assertEquals(10000, c.expiration().wakeUpInterval()); assertEquals(10, c.expiration().lifespan()); assertEquals(10, c.expiration().maxIdle()); assertFalse(c.persistence().passivation()); StoreConfiguration fileStore = getStoreConfiguration(c, getFileStoreClass(schemaMajor)); assertFalse(fileStore.purgeOnStartup()); assertTrue(fileStore.preload()); assertFalse(fileStore.shared()); assertEquals(2048, fileStore.async().modificationQueueSize()); assertFalse(c.indexing().enabled()); c = getConfiguration(holder, "invalid"); assertEquals(CacheMode.INVALIDATION_SYNC, c.clustering().cacheMode()); assertTrue(c.invocationBatching().enabled()); assertTrue(c.statistics().enabled()); assertEquals(30500, c.locking().lockAcquisitionTimeout()); assertEquals(2500, c.locking().concurrencyLevel()); assertEquals(IsolationLevel.READ_COMMITTED, c.locking().isolationLevel()); // Converted to READ_COMMITTED by builder assertTrue(c.locking().useLockStriping()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Non XA assertTrue(c.transaction().useSynchronization()); // Non XA assertFalse(c.transaction().recovery().enabled()); // Non XA assertEquals(LockingMode.OPTIMISTIC, c.transaction().lockingMode()); assertEquals(60500, c.transaction().cacheStopTimeout()); assertEquals(20500, c.memory().size()); assertEquals(10500, c.expiration().wakeUpInterval()); assertEquals(11, c.expiration().lifespan()); assertEquals(11, c.expiration().maxIdle()); assertFalse(c.indexing().enabled()); c = getConfiguration(holder, "repl"); assertEquals(CacheMode.REPL_SYNC, c.clustering().cacheMode()); assertTrue(c.invocationBatching().enabled()); assertTrue(c.statistics().enabled()); assertEquals(31000, c.locking().lockAcquisitionTimeout()); assertEquals(3000, c.locking().concurrencyLevel()); assertEquals(IsolationLevel.REPEATABLE_READ, c.locking().isolationLevel()); // Converted to REPEATABLE_READ by builder assertTrue(c.locking().useLockStriping()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Batching, non XA assertTrue(c.transaction().useSynchronization()); // Batching, non XA assertFalse(c.transaction().recovery().enabled()); // Batching, non XA assertEquals(LockingMode.PESSIMISTIC, c.transaction().lockingMode()); assertEquals(61000, c.transaction().cacheStopTimeout()); assertEquals(21000, c.memory().size()); assertEquals(11000, c.expiration().wakeUpInterval()); assertEquals(12, c.expiration().lifespan()); assertEquals(12, c.expiration().maxIdle()); assertFalse(c.clustering().stateTransfer().fetchInMemoryState()); assertEquals(60000, c.clustering().stateTransfer().timeout()); assertEquals(10000, c.clustering().stateTransfer().chunkSize()); ClusterLoaderConfiguration clusterLoader = getStoreConfiguration(c, ClusterLoaderConfiguration.class); assertEquals(35000, clusterLoader.remoteCallTimeout()); assertFalse(clusterLoader.preload()); assertFalse(c.indexing().enabled()); c = getConfiguration(holder, "dist"); assertEquals(CacheMode.DIST_SYNC, c.clustering().cacheMode()); assertFalse(c.invocationBatching().enabled()); assertEquals(1200000, c.clustering().l1().lifespan()); assertEquals(4, c.clustering().hash().numOwners()); assertEquals(35000, c.clustering().remoteTimeout()); assertEquals(2, c.clustering().hash().numSegments()); assertTrue(c.clustering().hash().consistentHashFactory() instanceof SyncConsistentHashFactory); assertTrue(c.statistics().enabled()); assertEquals(31500, c.locking().lockAcquisitionTimeout()); assertEquals(3500, c.locking().concurrencyLevel()); assertEquals(IsolationLevel.READ_COMMITTED, c.locking().isolationLevel()); assertTrue(c.locking().useLockStriping()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Full XA assertFalse(c.transaction().useSynchronization()); // Full XA assertTrue(c.transaction().recovery().enabled()); // Full XA assertEquals(LockingMode.OPTIMISTIC, c.transaction().lockingMode()); assertEquals(61500, c.transaction().cacheStopTimeout()); assertEquals(21500, c.memory().size()); assertEquals(11500, c.expiration().wakeUpInterval()); assertEquals(13, c.expiration().lifespan()); assertEquals(13, c.expiration().maxIdle()); assertTrue(c.clustering().stateTransfer().fetchInMemoryState()); assertEquals(60500, c.clustering().stateTransfer().timeout()); assertEquals(10500, c.clustering().stateTransfer().chunkSize()); // Back up cross-site configuration BackupConfiguration backup = c.sites().allBackups().get(0); assertEquals("NYC", backup.site()); assertEquals(BackupFailurePolicy.WARN, backup.backupFailurePolicy()); assertEquals(BackupConfiguration.BackupStrategy.SYNC, backup.strategy()); assertEquals(12500, backup.replicationTimeout()); backup = c.sites().allBackups().get(1); assertEquals("SFO", backup.site()); assertEquals(BackupFailurePolicy.IGNORE, backup.backupFailurePolicy()); assertEquals(BackupConfiguration.BackupStrategy.ASYNC, backup.strategy()); assertEquals(13000, backup.replicationTimeout()); backup = c.sites().allBackups().get(2); assertEquals("LON", backup.site()); assertEquals(BackupFailurePolicy.FAIL, backup.backupFailurePolicy()); assertEquals(BackupConfiguration.BackupStrategy.SYNC, backup.strategy()); assertEquals(13500, backup.replicationTimeout()); assertEquals(3, backup.takeOffline().afterFailures()); assertEquals(10000, backup.takeOffline().minTimeToWait()); assertEquals("users", c.sites().backupFor().remoteCache()); assertEquals("LON", c.sites().backupFor().remoteSite()); c = getConfiguration(holder, "capedwarf-data"); assertEquals(CacheMode.REPL_SYNC, c.clustering().cacheMode()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Non XA assertTrue(c.transaction().useSynchronization()); // Non XA assertFalse(c.transaction().recovery().enabled()); // Non XA // Storage type was not configurable before 9.0/8.5 StorageType objectOrDefaultStorageType = (schemaMajor < 9 && schemaMinor < 5) ? StorageType.HEAP : StorageType.OBJECT; assertEquals(objectOrDefaultStorageType, c.memory().storageType()); assertEquals(-1, c.memory().size()); fileStore = getStoreConfiguration(c, getFileStoreClass(schemaMajor)); assertTrue(fileStore.preload()); assertFalse(fileStore.purgeOnStartup()); c = getConfiguration(holder, "capedwarf-metadata"); assertEquals(CacheMode.REPL_SYNC, c.clustering().cacheMode()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Non XA assertTrue(c.transaction().useSynchronization()); // Non XA assertFalse(c.transaction().recovery().enabled()); // Non XA assertEquals(objectOrDefaultStorageType, c.memory().storageType()); assertEquals(-1, c.memory().size()); DummyInMemoryStoreConfiguration dummyStore = getStoreConfiguration(c, DummyInMemoryStoreConfiguration.class); assertFalse(dummyStore.preload()); assertFalse(dummyStore.purgeOnStartup()); c = getConfiguration(holder, "capedwarf-memcache"); assertEquals(CacheMode.REPL_SYNC, c.clustering().cacheMode()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Non XA assertTrue(c.transaction().useSynchronization()); // Non XA assertFalse(c.transaction().recovery().enabled()); // Non XA assertEquals(objectOrDefaultStorageType, c.memory().storageType()); assertEquals(-1, c.memory().size()); assertEquals(LockingMode.PESSIMISTIC, c.transaction().lockingMode()); c = getConfiguration(holder, "capedwarf-default"); assertEquals(CacheMode.DIST_SYNC, c.clustering().cacheMode()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Non XA assertTrue(c.transaction().useSynchronization()); // Non XA assertFalse(c.transaction().recovery().enabled()); // Non XA assertEquals(objectOrDefaultStorageType, c.memory().storageType()); assertEquals(-1, c.memory().size()); fileStore = getStoreConfiguration(c, getFileStoreClass(schemaMajor)); assertTrue(fileStore.preload()); assertFalse(fileStore.purgeOnStartup()); assertFalse(c.indexing().enabled()); c = getConfiguration(holder, "capedwarf-dist"); assertEquals(CacheMode.DIST_SYNC, c.clustering().cacheMode()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Non XA assertTrue(c.transaction().useSynchronization()); // Non XA assertFalse(c.transaction().recovery().enabled()); // Non XA assertEquals(objectOrDefaultStorageType, c.memory().storageType()); assertEquals(-1, c.memory().size()); assertEquals(LockingMode.PESSIMISTIC, c.transaction().lockingMode()); fileStore = getStoreConfiguration(c, getFileStoreClass(schemaMajor)); assertTrue(fileStore.preload()); assertFalse(fileStore.purgeOnStartup()); c = getConfiguration(holder, "capedwarf-tasks"); assertEquals(CacheMode.DIST_SYNC, c.clustering().cacheMode()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Non XA assertTrue(c.transaction().useSynchronization()); // Non XA assertFalse(c.transaction().recovery().enabled()); // Non XA assertEquals(10000, c.memory().size()); fileStore = getStoreConfiguration(c, getFileStoreClass(schemaMajor)); assertTrue(fileStore.preload()); assertFalse(fileStore.purgeOnStartup()); assertFalse(c.indexing().enabled()); c = getConfiguration(holder, "HibernateSearch-LuceneIndexesMetadata"); assertEquals(CacheMode.REPL_SYNC, c.clustering().cacheMode()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Non XA assertTrue(c.invocationBatching().enabled()); assertTrue(c.transaction().useSynchronization()); // Non XA assertFalse(c.transaction().recovery().enabled()); // Non XA assertEquals(-1, c.memory().size()); fileStore = getStoreConfiguration(c, getFileStoreClass(schemaMajor)); assertTrue(fileStore.preload()); assertFalse(fileStore.purgeOnStartup()); c = getConfiguration(holder, "HibernateSearch-LuceneIndexesData"); assertEquals(CacheMode.REPL_SYNC, c.clustering().cacheMode()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Non XA assertTrue(c.invocationBatching().enabled()); assertTrue(c.transaction().useSynchronization()); // Non XA assertFalse(c.transaction().recovery().enabled()); // Non XA assertEquals(-1, c.memory().size()); fileStore = getStoreConfiguration(c, getFileStoreClass(schemaMajor)); assertTrue(fileStore.preload()); assertFalse(fileStore.purgeOnStartup()); c = getConfiguration(holder, "HibernateSearch-LuceneIndexesLocking"); assertEquals(CacheMode.REPL_SYNC, c.clustering().cacheMode()); assertEquals(TransactionMode.TRANSACTIONAL, c.transaction().transactionMode()); // Non XA assertTrue(c.invocationBatching().enabled()); assertTrue(c.transaction().useSynchronization()); // Non XA assertFalse(c.transaction().recovery().enabled()); // Non XA assertEquals(-1, c.memory().size()); c = getConfiguration(holder, "custom-interceptors"); List<InterceptorConfiguration> interceptors = c.customInterceptors().interceptors(); InterceptorConfiguration interceptor = interceptors.get(0); assertTrue(interceptor.asyncInterceptor() instanceof CustomInterceptor1); assertEquals(InvocationContextInterceptor.class, interceptor.after()); interceptor = interceptors.get(1); assertEquals(InvocationContextInterceptor.class, interceptor.before()); assertTrue(interceptor.asyncInterceptor() instanceof CustomInterceptor2); interceptor = interceptors.get(2); assertTrue(interceptor.asyncInterceptor() instanceof CustomInterceptor3); assertEquals(1, interceptor.index()); interceptor = interceptors.get(3); assertTrue(interceptor.asyncInterceptor() instanceof CustomInterceptor4); assertEquals(InterceptorConfiguration.Position.LAST, interceptor.position()); assertTrue(c.unsafe().unreliableReturnValues()); c = getConfiguration(holder, "write-skew"); assertEquals(IsolationLevel.REPEATABLE_READ, c.locking().isolationLevel()); // Ignore custom-container (if present) if (holder.getNamedConfigurationBuilders().containsKey("store-as-binary")) { c = getConfiguration(holder, "store-as-binary"); assertSame(StorageType.BINARY, c.memory().storageType()); } } }, ; protected final int major; protected final int minor; ParserVersionCheck(int major, int minor) { this.major = major; this.minor = minor; } public abstract void check(ConfigurationBuilderHolder cm, int schemaMajor, int schemaMinor); public boolean isIncludedBy(int major, int minor) { return major > this.major || (major == this.major && minor >= this.minor); } Class<? extends StoreConfiguration> getFileStoreClass(int schemaMajor) { if (schemaMajor < 13) { return SingleFileStoreConfiguration.class; } return SoftIndexFileStoreConfiguration.class; } } private static void assertTemplateConfiguration(ConfigurationBuilderHolder holder, String name) { Configuration configuration = getConfiguration(holder, name); assertNotNull("Configuration " + name + " expected", configuration); assertTrue("Configuration " + name + " should be a template", configuration.isTemplate()); } private static void assertCacheConfiguration(ConfigurationBuilderHolder holder, String name) { Configuration configuration = getConfiguration(holder, name); assertNotNull("Configuration " + name + " expected", configuration); assertFalse("Configuration " + name + " should not be a template", configuration.isTemplate()); } private static <T> T getStoreConfiguration(Configuration c, Class<T> configurationClass) { for (StoreConfiguration pc : c.persistence().stores()) { if (configurationClass.isInstance(pc)) { return (T) pc; } } throw new NoSuchElementException("There is no store of type " + configurationClass); } public static final class CustomInterceptor1 extends BaseCustomAsyncInterceptor { } public static final class CustomInterceptor2 extends BaseCustomAsyncInterceptor { } public static final class CustomInterceptor3 extends BaseCustomAsyncInterceptor { } public static final class CustomInterceptor4 extends BaseCustomAsyncInterceptor { String foo; // configured via XML } private static Configuration getConfiguration(ConfigurationBuilderHolder holder, String name) { ConfigurationBuilder builder = holder.getNamedConfigurationBuilders().get(name); return Objects.requireNonNull(builder).build(); } private static GlobalConfiguration getGlobalConfiguration(ConfigurationBuilderHolder holder) { return holder.getGlobalConfigurationBuilder().build(); } }
46,245
55.055758
144
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/parsing/LegacyXmlFileParsingTest.java
package org.infinispan.configuration.parsing; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.AssertJUnit.fail; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "unit", testName = "configuration.parsing.LegacyXmlFileParsingTest") public class LegacyXmlFileParsingTest extends AbstractInfinispanTest { @Test(expectedExceptions = CacheConfigurationException.class) public void testUnsupportedConfiguration() throws Exception { withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.fromXml("configs/legacy/6.0.xml", true)) { @Override public void call() { fail("Parsing an unsupported file should have failed."); } }); } }
968
34.888889
83
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/parsing/JsonParsingTest.java
package org.infinispan.configuration.parsing; import static org.testng.AssertJUnit.assertEquals; import java.io.IOException; import java.util.List; import java.util.Set; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.Test; @Test(groups = "unit", testName = "configuration.JsonParsingTest") public class JsonParsingTest extends AbstractInfinispanTest { public void testSerializationAllowList() throws IOException { ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader(), true, System.getProperties()); ConfigurationBuilderHolder holder = parserRegistry.parseFile("configs/serialization-test.json"); GlobalConfiguration globalConfiguration = holder.getGlobalConfigurationBuilder().build(); Set<String> classes = globalConfiguration.serialization().allowList().getClasses(); assertEquals(3, classes.size()); List<String> regexps = globalConfiguration.serialization().allowList().getRegexps(); assertEquals(2, regexps.size()); } public void testErrorReporting() { ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader(), true, System.getProperties()); Exceptions.expectException("^ISPN000327:.*broken.json\\[23,15\\].*", () -> parserRegistry.parseFile("configs/broken.json"), CacheConfigurationException.class); } }
1,572
48.15625
165
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/parsing/YamlParsingTest.java
package org.infinispan.configuration.parsing; import static org.testng.AssertJUnit.assertEquals; import java.io.IOException; import java.util.List; import java.util.Set; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.Test; @Test(groups = "unit", testName = "configuration.YamlParsingTest") public class YamlParsingTest extends AbstractInfinispanTest { public void testSerializationAllowList() throws IOException { ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader(), true, System.getProperties()); ConfigurationBuilderHolder holder = parserRegistry.parseFile("configs/serialization-test.yaml"); GlobalConfiguration globalConfiguration = holder.getGlobalConfigurationBuilder().build(); Set<String> classes = globalConfiguration.serialization().allowList().getClasses(); assertEquals(3, classes.size()); List<String> regexps = globalConfiguration.serialization().allowList().getRegexps(); assertEquals(2, regexps.size()); } public void testErrorReporting() { ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader(), true, System.getProperties()); Exceptions.expectException("^ISPN000327:.*broken.yaml\\[18,18\\].*", () -> parserRegistry.parseFile("configs/broken.yaml"), CacheConfigurationException.class); } }
1,572
48.15625
165
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/parsing/XmlFileParsingTest.java
package org.infinispan.configuration.parsing; import static org.infinispan.commons.test.Exceptions.expectException; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Map; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.configuration.io.ConfigurationResourceResolvers; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.util.Version; import org.infinispan.configuration.cache.AbstractStoreConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ClusterLoaderConfiguration; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.EncodingConfiguration; import org.infinispan.configuration.cache.InterceptorConfiguration; import org.infinispan.configuration.cache.PersistenceConfiguration; import org.infinispan.configuration.cache.StorageType; import org.infinispan.configuration.cache.StoreConfiguration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.ShutdownHookBehavior; import org.infinispan.distribution.ch.impl.DefaultConsistentHashFactory; import org.infinispan.eviction.EvictionStrategy; import org.infinispan.eviction.EvictionType; import org.infinispan.factories.threads.AbstractThreadPoolExecutorFactory; import org.infinispan.factories.threads.DefaultThreadFactory; import org.infinispan.factories.threads.EnhancedQueueExecutorFactory; import org.infinispan.interceptors.FooInterceptor; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.marshall.AdvancedExternalizerTest; import org.infinispan.marshall.TestObjectStreamMarshaller; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfiguration; import org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfiguration; import org.infinispan.persistence.spi.CacheLoader; import org.infinispan.persistence.spi.InitializationContext; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.remoting.transport.Transport; import org.infinispan.remoting.transport.jgroups.JGroupsTransport; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.tx.TestLookup; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.lookup.GenericTransactionManagerLookup; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; @Test(groups = "unit", testName = "configuration.XmlFileParsingTest") public class XmlFileParsingTest extends AbstractInfinispanTest { @Test(expectedExceptions = FileNotFoundException.class) public void testFailOnMissingConfigurationFile() throws IOException { new DefaultCacheManager("does-not-exist.xml"); } public void testNamedCacheFile() throws IOException { ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader(), true, System.getProperties()); ConfigurationBuilderHolder holder = parserRegistry.parseFile("configs/named-cache-test.xml"); assertNamedCacheFile(holder, false); } public void testNoNamedCaches() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container default-cache=\"default\">" + " <transport cluster=\"demoCluster\"/>\n" + " <replicated-cache name=\"default\">\n" + " </replicated-cache>\n" + "</cache-container>" ); ConfigurationBuilderHolder holder = parseStringConfiguration(config); GlobalConfiguration globalCfg = holder.getGlobalConfigurationBuilder().build(); assertTrue(globalCfg.transport().transport() instanceof JGroupsTransport); assertEquals("demoCluster", globalCfg.transport().clusterName()); Configuration cfg = holder.getDefaultConfigurationBuilder().build(); assertEquals(CacheMode.REPL_SYNC, cfg.clustering().cacheMode()); } private static ConfigurationBuilderHolder parseStringConfiguration(String config) { InputStream is = new ByteArrayInputStream(config.getBytes()); ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader(), true, System.getProperties()); return parserRegistry.parse(is, ConfigurationResourceResolvers.DEFAULT, MediaType.APPLICATION_XML); } @Test(expectedExceptions = CacheConfigurationException.class) public void testDuplicateCacheNames() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container default-cache=\"duplicatename\">" + " <transport cluster=\"demoCluster\"/>\n" + " <distributed-cache name=\"duplicatename\">\n" + " </distributed-cache>\n" + " <distributed-cache name=\"duplicatename\">\n" + " </distributed-cache>\n" + "</cache-container>" ); InputStream is = new ByteArrayInputStream(config.getBytes()); TestCacheManagerFactory.fromStream(is); } public void testNoSchemaWithStuff() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container default-cache=\"default\">" + " <local-cache name=\"default\">\n" + " <locking concurrency-level=\"10000\" isolation=\"REPEATABLE_READ\" />\n" + " </local-cache>\n" + "</cache-container>" ); ConfigurationBuilderHolder holder = parseStringConfiguration(config); Configuration cfg = holder.getDefaultConfigurationBuilder().build(); assertEquals(10000, cfg.locking().concurrencyLevel()); assertEquals(IsolationLevel.REPEATABLE_READ, cfg.locking().isolationLevel()); } public void testOffHeap() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container default-cache=\"default\">" + " <local-cache name=\"default\">\n" + " <memory storage=\"OFF_HEAP\" when-full=\"MANUAL\" />\n" + " </local-cache>\n" + "</cache-container>" ); ConfigurationBuilderHolder holder = parseStringConfiguration(config); Configuration cfg = holder.getDefaultConfigurationBuilder().build(); assertEquals(StorageType.OFF_HEAP, cfg.memory().storageType()); assertEquals(EvictionStrategy.MANUAL, cfg.memory().evictionStrategy()); config = TestingUtil.wrapXMLWithSchema( "<cache-container default-cache=\"default\">" + " <local-cache name=\"default\">\n" + " <memory/>\n" + " </local-cache>\n" + "</cache-container>" ); holder = parseStringConfiguration(config); cfg = holder.getDefaultConfigurationBuilder().build(); assertEquals(StorageType.HEAP, cfg.memory().storageType()); config = TestingUtil.wrapXMLWithoutSchema( "<cache-container default-cache=\"default\">" + " <local-cache name=\"default\">\n" + " <memory storage=\"BINARY\"/>\n" + " </local-cache>\n" + "</cache-container>" ); holder = parseStringConfiguration(config); cfg = holder.getDefaultConfigurationBuilder().build(); assertEquals(StorageType.BINARY, cfg.memory().storageType()); } public void testDummyInMemoryStore() { String config = TestingUtil.wrapXMLWithoutSchema( "<cache-container default-cache=\"default\">" + " <local-cache name=\"default\">\n" + " <persistence >\n" + " <dummy-store xmlns=\"urn:infinispan:config:store:dummy:" + Version.getSchemaVersion() + "\" store-name=\"myStore\" />\n" + " </persistence >\n" + " </local-cache>\n" + "</cache-container>" ); ConfigurationBuilderHolder holder = parseStringConfiguration(config); PersistenceConfiguration cfg = holder.getDefaultConfigurationBuilder().build().persistence(); StoreConfiguration storeConfiguration = cfg.stores().get(0); assertTrue(storeConfiguration instanceof DummyInMemoryStoreConfiguration); DummyInMemoryStoreConfiguration dummyInMemoryStoreConfiguration = (DummyInMemoryStoreConfiguration) storeConfiguration; assertEquals("myStore", dummyInMemoryStoreConfiguration.storeName()); } /** * Used by testStoreWithNoConfigureBy, although the cache is not really created. */ @SuppressWarnings("unused") public static class GenericLoader implements CacheLoader { @Override public void init(InitializationContext ctx) { } @Override public MarshallableEntry loadEntry(Object key) { return null; } @Override public boolean contains(Object key) { return false; } @Override public void start() { } @Override public void stop() { } } public void testStoreWithNoConfigureBy() { String config = TestingUtil.wrapXMLWithoutSchema( "<cache-container default-cache=\"default\">" + " <local-cache name=\"default\">\n" + " <persistence >\n" + " <store class=\"" + GenericLoader.class.getName() + "\" preload=\"true\" fetch-state=\"true\" />\n" + " </persistence >\n" + " </local-cache>\n" + "</cache-container>" ); ConfigurationBuilderHolder holder = parseStringConfiguration(config); PersistenceConfiguration cfg = holder.getDefaultConfigurationBuilder().build().persistence(); StoreConfiguration storeConfiguration = cfg.stores().get(0); assertTrue(storeConfiguration instanceof AbstractStoreConfiguration); AbstractStoreConfiguration abstractStoreConfiguration = (AbstractStoreConfiguration) storeConfiguration; assertTrue(abstractStoreConfiguration.preload()); } public void testCustomTransport() { String config = TestingUtil.wrapXMLWithSchema( "<jgroups transport=\"" + CustomTransport.class.getName() + "\"/>\n" + "<cache-container default-cache=\"default\">\n" + " <transport cluster=\"ispn-perf-test\"/>\n" + " <distributed-cache name=\"default\"/>\n" + "</cache-container>" ); ConfigurationBuilderHolder holder = parseStringConfiguration(config); Transport transport = holder.getGlobalConfigurationBuilder().build().transport().transport(); assertNotNull(transport); assertTrue(transport instanceof CustomTransport); } public void testNoDefaultCache() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container>" + " <transport cluster=\"demoCluster\"/>\n" + " <replicated-cache name=\"default\">\n" + " </replicated-cache>\n" + "</cache-container>" ); ConfigurationBuilderHolder holder = parseStringConfiguration(config); GlobalConfiguration globalCfg = holder.getGlobalConfigurationBuilder().build(); assertFalse(globalCfg.defaultCacheName().isPresent()); assertNull(holder.getDefaultConfigurationBuilder()); assertEquals(CacheMode.REPL_SYNC, getCacheConfiguration(holder, "default").clustering().cacheMode()); } private Configuration getCacheConfiguration(ConfigurationBuilderHolder holder, String cacheName) { return holder.getNamedConfigurationBuilders().get(cacheName).build(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN000432:.*") public void testNoDefaultCacheDeclaration() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container default-cache=\"non-existent\">" + " <transport cluster=\"demoCluster\"/>\n" + " <replicated-cache name=\"default\">\n" + " </replicated-cache>\n" + "</cache-container>" ); parseStringConfiguration(config); } public void testNoCacheName() { String config = "<local-cache>\n" + " <expiration interval=\"10500\" lifespan=\"11\" max-idle=\"11\"/>\n" + "</local-cache>"; ConfigurationBuilderHolder holder = parseStringConfiguration(config); Configuration configuration = holder.getCurrentConfigurationBuilder().build(); assertEquals(CacheMode.LOCAL, configuration.clustering().cacheMode()); assertEquals(10500, configuration.expiration().wakeUpInterval()); assertEquals(11, configuration.expiration().lifespan()); assertEquals(11, configuration.expiration().maxIdle()); } public void testWildcards() throws IOException { String config = TestingUtil.wrapXMLWithSchema( "<cache-container>" + " <local-cache-configuration name=\"wildcache*\">\n" + " <expiration interval=\"10500\" lifespan=\"11\" max-idle=\"11\"/>\n" + " </local-cache-configuration>\n" + "</cache-container>" ); ConfigurationBuilderHolder holder = parseStringConfiguration(config); try (DefaultCacheManager cm = new DefaultCacheManager(holder, false)) { Configuration wildcache1 = cm.getCacheConfiguration("wildcache1"); assertEquals(10500, wildcache1.expiration().wakeUpInterval()); assertEquals(11, wildcache1.expiration().lifespan()); assertEquals(11, wildcache1.expiration().maxIdle()); } } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN000485:.*") public void testAmbiguousWildcards() throws IOException { String config = TestingUtil.wrapXMLWithSchema( "<cache-container>" + " <local-cache-configuration name=\"wildcache*\">\n" + " </local-cache-configuration>\n" + " <local-cache-configuration name=\"wild*\">\n" + " </local-cache-configuration>\n" + "</cache-container>" ); ConfigurationBuilderHolder holder = parseStringConfiguration(config); try (DefaultCacheManager cm = new DefaultCacheManager(holder, false)) { cm.getCacheConfiguration("wildcache1"); } } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN000484:.*") public void testNoWildcardsInCacheName() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container>" + " <transport cluster=\"demoCluster\"/>\n" + " <replicated-cache name=\"wildcard*\">\n" + " </replicated-cache>\n" + "</cache-container>" ); parseStringConfiguration(config); fail("Should have failed earlier"); } public void testAsyncInheritance() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container>" + " <transport cluster=\"demoCluster\"/>\n" + " <replicated-cache-configuration mode=\"ASYNC\" name=\"repl-1\">\n" + " </replicated-cache-configuration>\n" + " <replicated-cache-configuration name=\"repl-2\" configuration=\"repl-1\">\n" + " </replicated-cache-configuration>\n" + "</cache-container>" ); InputStream is = new ByteArrayInputStream(config.getBytes()); ConfigurationBuilderHolder holder = TestCacheManagerFactory.parseStream(is, false); Configuration repl1 = getCacheConfiguration(holder, "repl-1"); Configuration repl2 = getCacheConfiguration(holder, "repl-2"); assertTrue(repl1.isTemplate()); assertTrue(repl2.isTemplate()); assertEquals(CacheMode.REPL_ASYNC, repl1.clustering().cacheMode()); assertEquals(CacheMode.REPL_ASYNC, repl2.clustering().cacheMode()); } public void testInlineJGroupsStack() throws IOException { try (DefaultCacheManager cm = new DefaultCacheManager("configs/config-with-jgroups-stack.xml")) { assertTrue(cm.isCoordinator()); } } public void testRaftMembersParsing() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container>" + " <transport cluster=\"node-name-missing\" raft-members=\"a b c\" node-name=\"a\"/>\n" + "</cache-container>" ); InputStream is = new ByteArrayInputStream(config.getBytes()); ConfigurationBuilderHolder holder = TestCacheManagerFactory.parseStream(is, false); GlobalConfiguration configuration = holder.getGlobalConfigurationBuilder().build(); Collection<String> raftMembers = configuration.transport().raftMembers(); assertEquals(3, raftMembers.size()); assertTrue(raftMembers.contains("a")); assertTrue(raftMembers.contains("b")); assertTrue(raftMembers.contains("c")); assertEquals("a", configuration.transport().nodeName()); } public void testNodeNameMissingWithRaft() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container>\n" + " <transport cluster=\"node-name-missing\" raft-members=\"a b c\"/>\n" + "</cache-container>" ); InputStream is = new ByteArrayInputStream(config.getBytes()); expectException(CacheConfigurationException.class, "ISPN000667:.*", () -> TestCacheManagerFactory.parseStream(is, false)); } public void testNodeNameNotInRaftMembers() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container>" + " <transport cluster=\"node-name-missing\" raft-members=\"a b c\" node-name=\"d\"/>\n" + "</cache-container>" ); InputStream is = new ByteArrayInputStream(config.getBytes()); expectException(CacheConfigurationException.class, "ISPN000668:.*", () -> TestCacheManagerFactory.parseStream(is, false)); } private void assertNamedCacheFile(ConfigurationBuilderHolder holder, boolean deprecated) { GlobalConfiguration gc = holder.getGlobalConfigurationBuilder().build(); EnhancedQueueExecutorFactory listenerThreadPool = gc.listenerThreadPool().threadPoolFactory(); assertEquals(5, listenerThreadPool.maxThreads()); assertEquals(10000, listenerThreadPool.queueLength()); DefaultThreadFactory listenerThreadFactory = gc.listenerThreadPool().threadFactory(); assertEquals("AsyncListenerThread", listenerThreadFactory.threadNamePattern()); AbstractThreadPoolExecutorFactory persistenceThreadPool = gc.persistenceThreadPool().threadPoolFactory(); assertNull(persistenceThreadPool); AbstractThreadPoolExecutorFactory blockingThreadPool = gc.blockingThreadPool().threadPoolFactory(); assertEquals(6, blockingThreadPool.maxThreads()); assertEquals(10001, blockingThreadPool.queueLength()); DefaultThreadFactory persistenceThreadFactory = gc.blockingThreadPool().threadFactory(); assertEquals("BlockingThread", persistenceThreadFactory.threadNamePattern()); AbstractThreadPoolExecutorFactory asyncThreadPool = gc.asyncThreadPool().threadPoolFactory(); assertNull(asyncThreadPool); AbstractThreadPoolExecutorFactory nonBlockingThreadPool = gc.nonBlockingThreadPool().threadPoolFactory(); assertEquals(5, nonBlockingThreadPool.coreThreads()); assertEquals(5, nonBlockingThreadPool.maxThreads()); assertEquals(10000, nonBlockingThreadPool.queueLength()); assertEquals(0, nonBlockingThreadPool.keepAlive()); DefaultThreadFactory asyncThreadFactory = gc.nonBlockingThreadPool().threadFactory(); assertEquals("NonBlockingThread", asyncThreadFactory.threadNamePattern()); AbstractThreadPoolExecutorFactory transportThreadPool = gc.transport().transportThreadPool().threadPoolFactory(); assertNull(transportThreadPool); AbstractThreadPoolExecutorFactory remoteCommandThreadPool = gc.transport().remoteCommandThreadPool().threadPoolFactory(); assertNull(remoteCommandThreadPool); AbstractThreadPoolExecutorFactory stateTransferThreadPool = gc.stateTransferThreadPool().threadPoolFactory(); assertNull(stateTransferThreadPool); DefaultThreadFactory evictionThreadFactory = gc.expirationThreadPool().threadFactory(); assertEquals("ExpirationThread", evictionThreadFactory.threadNamePattern()); assertTrue(gc.transport().transport() instanceof JGroupsTransport); assertEquals("infinispan-cluster", gc.transport().clusterName()); assertEquals("Jalapeno", gc.transport().nodeName()); assertEquals(50000, gc.transport().distributedSyncTimeout()); assertEquals(ShutdownHookBehavior.REGISTER, gc.shutdown().hookBehavior()); assertTrue(gc.serialization().marshaller() instanceof TestObjectStreamMarshaller); final Map<Integer, AdvancedExternalizer<?>> externalizers = gc.serialization().advancedExternalizers(); assertEquals(3, externalizers.size()); assertTrue(externalizers.get(1234) instanceof AdvancedExternalizerTest.IdViaConfigObj.Externalizer); assertTrue(externalizers.get(5678) instanceof AdvancedExternalizerTest.IdViaAnnotationObj.Externalizer); assertTrue(externalizers.get(3456) instanceof AdvancedExternalizerTest.IdViaBothObj.Externalizer); Configuration defaultCfg = holder.getDefaultConfigurationBuilder().build(); assertEquals(1000, defaultCfg.locking().lockAcquisitionTimeout()); assertEquals(100, defaultCfg.locking().concurrencyLevel()); assertEquals(IsolationLevel.REPEATABLE_READ, defaultCfg.locking().isolationLevel()); if (!deprecated) { assertReaperAndTimeoutInfo(defaultCfg); } Configuration c = getCacheConfiguration(holder, "transactional"); assertFalse(c.clustering().cacheMode().isClustered()); assertTrue(c.transaction().transactionManagerLookup() instanceof GenericTransactionManagerLookup); if (!deprecated) { assertReaperAndTimeoutInfo(defaultCfg); } c = getCacheConfiguration(holder, "transactional2"); assertTrue(c.transaction().transactionManagerLookup() instanceof TestLookup); assertEquals(10000, c.transaction().cacheStopTimeout()); assertEquals(LockingMode.PESSIMISTIC, c.transaction().lockingMode()); assertFalse(c.transaction().autoCommit()); c = getCacheConfiguration(holder, "syncInval"); assertEquals(CacheMode.INVALIDATION_SYNC, c.clustering().cacheMode()); assertTrue(c.clustering().stateTransfer().awaitInitialTransfer()); assertEquals(15000, c.clustering().remoteTimeout()); c = getCacheConfiguration(holder, "asyncInval"); assertEquals(CacheMode.INVALIDATION_ASYNC, c.clustering().cacheMode()); assertEquals(15000, c.clustering().remoteTimeout()); c = getCacheConfiguration(holder, "syncRepl"); assertEquals(CacheMode.REPL_SYNC, c.clustering().cacheMode()); assertFalse(c.clustering().stateTransfer().fetchInMemoryState()); assertTrue(c.clustering().stateTransfer().awaitInitialTransfer()); assertEquals(15000, c.clustering().remoteTimeout()); c = getCacheConfiguration(holder, "asyncRepl"); assertEquals(CacheMode.REPL_ASYNC, c.clustering().cacheMode()); assertFalse(c.clustering().stateTransfer().fetchInMemoryState()); assertTrue(c.clustering().stateTransfer().awaitInitialTransfer()); c = getCacheConfiguration(holder, "txSyncRepl"); assertTrue(c.transaction().transactionManagerLookup() instanceof GenericTransactionManagerLookup); assertEquals(CacheMode.REPL_SYNC, c.clustering().cacheMode()); assertFalse(c.clustering().stateTransfer().fetchInMemoryState()); assertTrue(c.clustering().stateTransfer().awaitInitialTransfer()); assertEquals(15000, c.clustering().remoteTimeout()); c = getCacheConfiguration(holder, "overriding"); assertEquals(CacheMode.LOCAL, c.clustering().cacheMode()); assertEquals(20000, c.locking().lockAcquisitionTimeout()); assertEquals(1000, c.locking().concurrencyLevel()); assertEquals(IsolationLevel.REPEATABLE_READ, c.locking().isolationLevel()); assertEquals(StorageType.HEAP, c.memory().storageType()); c = getCacheConfiguration(holder, "storeAsBinary"); assertEquals(StorageType.BINARY, c.memory().storageType()); c = getCacheConfiguration(holder, "withFileStore"); assertTrue(c.persistence().preload()); assertFalse(c.persistence().passivation()); assertEquals(1, c.persistence().stores().size()); SoftIndexFileStoreConfiguration loaderCfg = (SoftIndexFileStoreConfiguration) c.persistence().stores().get(0); assertFalse(loaderCfg.ignoreModifications()); assertFalse(loaderCfg.purgeOnStartup()); assertEquals("/tmp/FileCacheStore-Location", loaderCfg.dataLocation()); assertTrue(loaderCfg.async().enabled()); assertEquals(700, loaderCfg.async().modificationQueueSize()); c = getCacheConfiguration(holder, "withClusterLoader"); assertEquals(1, c.persistence().stores().size()); ClusterLoaderConfiguration clusterLoaderCfg = (ClusterLoaderConfiguration) c.persistence().stores().get(0); assertEquals(15000, clusterLoaderCfg.remoteCallTimeout()); c = getCacheConfiguration(holder, "withLoaderDefaults"); loaderCfg = (SoftIndexFileStoreConfiguration) c.persistence().stores().get(0); assertEquals("/tmp/Another-FileCacheStore-Location", loaderCfg.dataLocation()); c = getCacheConfiguration(holder, "withouthJmxEnabled"); assertFalse(c.statistics().enabled()); assertTrue(gc.statistics()); assertTrue(gc.jmx().enabled()); assertEquals("funky_domain", gc.jmx().domain()); assertTrue(gc.jmx().mbeanServerLookup() instanceof TestMBeanServerLookup); c = getCacheConfiguration(holder, "dist"); assertEquals(CacheMode.DIST_SYNC, c.clustering().cacheMode()); assertEquals(600000, c.clustering().l1().lifespan()); assertEquals(120000, c.clustering().stateTransfer().timeout()); assertEquals(1200, c.clustering().l1().cleanupTaskFrequency()); assertTrue(c.clustering().hash().consistentHashFactory() instanceof DefaultConsistentHashFactory); assertEquals(3, c.clustering().hash().numOwners()); assertTrue(c.clustering().l1().enabled()); c = getCacheConfiguration(holder, "dist_with_capacity_factors"); assertEquals(CacheMode.DIST_SYNC, c.clustering().cacheMode()); assertEquals(600000, c.clustering().l1().lifespan()); assertEquals(120000, c.clustering().stateTransfer().timeout()); assertNull(c.clustering().hash().consistentHashFactory()); assertEquals(3, c.clustering().hash().numOwners()); assertTrue(c.clustering().l1().enabled()); assertEquals(0.0f, c.clustering().hash().capacityFactor()); if (!deprecated) assertEquals(1000, c.clustering().hash().numSegments()); c = getCacheConfiguration(holder, "groups"); assertTrue(c.clustering().hash().groups().enabled()); assertEquals(1, c.clustering().hash().groups().groupers().size()); assertEquals(String.class, c.clustering().hash().groups().groupers().get(0).getKeyType()); c = getCacheConfiguration(holder, "chunkSize"); assertTrue(c.clustering().stateTransfer().fetchInMemoryState()); assertEquals(120000, c.clustering().stateTransfer().timeout()); assertEquals(1000, c.clustering().stateTransfer().chunkSize()); c = getCacheConfiguration(holder, "cacheWithCustomInterceptors"); assertFalse(c.customInterceptors().interceptors().isEmpty()); assertEquals(6, c.customInterceptors().interceptors().size()); for (InterceptorConfiguration i : c.customInterceptors().interceptors()) { if (i.asyncInterceptor() instanceof FooInterceptor) { assertEquals(i.properties().getProperty("foo"), "bar"); } } c = getCacheConfiguration(holder, "evictionCache"); assertEquals(5000, c.memory().size()); assertEquals(EvictionStrategy.REMOVE, c.memory().evictionStrategy()); assertEquals(EvictionType.COUNT, c.memory().evictionType()); assertEquals(StorageType.OBJECT, c.memory().storageType()); assertEquals(60000, c.expiration().lifespan()); assertEquals(1000, c.expiration().maxIdle()); assertEquals(500, c.expiration().wakeUpInterval()); c = getCacheConfiguration(holder, "evictionMemoryExceptionCache"); assertEquals(5000, c.memory().size()); assertEquals(EvictionStrategy.EXCEPTION, c.memory().evictionStrategy()); assertEquals(EvictionType.MEMORY, c.memory().evictionType()); assertEquals(StorageType.BINARY, c.memory().storageType()); c = getCacheConfiguration(holder, "storeKeyValueBinary"); assertEquals(StorageType.BINARY, c.memory().storageType()); } private void assertReaperAndTimeoutInfo(Configuration defaultCfg) { assertEquals(123, defaultCfg.transaction().reaperWakeUpInterval()); assertEquals(3123, defaultCfg.transaction().completedTxTimeout()); } public void testErrorReporting() { ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader(), true, System.getProperties()); Exceptions.expectException("^ISPN000327:.*broken.xml\\[13,18\\].*", () -> parserRegistry.parseFile("configs/broken.xml"), CacheConfigurationException.class); } public void testEncodingMatching() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container>\n" + "<distributed-cache name=\"encoded-a\"><encoding media-type=\"application/x-protostream\"/></distributed-cache>\n" + "<distributed-cache name=\"encoded-b\"><encoding><key media-type=\"application/x-protostream\"/><value media-type=\"application/x-protostream\"/></encoding></distributed-cache>\n" + "</cache-container>" ); ConfigurationBuilderHolder holder = parseStringConfiguration(config); EncodingConfiguration a = holder.getNamedConfigurationBuilders().get("encoded-a").build().encoding(); EncodingConfiguration b = holder.getNamedConfigurationBuilders().get("encoded-b").build().encoding(); assertTrue(a.matches(b)); } public void testOrdering() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container>" + " <transport cluster=\"demoCluster\"/>\n" + " <replicated-cache-configuration name=\"repl-2\" configuration=\"repl-1\">\n" + " </replicated-cache-configuration>\n" + " <replicated-cache-configuration mode=\"ASYNC\" name=\"repl-1\">\n" + " </replicated-cache-configuration>\n" + "</cache-container>" ); InputStream is = new ByteArrayInputStream(config.getBytes()); ConfigurationBuilderHolder holder = TestCacheManagerFactory.parseStream(is, false); Configuration repl1 = getCacheConfiguration(holder, "repl-1"); Configuration repl2 = getCacheConfiguration(holder, "repl-2"); assertTrue(repl1.isTemplate()); assertTrue(repl2.isTemplate()); assertEquals(CacheMode.REPL_ASYNC, repl1.clustering().cacheMode()); assertEquals(CacheMode.REPL_ASYNC, repl2.clustering().cacheMode()); } public static class CustomTransport extends JGroupsTransport { } }
32,603
46.666667
199
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/parsing/SFSToSIFSMigratorTest.java
package org.infinispan.configuration.parsing; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.infinispan.test.fwk.TestCacheManagerFactory.createCacheManager; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.Cache; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.AbstractCacheTest; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.AfterClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Test the migrator store to ensure it properly copies over the contents of the SFS to a SIFS for migration purposes. * @author William Burns * @since 13.0 */ @Test(groups = "functional", testName = "configuration.parsing.SFSToSIFSMigratorTest") public class SFSToSIFSMigratorTest extends AbstractInfinispanTest { private static final String CACHE_NAME = "testCache"; @AfterClass protected void clearTempDirectory() { Util.recursiveFileRemove(tmpDirectory(this.getClass().getSimpleName())); } private enum StoreType { SINGLE_NON_SEGMENTED { @Override void apply(ConfigurationBuilder configurationBuilder) { configurationBuilder.persistence().addSingleFileStore().segmented(false); } }, SINGLE_SEGMENTED { @Override void apply(ConfigurationBuilder configurationBuilder) { configurationBuilder.persistence().addSingleFileStore().segmented(true); } }, MIGRATING { @Override void apply(ConfigurationBuilder configurationBuilder) { configurationBuilder.persistence().addStore(SFSToSIFSConfigurationBuilder.class); } }, SOFT_INDEX { @Override void apply(ConfigurationBuilder configurationBuilder) { configurationBuilder.persistence().addSoftIndexFileStore(); } }; abstract void apply(ConfigurationBuilder configurationBuilder); } @DataProvider(name = "singleFileStoreTypes") Object[][] singleTypes() { return new Object[][] { { StoreType.SINGLE_NON_SEGMENTED }, { StoreType. SINGLE_SEGMENTED }, }; } /** * Test that makes sure data can be migrated from two different stores (in this case SingleFileStore and SoftIndex). * Note that SIFS only supports being segmented so we don't need a configuration to change that. */ @Test(dataProvider = "singleFileStoreTypes") public void testStoreMigration(StoreType storeType) { GlobalConfigurationBuilder globalConfigurationBuilder = globalConfiguration(); EmbeddedCacheManager embeddedCacheManager = createManager(storeType, globalConfigurationBuilder); try { Cache<String, String> sfsCache = embeddedCacheManager.getCache(CACHE_NAME); sfsCache.put("key", "value"); TestingUtil.killCacheManagers(embeddedCacheManager); // Now create a manager which will migrate from SFS to SIFS embeddedCacheManager = createManager(StoreType.MIGRATING, globalConfigurationBuilder); Cache<String, String> sifsCache = embeddedCacheManager.getCache(CACHE_NAME); assertEquals("value", sifsCache.get("key")); TestingUtil.killCacheManagers(embeddedCacheManager); // Have a manger with only soft index and make sure it works properly embeddedCacheManager = createManager(StoreType.SOFT_INDEX, globalConfigurationBuilder); sifsCache = embeddedCacheManager.getCache(CACHE_NAME); assertEquals("value", sifsCache.get("key")); } finally { TestingUtil.killCacheManagers(embeddedCacheManager); } } private GlobalConfigurationBuilder globalConfiguration() { String stateDirectory = tmpDirectory(this.getClass().getSimpleName()); GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); global.globalState().enable().persistentLocation(stateDirectory); return global; } private EmbeddedCacheManager createManager(StoreType storeType, GlobalConfigurationBuilder global) { ConfigurationBuilder config = AbstractCacheTest.getDefaultClusteredCacheConfig(CacheMode.LOCAL); storeType.apply(config); EmbeddedCacheManager manager = createCacheManager(global, new ConfigurationBuilder()); manager.defineConfiguration(CACHE_NAME, config.build()); return manager; } }
4,742
37.25
119
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/module/MyParserExtension.java
package org.infinispan.configuration.module; import org.infinispan.commons.configuration.io.ConfigurationReader; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ConfigurationParser; import org.infinispan.configuration.parsing.Namespace; import org.infinispan.configuration.parsing.ParseUtils; import org.infinispan.configuration.parsing.ParserScope; /** * MyParserExtension. This is a simple extension parser which parses modules in the "urn:infinispan:config:mymodule" namespace * * @author Tristan Tarrant * @since 5.2 */ @Namespace(uri = "urn:infinispan:config:mymodule", root = "sample-element") @Namespace(root = "sample-element") public class MyParserExtension implements ConfigurationParser { @Override public void readElement(ConfigurationReader reader, ConfigurationBuilderHolder holder) { if (!holder.inScope(ParserScope.CACHE) && !holder.inScope(ParserScope.CACHE_TEMPLATE)) { throw new IllegalStateException("WRONG SCOPE"); } ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder(); Element element = Element.forName(reader.getLocalName()); switch (element) { case SAMPLE_ELEMENT: { parseSampleElement(reader, builder.addModule(MyModuleConfigurationBuilder.class)); break; } default: { throw ParseUtils.unexpectedElement(reader); } } } private void parseSampleElement(ConfigurationReader reader, MyModuleConfigurationBuilder builder) { for (int i = 0; i < reader.getAttributeCount(); i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); String value = reader.getAttributeValue(i); Attribute attribute = Attribute.forName(reader.getAttributeName(i)); switch (attribute) { case SAMPLE_ATTRIBUTE: { builder.attribute(value); break; } default: { throw ParseUtils.unexpectedAttribute(reader, i); } } } ParseUtils.requireNoContent(reader); } @Override public Namespace[] getNamespaces() { return ParseUtils.getNamespaceAnnotations(getClass()); } }
2,278
35.174603
126
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/module/Element.java
package org.infinispan.configuration.module; import java.util.HashMap; import java.util.Map; /** * Element. * * @author Tristan Tarrant * @since 5.2 */ public enum Element { // must be first UNKNOWN(null), SAMPLE_ELEMENT("sample-element"); private final String name; Element(final String name) { this.name = name; } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, Element> MAP; static { final Map<String, Element> map = new HashMap<String, Element>(8); for (Element element : values()) { final String name = element.getLocalName(); if (name != null) { map.put(name, element); } } MAP = map; } public static Element forName(final String localName) { final Element element = MAP.get(localName); return element == null ? UNKNOWN : element; } }
1,003
18.686275
71
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/module/MyModuleConfiguration.java
package org.infinispan.configuration.module; import org.infinispan.commons.configuration.BuiltBy; @BuiltBy(MyModuleConfigurationBuilder.class) public class MyModuleConfiguration { final private String attribute; MyModuleConfiguration(String attribute) { this.attribute = attribute; } public String attribute() { return attribute; } }
365
20.529412
52
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/module/ModuleConfigurationTest.java
package org.infinispan.configuration.module; import org.infinispan.commons.configuration.Combine; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; import static org.testng.AssertJUnit.assertEquals; @Test(groups = "unit", testName = "configuration.module.ModuleConfigurationTest") public class ModuleConfigurationTest { public void testModuleConfiguration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addModule(MyModuleConfigurationBuilder.class).attribute("testValue"); Configuration configuration = builder.build(); assertEquals(configuration.module(MyModuleConfiguration.class).attribute(), "testValue"); ConfigurationBuilder secondBuilder = new ConfigurationBuilder(); secondBuilder.read(configuration, Combine.DEFAULT); Configuration secondConfiguration = secondBuilder.build(); assertEquals(secondConfiguration.module(MyModuleConfiguration.class).attribute(), "testValue"); } }
1,077
40.461538
101
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/module/ExtendedParserTest.java
package org.infinispan.configuration.module; import static org.infinispan.test.TestingUtil.withCacheManager; import java.io.IOException; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.Assert; import org.testng.annotations.Test; /** * ExtendedParserTest. * * @author Tristan Tarrant * @since 5.2 */ @Test(groups = "unit", testName = "configuration.module.ExtendedParserTest") public class ExtendedParserTest extends AbstractInfinispanTest { public void testExtendedParserModulesElement() throws IOException { String config = TestingUtil.wrapXMLWithSchema("8.2", "<cache-container name=\"container-extra-modules\" default-cache=\"extra-module\">" + " <local-cache name=\"extra-module\">\n" + " <modules>\n" + " <sample-element xmlns=\"urn:infinispan:config:mymodule\" sample-attribute=\"test-value\" />\n" + " </modules>\n" + " </local-cache>\n" + "</cache-container>" ); assertCacheConfiguration(config); } public void testExtendedParserBareExtension() throws IOException { String config = TestingUtil.wrapXMLWithSchema( "<cache-container name=\"container-extra-modules\" default-cache=\"extra-module\">" + " <local-cache name=\"extra-module\">\n" + " <sample-element xmlns=\"urn:infinispan:config:mymodule\" sample-attribute=\"test-value\" />\n" + " </local-cache>\n" + "</cache-container>" ); assertCacheConfiguration(config); } private void assertCacheConfiguration(String config) throws IOException { ConfigurationBuilderHolder holder = parseToHolder(config); withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createClusteredCacheManager(holder)) { @Override public void call() { Assert.assertEquals(cm.getDefaultCacheConfiguration().module(MyModuleConfiguration.class).attribute(), "test-value"); } }); } private ConfigurationBuilderHolder parseToHolder(String config) { ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader()); return parserRegistry.parse(config); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "WRONG SCOPE") public void testExtendedParserWrongScope() { String config = TestingUtil.wrapXMLWithSchema( "<cache-container name=\"container-extra-modules\" default-cache=\"extra-module\">" + " <local-cache name=\"extra-module\">\n" + " </local-cache>\n" + " <sample-element xmlns=\"urn:infinispan:config:mymodule\" sample-attribute=\"test-value\" />\n" + "</cache-container>" ); parseToHolder(config); } }
3,204
38.567901
129
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/module/Attribute.java
package org.infinispan.configuration.module; import java.util.HashMap; import java.util.Map; /** * Attribute. * * @author Tristan Tarrant * @since 5.2 */ public enum Attribute { // must be first UNKNOWN(null), SAMPLE_ATTRIBUTE("sample-attribute"), ; private final String name; Attribute(final String name) { this.name = name; } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, Attribute> attributes; static { Map<String, Attribute> map = new HashMap<>(); for (Attribute attribute : values()) { final String name = attribute.getLocalName(); if (name != null) { map.put(name, attribute); } } attributes = map; } public static Attribute forName(final String localName) { final Attribute attribute = attributes.get(localName); return attribute == null ? UNKNOWN : attribute; } }
1,040
18.641509
60
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/module/MyModuleConfigurationBuilder.java
package org.infinispan.configuration.module; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.cache.AbstractModuleConfigurationBuilder; import org.infinispan.configuration.cache.ConfigurationBuilder; /** * * MyModuleConfigurationBuilder. A builder for {@link MyModuleConfiguration} * * @author Tristan Tarrant * @since 5.2 */ public class MyModuleConfigurationBuilder extends AbstractModuleConfigurationBuilder implements Builder<MyModuleConfiguration> { private String attribute; public MyModuleConfigurationBuilder(ConfigurationBuilder builder) { super(builder); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } public MyModuleConfigurationBuilder attribute(String attribute) { this.attribute = attribute; return this; } @Override public MyModuleConfiguration create() { return new MyModuleConfiguration(attribute); } @Override public MyModuleConfigurationBuilder read(MyModuleConfiguration template, Combine combine) { this.attribute(template.attribute()); return this; } }
1,263
27.727273
128
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/serializer/AbstractConfigurationSerializerTest.java
package org.infinispan.configuration.serializer; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.io.ConfigurationResourceResolvers; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.configuration.cache.AbstractStoreConfiguration; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexingConfiguration; import org.infinispan.configuration.cache.QueryConfiguration; import org.infinispan.configuration.cache.StoreConfiguration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @Test(groups = "functional") public abstract class AbstractConfigurationSerializerTest extends AbstractInfinispanTest { public static final List<MediaType> ALL = Arrays.asList(MediaType.APPLICATION_XML, MediaType.APPLICATION_YAML, MediaType.APPLICATION_JSON); public static final List<MediaType> XML = Collections.singletonList(MediaType.APPLICATION_XML); public static class Parameter { final Path config; final MediaType mediaType; final ParserRegistry registry; public Parameter(Path config, MediaType mediaType, ParserRegistry registry) { this.config = config; this.mediaType = mediaType; this.registry = registry; } @Override public String toString() { return config.subpath(config.getNameCount() - 3, config.getNameCount()) + " (" + mediaType.getSubType().toUpperCase() + ")"; } } @DataProvider(name = "configurationFiles") public Object[][] configurationFiles() throws Exception { Path configDir = Paths.get(System.getProperty("build.directory"), "test-classes", "configs", "all"); Properties properties = new Properties(); properties.put("jboss.server.temp.dir", System.getProperty("java.io.tmpdir")); ParserRegistry registry = new ParserRegistry(Thread.currentThread().getContextClassLoader(), false, properties); List<Path> paths = Files.list(configDir).collect(Collectors.toList()); return paths.stream().flatMap(p -> typesFor(p).stream().map(t -> new Object[]{new Parameter(p, t, registry)})).toArray(Object[][]::new); } public static List<MediaType> typesFor(Path p) { try { // If the file name starts with a number and it's >= 12, then use all media types. Otherwise just test XML return Integer.parseInt(p.getFileName().toString().split("\\.")[0]) >= 12 ? ALL : XML; } catch (NumberFormatException e) { // The file name is not a version number, test all media types. return ALL; } } @Test(dataProvider = "configurationFiles") public void configurationSerializationTest(Parameter parameter) throws IOException { URL url = FileLookupFactory.newInstance().lookupFileLocation(parameter.config.toString(), Thread.currentThread().getContextClassLoader()); ConfigurationBuilderHolder holderBefore = parameter.registry.parse(url); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Map<String, Configuration> configurations = new LinkedHashMap<>(); for (Map.Entry<String, ConfigurationBuilder> configuration : holderBefore.getNamedConfigurationBuilders().entrySet()) { configurations.put(configuration.getKey(), configuration.getValue().build()); } try (ConfigurationWriter writer = ConfigurationWriter.to(baos).withType(parameter.mediaType).build()) { parameter.registry.serialize(writer, holderBefore.getGlobalConfigurationBuilder().build(), configurations); } log.debug(baos); System.out.println(baos); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ConfigurationBuilderHolder holderAfter = parameter.registry.parse(bais, ConfigurationResourceResolvers.DEFAULT, parameter.mediaType); GlobalConfiguration globalConfigurationBefore = holderBefore.getGlobalConfigurationBuilder().build(); GlobalConfiguration globalConfigurationAfter = holderAfter.getGlobalConfigurationBuilder().build(); assertEquals(globalConfigurationBefore.security().securityCacheTimeout(), globalConfigurationAfter.security().securityCacheTimeout()); assertEquals(globalConfigurationBefore.security().securityCacheSize(), globalConfigurationAfter.security().securityCacheSize()); compareAttributeSets("Global", globalConfigurationBefore.globalState().attributes(), globalConfigurationAfter.globalState().attributes(), "localConfigurationStorage"); compareAttributeSets("Global", globalConfigurationBefore.jmx().attributes(), globalConfigurationAfter.jmx().attributes(), org.infinispan.configuration.parsing.Attribute.MBEAN_SERVER_LOOKUP.toString()); compareAttributeSets("Global", globalConfigurationBefore.security().authorization().attributes(), globalConfigurationAfter.security().authorization().attributes()); compareAttributeSets("Global", globalConfigurationBefore.serialization().attributes(), globalConfigurationAfter.serialization().attributes(), "marshaller", "classResolver", "advancedExternalizer", "contextInitializers"); compareAttributeSets("Global", globalConfigurationBefore.transport().attributes(), globalConfigurationAfter.transport().attributes(), "transport", "properties"); compareExtraGlobalConfiguration(globalConfigurationBefore, globalConfigurationAfter); for (String name : holderBefore.getNamedConfigurationBuilders().keySet()) { Configuration configurationBefore = holderBefore.getNamedConfigurationBuilders().get(name).build(); assertTrue(name, holderAfter.getNamedConfigurationBuilders().containsKey(name)); Configuration configurationAfter = holderAfter.getNamedConfigurationBuilders().get(name).build(); compareConfigurations(name, configurationBefore, configurationAfter); } } private void compareConfigurations(String name, Configuration configurationBefore, Configuration configurationAfter) { compareAttributeSets(name, configurationBefore.clustering().attributes(), configurationAfter.clustering().attributes()); compareAttributeSets(name, configurationBefore.clustering().hash().attributes(), configurationAfter.clustering().hash().attributes()); compareAttributeSets(name, configurationBefore.clustering().l1().attributes(), configurationAfter.clustering().l1().attributes()); compareAttributeSets(name, configurationBefore.clustering().partitionHandling().attributes(), configurationAfter.clustering().partitionHandling().attributes()); assertEquals(name, configurationBefore.memory(), configurationAfter.memory()); compareAttributeSets(name, configurationBefore.expiration().attributes(), configurationAfter.expiration().attributes()); compareIndexing(name, configurationBefore.indexing(), configurationAfter.indexing()); compareQuery(name, configurationBefore.query(), configurationAfter.query()); compareAttributeSets(name, configurationBefore.locking().attributes(), configurationAfter.locking().attributes()); compareAttributeSets(name, configurationBefore.statistics().attributes(), configurationAfter.statistics().attributes()); compareAttributeSets(name, configurationBefore.sites().attributes(), configurationAfter.sites().attributes()); compareSites(name, configurationBefore.sites().allBackups(), configurationAfter.sites().allBackups()); compareAttributeSets(name, configurationBefore.invocationBatching().attributes(), configurationAfter.invocationBatching().attributes()); compareAttributeSets(name, configurationBefore.customInterceptors().attributes(), configurationAfter.customInterceptors().attributes()); compareAttributeSets(name, configurationBefore.unsafe().attributes(), configurationAfter.unsafe().attributes()); compareAttributeSets(name, configurationBefore.persistence().attributes(), configurationAfter.persistence().attributes()); compareStores(name, configurationBefore.persistence().stores(), configurationAfter.persistence().stores()); compareAttributeSets(name, configurationBefore.security().authorization().attributes(), configurationAfter.security().authorization().attributes()); compareAttributeSets(name, configurationBefore.transaction().attributes(), configurationAfter.transaction().attributes(), "transaction-manager-lookup"); compareExtraConfiguration(name, configurationBefore, configurationAfter); } private void compareQuery(String name, QueryConfiguration before, QueryConfiguration after) { assertEquals(String.format("Query attributes for %s mismatch", name), before.attributes(), after.attributes()); } private void compareIndexing(String name, IndexingConfiguration before, IndexingConfiguration after) { assertEquals(String.format("Indexing attributes for %s mismatch", name), before.attributes(), after.attributes()); assertEquals(String.format("Indexing reader for %s mismatch", name), before.reader(), after.reader()); assertEquals(String.format("Indexing writer for %s mismatch", name), before.writer(), after.writer()); } protected void compareExtraConfiguration(String name, Configuration configurationBefore, Configuration configurationAfter) { // Do nothing. Subclasses can override to implement their own specific comparison } protected void compareExtraGlobalConfiguration(GlobalConfiguration configurationBefore, GlobalConfiguration configurationAfter) { // Do nothing. Subclasses can override to implement their own specific comparison } private void compareStores(String name, List<StoreConfiguration> beforeStores, List<StoreConfiguration> afterStores) { assertEquals("Configuration " + name + " stores count mismatch", beforeStores.size(), afterStores.size()); for (int i = 0; i < beforeStores.size(); i++) { StoreConfiguration beforeStore = beforeStores.get(i); StoreConfiguration afterStore = afterStores.get(i); compareStoreConfiguration(name, beforeStore, afterStore); } } protected void compareStoreConfiguration(String name, StoreConfiguration beforeStore, StoreConfiguration afterStore) { if (beforeStore instanceof AbstractStoreConfiguration) { AbstractStoreConfiguration beforeASC = (AbstractStoreConfiguration) beforeStore; AbstractStoreConfiguration afterASC = (AbstractStoreConfiguration) afterStore; compareAttributeSets(name, beforeASC.attributes(), afterASC.attributes()); compareAttributeSets(name, beforeASC.async().attributes(), afterASC.async().attributes()); } else { throw new IllegalArgumentException("Cannot compare stores of type: " + beforeStore.getClass().getName()); } } protected static void compareAttributeSets(String name, AttributeSet before, AttributeSet after, String... exclude) { if (before != null && after != null) { List<String> exclusions = exclude != null ? Arrays.asList(exclude) : Collections.emptyList(); for (Attribute<?> attribute : before.attributes()) { if (!exclusions.contains(attribute.name())) { assertEquals("Configuration " + name, attribute, after.attribute(attribute.name())); } } } } private void compareSites(String name, List<BackupConfiguration> sitesBefore, List<BackupConfiguration> sitesAfter) { assertEquals("Configuration " + name + " sites count mismatch", sitesBefore.size(), sitesAfter.size()); for (int i = 0; i < sitesBefore.size(); i++) { BackupConfiguration before = sitesBefore.get(i); BackupConfiguration after = sitesAfter.get(i); assertEquals("Configuration " + name + " stores class mismatch", before.getClass(), after.getClass()); compareAttributeSets(name, before.attributes(), after.attributes()); compareAttributeSets(name, before.takeOffline().attributes(), after.takeOffline().attributes()); compareAttributeSets(name, before.stateTransfer().attributes(), after.stateTransfer().attributes()); } } }
13,220
63.808824
226
java
null
infinispan-main/core/src/test/java/org/infinispan/configuration/serializer/ConfigurationSerializerTest.java
package org.infinispan.configuration.serializer; import org.testng.annotations.Test; @Test(testName = "configuration.serializer.ConfigurationSerializerTest", groups = "functional") public class ConfigurationSerializerTest extends AbstractConfigurationSerializerTest { }
272
33.125
95
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/MarshalledValuesEvictionTest.java
package org.infinispan.eviction.impl; import static org.infinispan.protostream.FileDescriptorSource.fromString; import static org.testng.AssertJUnit.assertEquals; import java.io.IOException; import java.io.UncheckedIOException; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.eviction.EvictionType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.jgroups.util.Util; import org.testng.annotations.Test; @Test(groups = "functional", testName = "eviction.MarshalledValuesEvictionTest") public class MarshalledValuesEvictionTest extends SingleCacheManagerTest { private static final int CACHE_SIZE = 128; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.memory().size(CACHE_SIZE).evictionType(EvictionType.COUNT).storageType(StorageType.BINARY) .expiration().wakeUpInterval(100L) .locking().useLockStriping(false) // to minimise chances of deadlock in the unit test .build(); cacheManager = TestCacheManagerFactory.createCacheManager(new ContextInitializer(), cfg); cache = cacheManager.getCache(); return cacheManager; } public void testEvictCustomKeyValue() { EvictionPojoMarshaller.resetStats(); int expectedWrites = 0; int expectedReads = 0; for (int i = 0; i < CACHE_SIZE * 2; i++) { EvictionPojo p1 = new EvictionPojo(); p1.i = (int) Util.random(2000); EvictionPojo p2 = new EvictionPojo(); p2.i = 24; Object old = cache.put(p1, p2); if (old != null) expectedReads++; // unmarshall old value if overwritten expectedWrites += 2; // key and value } assertEquals(CACHE_SIZE, cache.getAdvancedCache().getDataContainer().size()); assertEquals(expectedWrites, EvictionPojoMarshaller.writes.get()); assertEquals(expectedReads, EvictionPojoMarshaller.reads.get()); } public void testEvictPrimitiveKeyCustomValue() { EvictionPojoMarshaller.resetStats(); int expectedWrites = 0; int expectedReads = 0; for (int i = 0; i < CACHE_SIZE * 2; i++) { EvictionPojo p1 = new EvictionPojo(); p1.i = (int) Util.random(2000); Object old = cache.put(i, p1); if (old != null) expectedReads++; // unmarshall old value if overwritten expectedWrites++; // just the value } assertEquals(expectedWrites, EvictionPojoMarshaller.writes.get()); assertEquals(expectedReads, EvictionPojoMarshaller.reads.get()); } static class EvictionPojoMarshaller implements org.infinispan.protostream.MessageMarshaller<EvictionPojo> { static AtomicInteger writes = new AtomicInteger(); static AtomicInteger reads = new AtomicInteger(); public static void resetStats() { reads.set(0); writes.set(0); } @Override public EvictionPojo readFrom(ProtoStreamReader reader) throws IOException { EvictionPojo o = new EvictionPojo(); o.i = reader.readInt("i"); reads.incrementAndGet(); return o; } @Override public void writeTo(ProtoStreamWriter writer, EvictionPojo evictionPojo) throws IOException { writer.writeInt("i", evictionPojo.i); writes.incrementAndGet(); } @Override public Class<? extends EvictionPojo> getJavaClass() { return EvictionPojo.class; } @Override public String getTypeName() { return "EvictionPojo"; } } private static class ContextInitializer implements SerializationContextInitializer { @Override public String getProtoFileName() { return EvictionPojo.class.getName(); } @Override public String getProtoFile() throws UncheckedIOException { return "message EvictionPojo {optional int32 i=1;}"; } @Override public void registerSchema(SerializationContext serCtx) { serCtx.registerProtoFiles(fromString(getProtoFileName(), getProtoFile())); } @Override public void registerMarshallers(SerializationContext serCtx) { serCtx.registerMarshaller(new EvictionPojoMarshaller()); } } public static class EvictionPojo { @ProtoField(number = 1, defaultValue = "0") int i; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EvictionPojo pojo = (EvictionPojo) o; return i == pojo.i; } @Override public int hashCode() { int result; result = i; return result; } } }
5,198
32.980392
110
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/EvictionDuringBatchTest.java
package org.infinispan.eviction.impl; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.TimeUnit; import org.infinispan.AdvancedCache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @author Mircea Markus * @author anistor@redhat.com * @since 5.1 */ @Test (groups = "functional", testName = "eviction.EvictionDuringBatchTest") @CleanupAfterMethod public class EvictionDuringBatchTest extends SingleCacheManagerTest { protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfgBuilder = new ConfigurationBuilder(); cfgBuilder.memory().size(128) // 128 max entries .expiration().wakeUpInterval(100L) .locking().useLockStriping(false) // to minimize chances of deadlock in the unit test .invocationBatching().enable(true); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(cfgBuilder); cache = cm.getCache(); cache.addListener(new EvictionFunctionalTest.EvictionListener()); return cm; } public void testEvictionDuringBatchOperations() throws Exception { AdvancedCache<Object,Object> advancedCache = cache.getAdvancedCache(); for (int i = 0; i < 512; i++) { advancedCache.startBatch(); cache.put("key-" + (i + 1), "value-" + (i + 1), 1, TimeUnit.MINUTES); advancedCache.endBatch(true); } Thread.sleep(1000); // sleep long enough to allow the thread to wake-up int cacheSize = cache.size(); assertTrue("no data in cache! all state lost?", cacheSize != 0); assertTrue("cache size too big: " + cacheSize, cacheSize < 512); } public void testEvictInBatch() throws Exception { cache().put("myKey", "myValue"); cache().getAdvancedCache().startBatch(); //this should execute non-transactionally despite the batch transaction and should not fail as in https://issues.jboss.org/browse/ISPN-2845 cache().evict("myKey"); cache().getAdvancedCache().endBatch(true); assertFalse(cache().containsKey("myKey")); } }
2,406
37.822581
145
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/ManualEvictionWithPassivationAndSizeBasedAndConcurrentOperationsInBackupOwnerTest.java
package org.infinispan.eviction.impl; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.testng.annotations.Test; /** * Tests manual eviction with concurrent read and/or write operation. This test has passivation enabled and the eviction * happens in the backup owner * * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "eviction.ManualEvictionWithPassivationAndSizeBasedAndConcurrentOperationsInBackupOwnerTest") public class ManualEvictionWithPassivationAndSizeBasedAndConcurrentOperationsInBackupOwnerTest extends ManualEvictionWithSizeBasedAndConcurrentOperationsInBackupOwnerTest { { passivation = true; } @Override protected void configurePersistence(ConfigurationBuilder builder) { builder.persistence().passivation(true).addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(storeName + storeNamePrefix.getAndIncrement()); } }
1,033
37.296296
133
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/ManualEvictionWithPassivationAndSizeBasedAndConcurrentOperationsInPrimaryOwnerTest.java
package org.infinispan.eviction.impl; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.testng.annotations.Test; /** * Tests manual eviction with concurrent read and/or write operation. This test has passivation enabled and the eviction * happens in the primary owner * * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "eviction.ManualEvictionWithPassivationAndSizeBasedAndConcurrentOperationsInPrimaryOwnerTest") public class ManualEvictionWithPassivationAndSizeBasedAndConcurrentOperationsInPrimaryOwnerTest extends ManualEvictionWithSizeBasedAndConcurrentOperationsInPrimaryOwnerTest { { passivation = true; } @Override protected void configurePersistence(ConfigurationBuilder builder) { builder.persistence().passivation(true).addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(storeName + storeNamePrefix.getAndIncrement()); } }
1,037
37.444444
134
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/MemoryEvictionTest.java
package org.infinispan.eviction.impl; import java.util.Random; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.DataContainer; import org.infinispan.eviction.EvictionType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.Test; /** * This test is useful to test how much memory is in use by the data container. Since the Java GC may not clean up * everything on 1 pass, we have to run multiple passes through until we get a number that is relatively stable. * @author William Burns */ @Test(groups = "profiling", testName = "eviction.MemoryEvictionTest") public class MemoryEvictionTest extends SingleCacheManagerTest { private final long MAX_MEMORY = 400 * 1000 * 1000; private final int MATCH_COUNT = 5; private final static Log log = LogFactory.getLog(MemoryEvictionTest.class); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg .memory().storageType(StorageType.BINARY).evictionType(EvictionType.MEMORY).size(MAX_MEMORY) .build(); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(cfg); cache = cm.getCache(); return cm; } public void testSimpleSizeEviction() { log.debugf("Max memory: %d", MAX_MEMORY); DataContainer dc = cache.getAdvancedCache().getDataContainer(); printMemoryUsage(dc.size()); Random random = new Random(); int matchCount = 0; int byteKeySize = 10; int byteValueSize = 100; long previousMemorySize = 0; for (int j = 0; j < 200; ++j) { while (matchCount < this.MATCH_COUNT) { for (int i = 0; i < 20000; ++i) { byte[] keyBytes = new byte[byteKeySize]; byte[] valueBytes = new byte[byteValueSize]; random.nextBytes(keyBytes); random.nextBytes(valueBytes); cache.getAdvancedCache().put(keyBytes, valueBytes); } long memorySize = printMemoryUsage(dc.size()); if (memorySize == previousMemorySize) { matchCount++; } previousMemorySize = memorySize; } } } // Also returns size private long printMemoryUsage(int cacheSize) { System.gc(); System.gc(); Runtime runtime = Runtime.getRuntime(); long usedMemory = runtime.totalMemory() - runtime.freeMemory(); log.debugf("Used memory = %d, cache size = %d", usedMemory, cacheSize); return usedMemory; } }
2,867
36.736842
115
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/MemoryBasedEvictionFunctionalTest.java
package org.infinispan.eviction.impl; import static org.testng.AssertJUnit.assertTrue; import java.util.Arrays; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.global.SerializationConfigurationBuilder; import org.infinispan.container.offheap.OffHeapConcurrentMap; import org.infinispan.container.offheap.UnpooledOffHeapMemoryAllocator; import org.infinispan.eviction.EvictionType; import org.infinispan.eviction.impl.protostream.PrimitiveArrayCtx; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "eviction.MemoryBasedEvictionFunctionalTest") public class MemoryBasedEvictionFunctionalTest extends SingleCacheManagerTest { protected static final long CACHE_SIZE = 2000; protected StorageType storageType; public MemoryBasedEvictionFunctionalTest storageType(StorageType storageType) { this.storageType = storageType; return this; } protected void configure(ConfigurationBuilder cb) { } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); builder.memory().evictionType(EvictionType.MEMORY).storageType(storageType); if (storageType == StorageType.BINARY) { builder.memory().size(CACHE_SIZE); } else { builder.memory().size(CACHE_SIZE + UnpooledOffHeapMemoryAllocator.estimateSizeOverhead(OffHeapConcurrentMap.INITIAL_SIZE << 3)); } configure(builder); GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); SerializationConfigurationBuilder serialization = globalBuilder.serialization(); serialization.addContextInitializer(new PrimitiveArrayCtx()); serialization.addContextInitializer(TestDataSCI.INSTANCE); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(globalBuilder, builder); cache = cm.getCache(); return cm; } @Factory public Object[] factory() { return new Object[]{ new MemoryBasedEvictionFunctionalTest().storageType(StorageType.BINARY), new MemoryBasedEvictionFunctionalTest().storageType(StorageType.OFF_HEAP) }; } @Override protected String parameters() { return "[storageType=" + storageType + "]"; } public void testByteArray() throws Exception { int keyValueByteSize = 100; long numberInserted = CACHE_SIZE / 2 / keyValueByteSize; Random random = new Random(); // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (long i = 0; i < numberInserted; i++) { byte[] key = new byte[keyValueByteSize]; byte[] value = new byte[keyValueByteSize]; random.nextBytes(key); random.nextBytes(value); cache.put(key, value); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testByteObjectArray() throws Exception { int keyValueByteSize = 100; long numberInserted = CACHE_SIZE / 2 / keyValueByteSize; Random random = new Random(); // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (long i = 0; i < numberInserted; i++) { byte[] key = new byte[keyValueByteSize]; Byte[] value = new Byte[keyValueByteSize]; fillByteArray(random, key); fillByteArray(random, value); cache.put(key, value); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } private void fillByteArray(Random random, byte[] bytes) { random.nextBytes(bytes); } private void fillByteArray(Random random, Byte[] bytes) { byte[] singleByte = new byte[1]; for (int i = 0; i < bytes.length; ++i) { random.nextBytes(singleByte); bytes[i] = Byte.valueOf(singleByte[0]); } } public void testShort() throws Exception { long numberInserted = CACHE_SIZE / 2; Random random = new Random(); // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (short i = 0; i < numberInserted; i++) { cache.put(i, Short.valueOf((short) random.nextInt(Short.MAX_VALUE + 1))); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testShortArray() throws Exception { int arraySize = 10; long numberInserted = CACHE_SIZE / 2 / arraySize; Random random = new Random(); short[] shortArray = new short[arraySize]; Short[] ShortArray = new Short[arraySize]; // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (short i = 0; i < numberInserted; i++) { IntStream.range(0, arraySize).forEach(j -> shortArray[j] = (short) random.nextInt(Short.MAX_VALUE)); Arrays.setAll(ShortArray, j -> Short.valueOf((short) random.nextInt(Short.MAX_VALUE))); cache.put(shortArray, ShortArray); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testInteger() throws Exception { long numberInserted = CACHE_SIZE / 8; Random random = new Random(); // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (int i = 0; i < numberInserted; i++) { cache.put(i, Integer.valueOf(random.nextInt())); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testIntegerArray() throws Exception { int arraySize = 10; long numberInserted = CACHE_SIZE / 4 / arraySize; Random random = new Random(); int[] integerArray = new int[arraySize]; Integer[] IntegerArray = new Integer[arraySize]; // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (short i = 0; i < numberInserted; i++) { Arrays.setAll(integerArray, j -> random.nextInt()); Arrays.setAll(IntegerArray, j -> Integer.valueOf(random.nextInt())); cache.put(integerArray, IntegerArray); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testLong() throws Exception { long numberInserted = CACHE_SIZE / 4; Random random = new Random(); // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (long i = 0; i < numberInserted; i++) { cache.put(i, Long.valueOf(random.nextLong())); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testLongArray() throws Exception { int arraySize = 10; long numberInserted = CACHE_SIZE / 8 / arraySize; Random random = new Random(); long[] longArray = new long[arraySize]; Long[] LongArray = new Long[arraySize]; // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (short i = 0; i < numberInserted; i++) { Arrays.setAll(longArray, j -> random.nextLong()); Arrays.setAll(LongArray, j -> Long.valueOf(random.nextLong())); cache.put(longArray, LongArray); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testByte() throws Exception { long numberInserted = CACHE_SIZE / 2; Random random = new Random(); // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead byte[] bytes = new byte[1]; for (short i = 0; i < numberInserted; i++) { random.nextBytes(bytes); cache.put(i, bytes[0]); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testByteObject() throws Exception { long numberInserted = CACHE_SIZE / 2; Random random = new Random(); // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead byte[] bytes = new byte[1]; for (short i = 0; i < numberInserted; i++) { random.nextBytes(bytes); cache.put(i, Byte.valueOf(bytes[0])); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testFloat() throws Exception { long numberInserted = CACHE_SIZE / 4; Random random = new Random(); // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (float i = 0; i < numberInserted; i++) { cache.put(i, Float.valueOf(random.nextFloat())); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testDouble() throws Exception { long numberInserted = CACHE_SIZE / 8; Random random = new Random(); // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (double i = 0; i < numberInserted; i++) { cache.put(i, Double.valueOf(random.nextDouble())); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testDoubleArray() throws Exception { int arraySize = 10; long numberInserted = CACHE_SIZE / 8 / arraySize; Random random = new Random(); double[] doubleArray = new double[arraySize]; Double[] DoubleArray = new Double[arraySize]; // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (short i = 0; i < numberInserted; i++) { Arrays.setAll(doubleArray, j -> random.nextDouble()); Arrays.setAll(DoubleArray, j -> Double.valueOf(random.nextDouble())); cache.put(doubleArray, DoubleArray); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testString() throws Exception { int stringLength = 10; long numberInserted = CACHE_SIZE / stringLength + 4; Random random = new Random(); // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (long i = 0; i < numberInserted; i++) { cache.put(i, randomStringFullOfInt(random, stringLength)); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } public void testStringArray() throws Exception { int arraySize = 10; int stringLength = 10; long numberInserted = CACHE_SIZE / stringLength + 4 / arraySize; Random random = new Random(); String[] stringArray = new String[arraySize]; // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead AtomicInteger atomicInteger = new AtomicInteger(); for (long i = 0; i < numberInserted; i++) { atomicInteger.set(0); Arrays.setAll(stringArray, j -> randomStringFullOfInt(random, stringLength)); cache.put(i, stringArray); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } protected String randomStringFullOfInt(Random random, int digits) { return random.ints(digits, 0, 10).collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); } }
13,010
42.956081
137
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/ManualEvictionWithConcurrentOperationsInPrimaryOwnerTest.java
package org.infinispan.eviction.impl; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Same as {@link ManualEvictionWithSizeBasedAndConcurrentOperationsInPrimaryOwnerTest} but with an unbounded data * container * * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "eviction.ManualEvictionWithConcurrentOperationsInPrimaryOwnerTest", singleThreaded = true) public class ManualEvictionWithConcurrentOperationsInPrimaryOwnerTest extends ManualEvictionWithSizeBasedAndConcurrentOperationsInPrimaryOwnerTest { @Override protected void configureEviction(ConfigurationBuilder builder) { builder.memory().size(-1); } @Override public void testEvictionDuringRemove() { // Ignore this test as it requires size eviction } @Override public void testEvictionDuringWrite() { // Ignore this test as it requires size eviction } }
960
29.03125
131
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/EvictionWithPassivationTest.java
package org.infinispan.eviction.impl; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import java.util.Collections; import java.util.concurrent.CompletionStage; import java.util.concurrent.Future; import java.util.concurrent.Phaser; import java.util.concurrent.TimeUnit; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.Configurations; import org.infinispan.configuration.cache.StorageType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; import org.infinispan.notifications.cachelistener.event.CacheEntriesEvictedEvent; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "eviction.EvictionWithPassivationTest") public class EvictionWithPassivationTest extends SingleCacheManagerTest { private static final String CACHE_NAME = "testCache"; private final int EVICTION_MAX_ENTRIES = 2; private StorageType storage; private EvictionListener evictionListener; public EvictionWithPassivationTest() { // Cleanup needs to be after method, else LIRS can cause failures due to it not caching values due to hot // size being equal to full container size cleanup = CleanupPhase.AFTER_METHOD; } @Factory public Object[] factory() { return new Object[] { new EvictionWithPassivationTest().withStorage(StorageType.BINARY), new EvictionWithPassivationTest().withStorage(StorageType.OBJECT), new EvictionWithPassivationTest().withStorage(StorageType.OFF_HEAP) }; } @Override protected String parameters() { return "[" + storage + "]"; } private ConfigurationBuilder buildCfg() { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg .persistence() .passivation(true) .addStore(DummyInMemoryStoreConfigurationBuilder.class).purgeOnStartup(true) .invocationBatching().enable() .memory().storageType(storage); cfg.memory().size(EVICTION_MAX_ENTRIES); return cfg; } public EvictionWithPassivationTest withStorage(StorageType storage) { this.storage = storage; return this; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.createCacheManager(getDefaultStandaloneCacheConfig(true)); cacheManager.defineConfiguration(CACHE_NAME, buildCfg().build()); evictionListener = new EvictionListener(); Cache<String, String> testCache = cacheManager.getCache(CACHE_NAME); testCache.addListener(evictionListener); return cacheManager; } public void testBasicStore() { Cache<String, String> testCache = cacheManager.getCache(CACHE_NAME); testCache.clear(); testCache.put("X", "4567"); testCache.put("Y", "4568"); testCache.put("Z", "4569"); assertEquals("4567", testCache.get("X")); assertEquals("4568", testCache.get("Y")); assertEquals("4569", testCache.get("Z")); for (int i = 0; i < 10; i++) { testCache.getAdvancedCache().startBatch(); String k = "A" + i; testCache.put(k, k); k = "B" + i; testCache.put(k, k); testCache.getAdvancedCache().endBatch(true); } for (int i = 0; i < 10; i++) { String k = "A" + i; assertEquals(k, testCache.get(k)); k = "B" + i; assertEquals(k, testCache.get(k)); } } public void testActivationInBatchRolledBack() { Cache<String, String> testCache = cacheManager.getCache(CACHE_NAME); final String key = "X"; final String value = "4567"; testCache.clear(); testCache.put(key, value); testCache.evict(key); // Now make sure the act of activation for the entry is not tied to the transaction testCache.startBatch(); assertEquals(value, testCache.get(key)); testCache.endBatch(false); // The data should still be present even if a rollback occurred assertEquals(value, testCache.get(key)); } public void testActivationWithAnotherConcurrentRequest() throws Exception { final Cache<String, String> testCache = cacheManager.getCache(CACHE_NAME); final String key = "Y"; final String value = "4568"; testCache.clear(); testCache.put(key, value); testCache.evict(key); // Now make sure the act of activation for the entry is not tied to the transaction testCache.startBatch(); assertEquals(value, testCache.get(key)); // Another thread should be able to see the data as well! Future<String> future = testCache.getAsync(key); assertEquals(value, future.get(10, TimeUnit.SECONDS)); assertEquals(value, testCache.get(key)); testCache.endBatch(true); // Lastly try the retrieval after batch was committed assertEquals(value, testCache.get(key)); } public void testActivationPendingTransactionDoesNotAffectOthers() throws Throwable { final String previousValue = "prev-value"; final Cache<String, String> testCache = cacheManager.getCache(CACHE_NAME); testCache.clear(); final String key = "Y"; final String value; if (previousValue != null) { testCache.put(key, previousValue); value = previousValue + "4568"; } else { value = "4568"; } // evict so it is in the loader but not in data container testCache.evict(key); testCache.startBatch(); try { if (previousValue != null) { assertEquals(previousValue, testCache.put(key, value)); } else { assertNull(testCache.put(key, value)); } // In tx we should see new value assertEquals(value, testCache.get(key)); // The spawned thread shouldn't see the new value yet, should see the old one still Future<String> future = fork(() -> testCache.get(key)); if (previousValue != null) { assertEquals(previousValue, future.get(10000, TimeUnit.SECONDS)); } else { assertNull(future.get(10, TimeUnit.SECONDS)); } } catch (Throwable e) { testCache.endBatch(false); throw e; } testCache.endBatch(true); assertEquals(value, testCache.get(key)); } public void testActivationPutAllInBatchRolledBack() throws Exception { Cache<String, String> testCache = cacheManager.getCache(CACHE_NAME); final String key = "X"; final String value = "4567"; testCache.clear(); testCache.put(key, value); testCache.evict(key); // Now make sure the act of activation for the entry is not tied to the transaction testCache.startBatch(); testCache.putAll(Collections.singletonMap(key, value + "-putall")); testCache.endBatch(false); // The data should still be present even if a rollback occurred assertEquals(value, testCache.get(key)); } public void testRemovalOfEvictedEntry() throws Exception { Cache<String, String> testCache = cacheManager.getCache(CACHE_NAME); int phase = evictionListener.phaser.getPhase(); for (int i = 0; i < EVICTION_MAX_ENTRIES + 1; i++) { testCache.put("key" + i, "value" + i); } // Eviction notification can be non blocking async in certain configs - so wait for notification to complete evictionListener.phaser.awaitAdvanceInterruptibly(phase, 10, TimeUnit.SECONDS); String evictedKey = evictionListener.getEvictedKey(); assertEntryInStore(evictedKey, true); testCache.remove(evictedKey); assertFalse(testCache.containsKey(evictedKey)); assertNull(testCache.get(evictedKey)); } public void testComputeOnEvictedEntry() throws Exception { Cache<String, String> testCache = cacheManager.getCache(CACHE_NAME); int phase = evictionListener.phaser.getPhase(); for (int i = 0; i < EVICTION_MAX_ENTRIES + 1; i++) { testCache.put("key" + i, "value" + i); } // Eviction notification can be non blocking async in certain configs - so wait for notification to complete evictionListener.phaser.awaitAdvanceInterruptibly(phase, 10, TimeUnit.SECONDS); String evictedKey = evictionListener.getEvictedKey(); assertEntryInStore(evictedKey, true); testCache.compute(evictedKey, (k ,v) -> v + "-modfied"); assertEntryInStore(evictedKey, false); } public void testRemoveViaComputeOnEvictedEntry() throws Exception { Cache<String, String> testCache = cacheManager.getCache(CACHE_NAME); int phase = evictionListener.phaser.getPhase(); for (int i = 0; i < EVICTION_MAX_ENTRIES + 1; i++) { testCache.put("key" + i, "value" + i); } // Eviction notification can be non blocking async in certain configs - so wait for notification to complete evictionListener.phaser.awaitAdvanceInterruptibly(phase, 10, TimeUnit.SECONDS); String evictedKey = evictionListener.getEvictedKey(); if (evictedKey == null) { System.currentTimeMillis(); } assertEntryInStore(evictedKey, true); testCache.compute(evictedKey, (k ,v) -> null); assertFalse(testCache.containsKey(evictedKey)); assertEntryInStore(evictedKey, false); } public void testCleanStoreOnPut() throws Exception { Cache<String, String> testCache = cacheManager.getCache(CACHE_NAME); testCache.clear(); putIntoStore("key", "oldValue"); testCache.put("key", "value"); assertEntryInStore("key", false); } private void assertEntryInStore(String key, boolean expectPresent) throws Exception { assertNotNull(key); AdvancedCache<String, String> testCache = cacheManager.<String, String>getCache(CACHE_NAME).getAdvancedCache(); Object loaderKey = testCache.getKeyDataConversion().toStorage(key); CompletionStage<MarshallableEntry<String, String>> stage = TestingUtil.extractComponent(testCache, PersistenceManager.class) .loadFromAllStores(loaderKey, true, true); MarshallableEntry<String, String> entry = CompletionStages.join(stage); if (expectPresent) { assertNotNull(entry); } else { assertNull(entry); } DummyInMemoryStore loader = TestingUtil.getFirstStore(testCache); if (expectPresent) { eventuallyEquals(entry, () -> loader.loadEntry(loaderKey)); } else { assertFalse(loader.contains(loaderKey)); } } private void putIntoStore(String key, String value) { AdvancedCache<String, String> testCache = cacheManager.<String, String>getCache(CACHE_NAME).getAdvancedCache(); DummyInMemoryStore writer = TestingUtil.getFirstStore(testCache); Object writerKey = testCache.getKeyDataConversion().toStorage(key); Object writerValue = testCache.getValueDataConversion().toStorage(value); MarshallableEntry entry; if (Configurations.isTxVersioned(testCache.getCacheConfiguration())) { entry = MarshalledEntryUtil.createWithVersion(writerKey, writerValue, testCache); } else { entry = MarshalledEntryUtil.create(writerKey, writerValue, testCache); } writer.write(entry); } @Listener public static class EvictionListener { private String evictedKey; private final Phaser phaser = new Phaser(1); @CacheEntriesEvicted public void entryEvicted(CacheEntriesEvictedEvent e) { evictedKey = (String) e.getEntries().keySet().iterator().next(); // Notify main thread we have evicted something phaser.arrive(); } public String getEvictedKey() { return evictedKey; } } }
12,681
35.442529
130
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/EvictionWithConcurrentOperationsTest.java
package org.infinispan.eviction.impl; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.util.Arrays; import java.util.concurrent.Callable; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import org.infinispan.Cache; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.read.GetCacheEntryCommand; import org.infinispan.commands.read.GetKeyValueCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.context.Flag; import org.infinispan.context.InvocationContext; import org.infinispan.interceptors.AsyncInterceptor; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.interceptors.impl.EntryWrappingInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; import org.infinispan.notifications.cachelistener.event.CacheEntriesEvictedEvent; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.support.WaitNonBlockingStore; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.test.Mocks; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CheckPoint; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.DataOperationOrderer; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * Tests size-based eviction with concurrent read and/or write operation. In this test, we have no passivation. * * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "eviction.EvictionWithConcurrentOperationsTest") public class EvictionWithConcurrentOperationsTest extends SingleCacheManagerTest { protected boolean passivation = false; protected final AtomicInteger storeNamePrefix = new AtomicInteger(0); public final String storeName = getClass().getSimpleName(); protected final String persistentLocation = CommonsTestingUtil.tmpDirectory(getClass()); public EvictionWithConcurrentOperationsTest() { cleanup = CleanupPhase.AFTER_METHOD; } /** * ISPN-3048: this is a simple scenario. a put triggers the eviction while another thread tries to read. the read * occurs before the eviction listener is notified (and passivated if enabled). the key still exists in the map */ public void testScenario1() throws Exception { final Object key1 = new SameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final Object key2 = new SameHashCodeKey("key2"); final Latch latch = new Latch(); final ControlledPassivationManager controlledPassivationManager = replacePassivationManager(latch); //this will trigger the eviction of key1. key1 eviction will be blocked in the latch latch.enable(); Future<Object> put; try { put = fork(() -> cache.put(key2, "v2")); latch.waitToBlock(30, TimeUnit.SECONDS); //the eviction was trigger and it blocked before passivation assertEquals("Wrong value for key " + key1 + " in get operation.", "v1", cache.get(key1)); } finally { //let the eviction continue and wait for put latch.disable(); } put.get(30, TimeUnit.SECONDS); assertInMemory(key2, "v2"); assertNotInMemory(key1, "v1"); } /** * ISPN-3048: this is a simple scenario. a put triggers the eviction while another thread tries to read. the read * occurs after the eviction listener is notified (if passivation is enabled, it is written to disk). the key still * exists in the map */ public void testScenario2() throws Exception { final Object key1 = new SameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final Object key2 = new SameHashCodeKey("key2"); final Latch latch = new Latch(); final ControlledPassivationManager controlledPassivationManager = replacePassivationManager(latch); //this will trigger the eviction of key1. key1 eviction will be blocked in the latch latch.enable(); Future<Object> put; try { put = fork(() -> cache.put(key2, "v2")); latch.waitToBlock(30, TimeUnit.SECONDS); //the eviction was trigger and it blocked before passivation assertEquals("Wrong value for key " + key1 + " in get operation.", "v1", cache.get(key1)); } finally { //let the eviction continue and wait for put latch.disable(); } put.get(30, TimeUnit.SECONDS); assertInMemory(key2, "v2"); assertNotInMemory(key1, "v1"); } /** * ISPN-3048: a put triggers the eviction while another thread tries to read. the read occurs after the eviction * listener is notified (if passivation is enabled, it is written to disk) and after the entry is removed from the * map. however, it should be able to load it from persistence. */ public void testScenario3() throws Exception { final Object key1 = new SameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final Object key2 = new SameHashCodeKey("key2"); final Latch latch = new Latch(); final SyncEvictionListener evictionListener = new SyncEvictionListener() { @CacheEntriesEvicted @Override public void evicted(CacheEntriesEvictedEvent event) { if (event.getEntries().containsKey(key1)) { latch.blockIfNeeded(); } } }; cache.addListener(evictionListener); //this will trigger the eviction of key1. key1 eviction will be blocked in the latch latch.enable(); Future<Object> put; try { put = fork(() -> cache.put(key2, "v2")); latch.waitToBlock(30, TimeUnit.SECONDS); } finally { //let the eviction continue and wait for put latch.disable(); } put.get(30, TimeUnit.SECONDS); //the eviction was trigger and the key is no longer in the map // This should be after the async put is known to finish. It is undefined which would // win in the case of an entry being activated while it is also being passivated // This way it is clear which should be there assertEquals("Wrong value for key " + key1 + " in get operation.", "v1", cache.get(key1)); assertInMemory(key1, "v1"); assertNotInMemory(key2, "v2"); } /** * ISPN-3048: a put triggers the eviction while another thread tries to read. the read occurs after the eviction * listener is notified (if passivation is enabled, it is written to disk) and after the entry is removed from the * map. however, a concurrent read happens at the same time before the first has time to load it from persistence. */ public void testScenario4() throws Exception { final Object key1 = new SameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final Object key2 = new SameHashCodeKey("key2"); final Latch readLatch = new Latch(); final Latch writeLatch = new Latch(); final AtomicBoolean firstGet = new AtomicBoolean(false); final AfterEntryWrappingInterceptor afterEntryWrappingInterceptor = new AfterEntryWrappingInterceptor() .injectThis(cache); afterEntryWrappingInterceptor.beforeGet = () -> { if (firstGet.compareAndSet(false, true)) { readLatch.blockIfNeeded(); } }; final SyncEvictionListener evictionListener = new SyncEvictionListener() { @CacheEntriesEvicted @Override public void evicted(CacheEntriesEvictedEvent event) { if (event.getEntries().containsKey(key1)) { writeLatch.blockIfNeeded(); } } }; cache.addListener(evictionListener); //this will trigger the eviction of key1. key1 eviction will be blocked in the latch readLatch.enable(); Future<Object> put = fork(() -> cache.put(key2, "v2")); writeLatch.waitToBlock(30, TimeUnit.SECONDS); //the eviction was trigger and the key is no longer in the map Future<Object> get = fork(() -> cache.get(key1)); readLatch.waitToBlock(30, TimeUnit.SECONDS); // Ensures the eviction is complete of key1 put.get(30, TimeUnit.SECONDS); //the first read is blocked. it has check the data container and it didn't found any value //this second get should not block anywhere and it should fetch the value from persistence assertEquals("Wrong value for key " + key1 + " in get operation.", "v1", cache.get(key1)); //let the second get continue readLatch.disable(); assertEquals("Wrong value for key " + key1 + " in get operation.", "v1", get.get()); assertInMemory(key1, "v1"); assertNotInMemory(key2, "v2"); } /** * ISPN-3048: a put triggers the eviction while another thread tries to read. the read occurs after the eviction * listener is notified (if passivation is enabled, it is written to disk) and after the entry is removed from the * map. however, a concurrent put happens at the same time before the get has time to load it from persistence. */ public void testScenario5() throws Exception { final Object key1 = new SameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final Object key2 = new SameHashCodeKey("key2"); final Latch readLatch = new Latch(); final Latch writeLatch = new Latch(); final AfterEntryWrappingInterceptor afterEntryWrappingInterceptor = new AfterEntryWrappingInterceptor() .injectThis(cache); afterEntryWrappingInterceptor.beforeGet = () -> readLatch.blockIfNeeded(); final SyncEvictionListener evictionListener = new SyncEvictionListener() { @CacheEntriesEvicted @Override public void evicted(CacheEntriesEvictedEvent event) { if (event.getEntries().containsKey(key1)) { writeLatch.blockIfNeeded(); } } }; cache.addListener(evictionListener); //this will trigger the eviction of key1. key1 eviction will be blocked in the latch readLatch.enable(); Future<Object> get; try { cache.put(key2, "v2"); writeLatch.waitToBlock(30, TimeUnit.SECONDS); //the eviction was trigger and the key is no longer in the map get = fork(() -> cache.get(key1)); readLatch.waitToBlock(30, TimeUnit.SECONDS); //the first read is blocked. it has check the data container and it didn't found any value //this second get should not block anywhere and it should fetch the value from persistence assertEquals("Wrong value for key " + key1 + " in get operation.", "v1", cache.put(key1, "v3")); } finally { //let the get continue readLatch.disable(); } assertEquals("Wrong value for key " + key1 + " in get operation.", "v3", get.get(30, TimeUnit.SECONDS)); assertInMemory(key1, "v3"); assertNotInMemory(key2, "v2"); } /** * ISPN-3048: a put triggers the eviction while another thread tries to read. the read occurs after the eviction * listener is notified (if passivation is enabled, it is written to disk) and after the entry is removed from the * map. however, a concurrent put happens at the same time before the get has time to load it from persistence. The * get will occur after the put writes to persistence and before writes to data container */ public void testScenario6() throws Exception { final Object key1 = new SameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final Object key2 = new SameHashCodeKey("key2"); final Latch readLatch = new Latch(); final Latch writeLatch = new Latch(); final Latch writeLatch2 = new Latch(); final AtomicBoolean firstWriter = new AtomicBoolean(false); final AfterEntryWrappingInterceptor afterEntryWrappingInterceptor = new AfterEntryWrappingInterceptor() .injectThis(cache); afterEntryWrappingInterceptor.beforeGet = () -> readLatch.blockIfNeeded(); afterEntryWrappingInterceptor.afterPut = () -> { if (!firstWriter.compareAndSet(false, true)) { writeLatch2.blockIfNeeded(); } }; final SyncEvictionListener evictionListener = new SyncEvictionListener() { @CacheEntriesEvicted @Override public void evicted(CacheEntriesEvictedEvent event) { if (event.getEntries().containsKey(key1)) { writeLatch.blockIfNeeded(); } } }; cache.addListener(evictionListener); //this will trigger the eviction of key1. key1 eviction will be blocked in the latch readLatch.enable(); Future<Object> get; Future<Object> put2; try { Future<Object> put = fork(() -> cache.put(key2, "v2")); writeLatch.waitToBlock(30, TimeUnit.SECONDS); //the eviction was trigger and the key is no longer in the map get = fork(() -> cache.get(key1)); readLatch.waitToBlock(30, TimeUnit.SECONDS); // Ensures the eviction is complete of key1 put.get(30, TimeUnit.SECONDS); put2 = cache.putAsync(key1, "v3"); //wait until the 2nd put writes to persistence writeLatch2.waitToBlock(30, TimeUnit.SECONDS); } finally { //let the get continue readLatch.disable(); } assertPossibleValues(key1, get.get(30, TimeUnit.SECONDS), "v1", "v3"); assertEquals("Wrong value for key " + key1 + " in put operation.", "v1", put2.get(30, TimeUnit.SECONDS)); assertInMemory(key1, "v3"); assertNotInMemory(key2, "v2"); } /** * ISPN-3854: an entry is evicted. a get operation is performed and loads the entry from the persistence. However, * before continue the processing, a put succeeds and updates the key. Check in the end if the key is correctly * stored or not. */ public void testScenario7() throws Exception { final Object key1 = new SameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final Latch readLatch = new Latch(); final AfterActivationOrCacheLoader commandController = new AfterActivationOrCacheLoader() .injectThis(cache); commandController.afterGet = () -> readLatch.blockIfNeeded(); cache.evict(key1); assertNotInMemory(key1, "v1"); //perform the get. it will load the entry from cache loader. readLatch.enable(); Future<Object> get; try { get = fork(() -> cache.get(key1)); readLatch.waitToBlock(30, TimeUnit.SECONDS); //now, we perform a put. assertEquals("Wrong value for key " + key1 + " in put operation.", "v1", cache.put(key1, "v2")); } finally { //we let the get go... readLatch.disable(); } assertPossibleValues(key1, get.get(30, TimeUnit.SECONDS), "v1"); assertInMemory(key1, "v2"); } // Data is written to container but before releasing orderer the entry is evicted. In this case the entry // should be passivated to ensure data is still around public void testEvictionDuringWrite() throws InterruptedException, ExecutionException, TimeoutException { String key = "evicted-key"; // We use skip cache load to prevent the additional loading of the entry in the initial write testEvictionDuring(key, () -> cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD).put(key, "value"), AssertJUnit::assertNull, AssertJUnit::assertNotNull, true); } // This case the removal acquires the orderer lock, but doesn't yet remove the value. Then the eviction occurs // but can't complete yet as the orderer is still owned by removal. Then remove completes, but the eviction // should <b>NOT</b> passivate the entry as it was removed prior. public void testEvictionDuringRemove() throws InterruptedException, ExecutionException, TimeoutException { String key = "evicted-key"; cache.put(key, "removed"); testEvictionDuring(key, () -> cache.remove(key), AssertJUnit::assertNotNull, AssertJUnit::assertNull, false); } /** * Tests that an entry was written to container, but before it releases its orderer it is evicted */ void testEvictionDuring(String key, Callable<Object> callable, Consumer<Object> valueConsumer, Consumer<Object> finalResultConsumer, boolean blockOnCompletion) throws TimeoutException, InterruptedException, ExecutionException { // We use this checkpoint to hold the orderer lock during the write - which means the eviction will have to handle // it appropriately CheckPoint operationCheckPoint = new CheckPoint("operation"); operationCheckPoint.triggerForever(blockOnCompletion ? Mocks.AFTER_RELEASE : Mocks.BEFORE_RELEASE); DataOperationOrderer original; if (blockOnCompletion) { // Blocks just before releasing the orderer original = Mocks.blockingMock(operationCheckPoint, DataOperationOrderer.class, cache, (stub, m) -> stub.when(m).completeOperation(eq(key), any(), any())); } else { // Blocks just after acquiring orderer original = Mocks.blockingMock(operationCheckPoint, DataOperationOrderer.class, cache, (stub, m) -> stub.when(m).orderOn(eq(key), any())); } // Put the key which will wait on releasing the orderer at the end Future<Object> operationFuture = fork(callable); // Confirm everything is complete except releasing orderer operationCheckPoint.awaitStrict(Mocks.BEFORE_INVOCATION, 10, TimeUnit.SECONDS); // Replace the original so the eviction doesn't get blocked by the other check point TestingUtil.replaceComponent(cache, DataOperationOrderer.class, original, true); // We use this checkpoint to wait until the eviction is in process (that is that it has the caffeine lock // and has to wait until the prior orderer above completes CheckPoint evictionCheckPoint = new CheckPoint("eviction"); evictionCheckPoint.triggerForever(Mocks.BEFORE_RELEASE); Mocks.blockingMock(evictionCheckPoint, DataOperationOrderer.class, cache, (stub, m) -> stub.when(m).orderOn(eq(key), any())); // Put another key, which will evict our original key Future<Object> evictFuture = fork(() -> cache.put("other-key", "other-value")); // Now wait for the eviction to retrieve the orderer - but don't let it continue evictionCheckPoint.awaitStrict(Mocks.AFTER_INVOCATION, 10, TimeUnit.SECONDS); // Let the put complete operationCheckPoint.trigger(blockOnCompletion ? Mocks.BEFORE_RELEASE : Mocks.AFTER_RELEASE); // If the block is not on completion, that means that eviction holds the caffeine lock which means it may // be preventing the actual operation from completing - thus we free the eviction sooner if (!blockOnCompletion) { evictionCheckPoint.triggerForever(Mocks.AFTER_RELEASE); } // And ensure the operation complete valueConsumer.accept(operationFuture.get(10, TimeUnit.SECONDS)); // Finally let the eviction to complete if it wasn't above evictionCheckPoint.triggerForever(Mocks.AFTER_RELEASE); evictFuture.get(10, TimeUnit.SECONDS); finalResultConsumer.accept(cache.get(key)); } protected void initializeKeyAndCheckData(Object key, Object value) { assertTrue("A cache store should be configured!", cache.getCacheConfiguration().persistence().usingStores()); cache.put(key, value); DataContainer<?, ?> container = cache.getAdvancedCache().getDataContainer(); InternalCacheEntry<?, ?> entry = container.peek(key); assertNotNull("Key " + key + " does not exist in data container.", entry); assertEquals("Wrong value for key " + key + " in data container.", value, entry.getValue()); WaitNonBlockingStore<?, ?> loader = TestingUtil.getFirstStoreWait(cache); MarshallableEntry<?, ?> entryLoaded = loader.loadEntry(key); if (passivation) { assertNull(entryLoaded); } else { assertEquals("Wrong value for key " + key + " in cache loader", value, extractValue(entryLoaded)); } } protected void assertInMemory(Object key, Object value) { DataContainer<?, ?> container = cache.getAdvancedCache().getDataContainer(); InternalCacheEntry<?, ?> entry = container.get(key); assertNotNull("Key " + key + " does not exist in data container", entry); assertEquals("Wrong value for key " + key + " in data container", value, entry.getValue()); WaitNonBlockingStore<?, ?> loader = TestingUtil.getFirstStoreWait(cache); if (passivation) { // With passivation the entry must not exist in the store // but the removal is sometimes delayed PersistenceManager pm = TestingUtil.extractComponent(cache, PersistenceManager.class); assertNull(join(pm.loadFromAllStores(key, true, true))); eventuallyEquals(null, () -> loader.loadEntry(key)); } else { MarshallableEntry<?, ?> entryLoaded = loader.loadEntry(key); assertEquals("Wrong value for key " + key + " in cache loader", value, extractValue(entryLoaded)); } } protected void assertNotInMemory(Object key, Object value) { DataContainer<?, ?> container = cache.getAdvancedCache().getDataContainer(); InternalCacheEntry<?, ?> memoryEntry = container.peek(key); assertNull("Key " + key + " exists in data container", memoryEntry); WaitNonBlockingStore<?, ?> loader = TestingUtil.getFirstStoreWait(cache); if (passivation) { // With passivation the store write is sometimes delayed PersistenceManager pm = TestingUtil.extractComponent(cache, PersistenceManager.class); MarshallableEntry<?, ?> entryLoaded = join(pm.loadFromAllStores(key, true, true)); assertEquals("Wrong value for key " + key + " in cache loader", value, extractValue(entryLoaded)); eventuallyEquals("Wrong value for key " + key + " in cache loader", value, () -> extractValue(loader.loadEntry(key))); } else { MarshallableEntry<?, ?> entryLoaded = loader.loadEntry(key); assertEquals("Wrong value for key " + key + " in cache loader", value, extractValue(entryLoaded)); } } private Object extractValue(MarshallableEntry<?, ?> entry) { return entry != null ? entry.getValue() : null; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(false); configurePersistence(builder); configureEviction(builder); GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); globalBuilder.serialization().addContextInitializer(new EvictionWithConcurrentOperationsSCIImpl()); globalBuilder.globalState().enable().persistentLocation(persistentLocation); return TestCacheManagerFactory.createCacheManager(globalBuilder, builder); } @AfterClass(alwaysRun = true) protected void clearTempDir() { Util.recursiveFileRemove(persistentLocation); } protected void configureEviction(ConfigurationBuilder builder) { builder.memory().size(1); } protected void configurePersistence(ConfigurationBuilder builder) { builder.persistence().passivation(false).addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(storeName + storeNamePrefix.getAndIncrement()); } protected final ControlledPassivationManager replacePassivationManager(final Latch latch) { PassivationManager current = TestingUtil.extractComponent(cache, PassivationManager.class); ControlledPassivationManager controlledPassivationManager = new ControlledPassivationManager(current); controlledPassivationManager.beforePassivate = latch::blockIfNeeded; TestingUtil.replaceComponent(cache, PassivationManager.class, controlledPassivationManager, true); return controlledPassivationManager; } protected void assertPossibleValues(Object key, Object value, Object... expectedValues) { for (Object expectedValue : expectedValues) { if (value == null ? expectedValue == null : value.equals(expectedValue)) { return; } } fail("Wrong value for key " + key + ". value=" + value + ", expectedValues=" + Arrays.toString(expectedValues)); } public static class SameHashCodeKey { @ProtoField(1) final String name; @ProtoField(number = 2, defaultValue = "0") final int hashCode; //same hash code to force the keys to be in the same segment. SameHashCodeKey(String name) { this(name, 0); } @ProtoFactory SameHashCodeKey(String name, int hashCode) { this.name = name; this.hashCode = hashCode; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SameHashCodeKey that = (SameHashCodeKey) o; return name.equals(that.name); } @Override public int hashCode() { return hashCode; } @Override public String toString() { return name; } } protected class ControlledPassivationManager implements PassivationManager { protected final PassivationManager delegate; protected volatile Runnable beforePassivate; protected volatile Runnable afterPassivate; private ControlledPassivationManager(PassivationManager delegate) { this.delegate = delegate; } @Override public boolean isEnabled() { return delegate.isEnabled(); } @Override public CompletionStage<Void> passivateAsync(InternalCacheEntry entry) { final Runnable before = beforePassivate; if (before != null) { before.run(); } CompletionStage<Void> stage = delegate.passivateAsync(entry); final Runnable after = afterPassivate; if (after != null) { return stage.thenRun(after); } return stage; } @Override public CompletionStage<Void> passivateAllAsync() { return delegate.passivateAllAsync(); } @Override public void skipPassivationOnStop(boolean skip) { delegate.skipPassivationOnStop(skip); } @Override public long getPassivations() { return delegate.getPassivations(); } @Override public boolean getStatisticsEnabled() { return delegate.getStatisticsEnabled(); } @Override public void setStatisticsEnabled(boolean enabled) { delegate.setStatisticsEnabled(enabled); } @Override public void resetStatistics() { delegate.resetStatistics(); } } @Listener(sync = true) protected abstract class SyncEvictionListener { @CacheEntriesEvicted public abstract void evicted(CacheEntriesEvictedEvent event); } protected abstract class ControlledCommandInterceptor extends DDAsyncInterceptor { volatile Runnable beforeGet; volatile Runnable afterGet; volatile Runnable beforePut; volatile Runnable afterPut; @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { return handle(ctx, command, beforePut, afterPut); } @Override public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { return handle(ctx, command, beforeGet, afterGet); } @Override public Object visitGetCacheEntryCommand(InvocationContext ctx, GetCacheEntryCommand command) throws Throwable { return handle(ctx, command, beforeGet, afterGet); } protected final Object handle(InvocationContext ctx, VisitableCommand command, Runnable before, Runnable after) throws Throwable { if (before != null) { before.run(); } return invokeNextThenAccept(ctx, command, (rCtx, rCommand, rv) -> { if (after != null) { after.run(); } }); } } protected class AfterEntryWrappingInterceptor extends ControlledCommandInterceptor { public AfterEntryWrappingInterceptor injectThis(Cache<Object, Object> injectInCache) { TestingUtil.extractInterceptorChain(injectInCache).addInterceptorAfter(this, EntryWrappingInterceptor.class); return this; } } class AfterActivationOrCacheLoader extends ControlledCommandInterceptor { public AfterActivationOrCacheLoader injectThis(Cache<Object, Object> injectInCache) { AsyncInterceptorChain chain = TestingUtil.extractComponent(injectInCache, AsyncInterceptorChain.class); AsyncInterceptor loaderInterceptor = chain.findInterceptorExtending(org.infinispan.interceptors.impl.CacheLoaderInterceptor.class); TestingUtil.extractInterceptorChain(injectInCache).addInterceptorAfter(this, loaderInterceptor.getClass()); return this; } } protected class Latch { private boolean enabled = false; private boolean blocked = false; public final synchronized void enable() { this.enabled = true; } public final synchronized void disable() { this.enabled = false; notifyAll(); } public final synchronized void blockIfNeeded() { blocked = true; notifyAll(); while (enabled) { try { wait(TimeUnit.SECONDS.toMillis(10)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } } public final synchronized void waitToBlock(long timeout, TimeUnit timeUnit) throws InterruptedException, TimeoutException { final long endTime = Util.currentMillisFromNanotime() + timeUnit.toMillis(timeout); long waitingTime; while (!blocked && (waitingTime = endTime - Util.currentMillisFromNanotime()) > 0) { wait(waitingTime); } if (!blocked) { throw new TimeoutException(); } } } @AutoProtoSchemaBuilder( includeClasses = SameHashCodeKey.class, schemaFileName = "test.core.eviction.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.test.core.eviction", service = false ) interface EvictionWithConcurrentOperationsSCI extends SerializationContextInitializer { } }
32,735
40.437975
141
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/ExceptionEvictionTest.java
package org.infinispan.eviction.impl; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.fail; import java.util.Iterator; import java.util.concurrent.TimeUnit; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.Status; import jakarta.transaction.SystemException; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.MemoryConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.offheap.OffHeapConcurrentMap; import org.infinispan.container.offheap.UnpooledOffHeapMemoryAllocator; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.encoding.DataConversion; import org.infinispan.eviction.EvictionStrategy; import org.infinispan.eviction.EvictionType; import org.infinispan.expiration.ExpirationManager; import org.infinispan.interceptors.impl.ContainerFullException; import org.infinispan.interceptors.impl.TransactionalExceptionEvictionInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.Address; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.TransactionMode; import org.infinispan.util.ControlledTimeService; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * @author wburns * @since 9.0 */ @Test(groups = "functional", testName = "eviction.ExceptionEvictionTest") public class ExceptionEvictionTest extends MultipleCacheManagersTest { private static final int SIZE = 10; /** * The JVM overhead in bytes for an immortal entry when integer keys and values are marshalled with protostream and * stored as {@link org.infinispan.protostream.WrappedMessage}. * More details on {@link org.infinispan.container.entries.CacheEntrySizeCalculator}. */ public static final int IMMORTAL_ENTRY_SIZE = 104; /** * The overhead per entry in bytes when using optimistic transactions, due to extra storage in the metadata. */ public static final int OPTIMISTIC_TX_OVERHEAD = 48; /** * The extra overhead per entry in bytes due to usage of maxIdle or lifespan. */ public static final int MORTAL_ENTRY_OVERHEAD = 16; private int nodeCount; private ConfigurationBuilder configurationBuilder; protected ControlledTimeService timeService = new ControlledTimeService(); public ExceptionEvictionTest nodeCount(int nodeCount) { this.nodeCount = nodeCount; return this; } // Here to allow cacheMode to be method chained properly @Override public ExceptionEvictionTest cacheMode(CacheMode cacheMode) { super.cacheMode(cacheMode); return this; } @Override public Object[] factory() { return new Object[] { new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.OFF_HEAP).cacheMode(CacheMode.LOCAL).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.OFF_HEAP).cacheMode(CacheMode.DIST_SYNC).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.OFF_HEAP).cacheMode(CacheMode.REPL_SYNC).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(3).storageType(StorageType.OFF_HEAP).cacheMode(CacheMode.DIST_SYNC).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(3).storageType(StorageType.OFF_HEAP).cacheMode(CacheMode.REPL_SYNC).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.BINARY).cacheMode(CacheMode.LOCAL).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.BINARY).cacheMode(CacheMode.DIST_SYNC).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.BINARY).cacheMode(CacheMode.REPL_SYNC).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(3).storageType(StorageType.BINARY).cacheMode(CacheMode.DIST_SYNC).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(3).storageType(StorageType.BINARY).cacheMode(CacheMode.REPL_SYNC).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.OBJECT).cacheMode(CacheMode.LOCAL).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.OBJECT).cacheMode(CacheMode.DIST_SYNC).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.OBJECT).cacheMode(CacheMode.REPL_SYNC).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(3).storageType(StorageType.OBJECT).cacheMode(CacheMode.DIST_SYNC).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(3).storageType(StorageType.OBJECT).cacheMode(CacheMode.REPL_SYNC).lockingMode(LockingMode.OPTIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.OFF_HEAP).cacheMode(CacheMode.LOCAL).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.OFF_HEAP).cacheMode(CacheMode.DIST_SYNC).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.OFF_HEAP).cacheMode(CacheMode.REPL_SYNC).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(3).storageType(StorageType.OFF_HEAP).cacheMode(CacheMode.DIST_SYNC).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(3).storageType(StorageType.OFF_HEAP).cacheMode(CacheMode.REPL_SYNC).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.BINARY).cacheMode(CacheMode.LOCAL).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.BINARY).cacheMode(CacheMode.DIST_SYNC).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.BINARY).cacheMode(CacheMode.REPL_SYNC).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(3).storageType(StorageType.BINARY).cacheMode(CacheMode.DIST_SYNC).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(3).storageType(StorageType.BINARY).cacheMode(CacheMode.REPL_SYNC).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.OBJECT).cacheMode(CacheMode.LOCAL).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.OBJECT).cacheMode(CacheMode.DIST_SYNC).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(1).storageType(StorageType.OBJECT).cacheMode(CacheMode.REPL_SYNC).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(3).storageType(StorageType.OBJECT).cacheMode(CacheMode.DIST_SYNC).lockingMode(LockingMode.PESSIMISTIC), new ExceptionEvictionTest().nodeCount(3).storageType(StorageType.OBJECT).cacheMode(CacheMode.REPL_SYNC).lockingMode(LockingMode.PESSIMISTIC), }; } @Override protected String[] parameterNames() { return concat(super.parameterNames(), "nodeCount"); } @Override protected Object[] parameterValues() { return concat(super.parameterValues(), nodeCount); } @Override protected void createCacheManagers() throws Throwable { configurationBuilder = new ConfigurationBuilder(); MemoryConfigurationBuilder memoryConfigurationBuilder = configurationBuilder.memory(); memoryConfigurationBuilder.storageType(storageType); memoryConfigurationBuilder.evictionStrategy(EvictionStrategy.EXCEPTION); switch (storageType) { case OBJECT: memoryConfigurationBuilder.size(SIZE); break; case BINARY: memoryConfigurationBuilder.evictionType(EvictionType.MEMORY).size(convertAmountForStorage(SIZE) + MORTAL_ENTRY_OVERHEAD); break; case OFF_HEAP: // Each entry takes up 63 bytes total for our tests, however tests that add expiration require 16 more memoryConfigurationBuilder.evictionType(EvictionType.MEMORY).size(24 + // If we are running optimistic transactions we have to store version so it is larger than pessimistic convertAmountForStorage(SIZE) + UnpooledOffHeapMemoryAllocator.estimateSizeOverhead(OffHeapConcurrentMap.INITIAL_SIZE << 3)); break; } configurationBuilder .transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .lockingMode(lockingMode); configurationBuilder .clustering() .cacheMode(cacheMode) .hash() // Num owners has to be the same to guarantee amount of entries written .numOwners(nodeCount); for (int i = 0; i < nodeCount; ++i) { addClusterEnabledCacheManager(configurationBuilder); } for (int i = 0; i < nodeCount; ++i) { EmbeddedCacheManager manager = manager(i); TestingUtil.replaceComponent(manager, TimeService.class, timeService, true); } waitForClusterToForm(); } @AfterMethod @Override protected void clearContent() throws Throwable { super.clearContent(); // Call actual clear to reset interceptor counter for (Cache cache : caches()) { cache.clear(); } for (Cache cache : caches()) { // Have to use eventually as depending on which node but the transaction completion can be fired async eventuallyEquals(0l, () -> TestingUtil.extractComponent(cache, TransactionalExceptionEvictionInterceptor.class) .pendingTransactionCount()); } } Throwable getMostNestedSuppressedThrowable(Throwable t) { Throwable nested = getNestedThrowable(t); Throwable[] suppressedNested = nested.getSuppressed(); if (suppressedNested.length > 0) { nested = getNestedThrowable(suppressedNested[0]); } return nested; } Throwable getNestedThrowable(Throwable t) { Throwable cause; while ((cause = t.getCause()) != null) { t = cause; } return t; } long convertAmountForStorage(long expected) { boolean optimistic = lockingMode == LockingMode.OPTIMISTIC; switch (storageType) { case OBJECT: return expected; case BINARY: return expected * (optimistic ? IMMORTAL_ENTRY_SIZE + OPTIMISTIC_TX_OVERHEAD : IMMORTAL_ENTRY_SIZE); case OFF_HEAP: return expected * (optimistic ? UnpooledOffHeapMemoryAllocator.estimateSizeOverhead(51) : UnpooledOffHeapMemoryAllocator.estimateSizeOverhead(33)); default: throw new IllegalStateException("Unconfigured storage type: " + storageType); } } /** * Asserts that number of entries worth of counts is stored in the interceptors */ void assertInterceptorCount() { for (Cache cache : caches()) { // We use eventually as waitForNoRebalance does not wait until old entries are removed - causing random failures eventually(() -> { long expectedCount = convertAmountForStorage(cache.getAdvancedCache().getDataContainer().sizeIncludingExpired()); TransactionalExceptionEvictionInterceptor interceptor = TestingUtil.extractComponent(cache, TransactionalExceptionEvictionInterceptor.class); long size = interceptor.getCurrentSize(); log.debugf("Exception eviction size for cache: %s is: %d", cache.getCacheManager().getAddress(), size); expectedCount += interceptor.getMinSize(); boolean equal = expectedCount == size; if (!equal) { log.fatal("Expected: " + expectedCount + " but was: " + size + " for: " + cache.getCacheManager().getAddress()); } return equal; }); } } public void testExceptionOnInsert() { for (int i = 0; i < SIZE; ++i) { cache(0).put(i, i); } try { cache(0).put(-1, -1); fail("Should have thrown an exception!"); } catch (Throwable t) { Exceptions.assertException(ContainerFullException.class, getMostNestedSuppressedThrowable(t)); } } public void testExceptionOnInsertFunctional() { for (int i = 0; i < SIZE; ++i) { cache(0).computeIfAbsent(i, k -> SIZE); } try { cache(0).computeIfAbsent(-1, k -> SIZE); fail("Should have thrown an exception!"); } catch (Throwable t) { Exceptions.assertException(ContainerFullException.class, getMostNestedSuppressedThrowable(t)); } } public void testExceptionOnInsertWithRemove() { for (int i = 0; i < SIZE; ++i) { cache(0).put(i, i); } // Now we should have an extra space cache(0).remove(0); // Have to use a cached Integer value otherwise this will blosw up as too large cache(0).put(-128, -128); try { cache(0).put(-1, -1); fail("Should have thrown an exception!"); } catch (Throwable t) { Exceptions.assertException(ContainerFullException.class, getMostNestedSuppressedThrowable(t)); } } public void testNoExceptionWhenReplacingEntry() { for (int i = 0; i < SIZE; ++i) { cache(0).put(i, i); } // This should pass just fine cache(0).put(0, 0); } public void testNoExceptionAfterRollback() throws SystemException, NotSupportedException { // We only inserted 9 for (int i = 1; i < SIZE; ++i) { cache(0).put(i, i); } assertInterceptorCount(); TransactionManager tm = cache(0).getAdvancedCache().getTransactionManager(); tm.begin(); cache(0).put(0, 0); tm.rollback(); assertInterceptorCount(); assertNull(cache(0).get(0)); cache(0).put(SIZE + 1, SIZE + 1); assertInterceptorCount(); // This should fail now try { cache(0).put(-1, -1); fail("Should have thrown an exception!"); } catch (Throwable t) { Exceptions.assertException(ContainerFullException.class, getMostNestedSuppressedThrowable(t)); } assertInterceptorCount(); } /** * This test verifies that an insert would have caused an exception, but because the user rolled back it wasn't * an issue * @throws SystemException * @throws NotSupportedException */ public void testRollbackPreventedException() throws SystemException, NotSupportedException { // Insert all 10 for (int i = 0; i < SIZE; ++i) { cache(0).put(i, i); } TransactionManager tm = cache(0).getAdvancedCache().getTransactionManager(); tm.begin(); try { cache(0).put(SIZE + 1, SIZE + 1); } finally { tm.rollback(); } assertNull(cache(0).get(SIZE + 1)); } /** * This test verifies that if there are multiple entries that would cause an overflow to occur. Only one entry * would not cause an overflow, so this is specifically for when there is more than 1. * @throws SystemException * @throws NotSupportedException * @throws HeuristicRollbackException * @throws HeuristicMixedException */ public void testExceptionWithCommitMultipleEntries() throws SystemException, NotSupportedException, HeuristicRollbackException, HeuristicMixedException { // We only inserted 9 for (int i = 1; i < SIZE; ++i) { cache(0).put(i, i); } TransactionManager tm = cache(0).getAdvancedCache().getTransactionManager(); tm.begin(); try { cache(0).put(0, 0); cache(0).put(SIZE + 1, SIZE + 1); } catch (Throwable t) { tm.setRollbackOnly(); throw t; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) { try { tm.commit(); fail("Should have thrown an exception!"); } catch (RollbackException e) { Exceptions.assertException(ContainerFullException.class, getMostNestedSuppressedThrowable(e)); } } else { tm.rollback(); fail("Transaction was no longer active!"); } } } @DataProvider(name = "expiration") public Object[][] expirationParams() { return new Object[][] { { true, true }, { true, false }, { false, true }, { false, false } }; } @Test(dataProvider = "expiration") public void testEntryExpirationOverwritten(boolean maxIdle, boolean readInTx) throws Exception { Object expiringKey = 0; if (maxIdle) { cache(0).put(expiringKey, 0, -1, null, 10, TimeUnit.SECONDS); } else { cache(0).put(expiringKey, 0, 10, TimeUnit.SECONDS); } // Note that i starts at 1 so this adds SIZE - 1 entries for (int i = 1; i < SIZE; ++i) { cache(0).put(i, i); } timeService.advance(TimeUnit.SECONDS.toMillis(11)); if (readInTx) { TestingUtil.withTx(cache(0).getAdvancedCache().getTransactionManager(), () -> { // This should eventually expire all entries assertNull(cache(0).get(expiringKey)); return null; }); } else { // Make sure that it is updated outside of tx as well assertNull(cache(0).get(expiringKey)); } // We overwrite the existing key - which should work cache(0).put(expiringKey, 0); // This should fail now as we are back to full again try { cache(0).put(-1, -1); fail("Should have thrown an exception!"); } catch (Throwable t) { Exceptions.assertException(ContainerFullException.class, getMostNestedSuppressedThrowable(t)); } } /** * This tests to verify that when an entry is expired and removed from the data container that it properly updates * the current count */ @Test(dataProvider = "expiration") public void testEntryExpiration(boolean maxIdle, boolean readInTx) throws Exception { Object expiringKey = 0; if (maxIdle) { cache(0).put(expiringKey, 0, -1, null, 10, TimeUnit.SECONDS); } else { cache(0).put(expiringKey, 0, 10, TimeUnit.SECONDS); } // Note that i starts at 1 so this adds SIZE - 1 entries for (int i = 1; i < SIZE; ++i) { cache(0).put(i, i); } timeService.advance(TimeUnit.SECONDS.toMillis(11)); if (readInTx) { TestingUtil.withTx(cache(0).getAdvancedCache().getTransactionManager(), () -> { // This should eventually expire all entries assertNull(cache(0).get(expiringKey)); return null; }); } else { // Make sure that it is updated outside of tx as well assertNull(cache(0).get(expiringKey)); } // Manually triggering batch expiration is no longer required, but it helps reproduce ISPN-12971 for (Cache cache : caches()) { ExpirationManager<?, ?> em = cache.getAdvancedCache().getExpirationManager(); em.processExpiration(); } Object storageKey = cache(0).getAdvancedCache().getKeyDataConversion().toStorage(expiringKey); // Entry should be completely removed at some point - note that expired entries, that haven't been removed, still // count against counts for (Cache cache : caches()) { eventually(() -> cache.getAdvancedCache().getDataContainer().peek(storageKey) == null); } // This insert should work now cache(0).put(-128, -128); // This should fail now try { cache(0).put(-1, -1); fail("Should have thrown an exception!"); } catch (Throwable t) { Exceptions.assertException(ContainerFullException.class, getMostNestedSuppressedThrowable(t)); } } public void testDistributedOverflowOnPrimary() { testDistributedOverflow(true); } public void testDistributedOverflowOnBackup() { testDistributedOverflow(false); } void testDistributedOverflow(boolean onPrimary) { if (!cacheMode.isDistributed() || nodeCount < 3) { // Ignore the test if it isn't distributed and doesn't have at least 3 nodes return; } // Now we add 2 more nodes which means we have 5 nodes and 3 owners addClusterEnabledCacheManager(configurationBuilder); addClusterEnabledCacheManager(configurationBuilder); try { waitForClusterToForm(); LocalizedCacheTopology lct = cache(0).getAdvancedCache().getDistributionManager().getCacheTopology(); DataConversion dc = cache(0).getAdvancedCache().getKeyDataConversion(); // use positive numbers as protobuf encodes negative numbers as 10-bytes long int minKey = 1; int nextKey = minKey; Address targetNode; Iterator<Address> owners = lct.getWriteOwners(dc.toStorage(nextKey)).iterator(); if (onPrimary) { targetNode = owners.next(); } else { // Skip first one owners.next(); targetNode = owners.next(); } cache(0).put(nextKey, nextKey); // This will fill up the cache with entries that all map to owners for (int i = 0; i < SIZE - 1; ++i) { nextKey = getNextIntWithOwners(nextKey, lct, dc, targetNode, null); cache(0).put(nextKey, nextKey); } // We should have interceptor count equal to number of owners times how much storage takes up assertInterceptorCount(); for (Cache cache : caches()) { if (targetNode.equals(cache.getCacheManager().getAddress())) { assertEquals(10, cache.getAdvancedCache().getDataContainer().size()); break; } } nextKey = getNextIntWithOwners(nextKey, lct, dc, targetNode, onPrimary); try { cache(0).put(nextKey, nextKey); fail("Should have thrown an exception!"); } catch (Throwable t) { Exceptions.assertException(ContainerFullException.class, getMostNestedSuppressedThrowable(t)); } // Now that it partially failed it should have rolled back all the results assertInterceptorCount(); } finally { killMember(3); killMember(3); } } /** * * @param exclusiveValue * @param lct * @param dc * @param ownerAddress * @param primary * @return */ int getNextIntWithOwners(int exclusiveValue, LocalizedCacheTopology lct, DataConversion dc, Address ownerAddress, Boolean primary) { if (exclusiveValue < -128) { throw new IllegalArgumentException("We cannot support integers smaller than -128 as they will throw off BINARY sizing"); } int valueToTest = exclusiveValue; while (true) { valueToTest = valueToTest + 1; // Unfortunately we can't generate values higher than 128 if (valueToTest >= 128) { throw new IllegalStateException("Could not generate a key with the given owners"); } Object keyAsStorage = dc.toStorage(valueToTest); DistributionInfo di = lct.getDistribution(keyAsStorage); if (primary == null) { if (di.writeOwners().contains(ownerAddress)) { return valueToTest; } } else if (primary == Boolean.TRUE) { if (di.primary().equals(ownerAddress)) { return valueToTest; } } else { if (di.writeOwners().contains(ownerAddress)) { return valueToTest; } } } } /** * Test to make sure the counts are properly updated after adding and taking down nodes */ public void testInterceptorSizeCorrectWithStateTransfer() { // Test only works with REPL or DIST (latter only if numOwners > 1) if (!cacheMode.isClustered() || cacheMode.isDistributed() && nodeCount == 1) { return; } for (int i = 0; i < SIZE; ++i) { cache(0).put(i, i); } int numberToKill = 0; assertInterceptorCount(); try { addClusterEnabledCacheManager(configurationBuilder); waitForClusterToForm(); numberToKill++; assertInterceptorCount(); addClusterEnabledCacheManager(configurationBuilder); waitForClusterToForm(); numberToKill++; assertInterceptorCount(); killMember(nodeCount); numberToKill--; assertInterceptorCount(); killMember(nodeCount); numberToKill--; assertInterceptorCount(); } finally { for (int i = 0; i < numberToKill; ++i) { killMember(nodeCount); } } } }
26,091
37.769688
155
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/ManualEvictionWithPassivationAndConcurrentOperationsInPrimaryOwnerTest.java
package org.infinispan.eviction.impl; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Same as {@link ManualEvictionWithPassivationAndSizeBasedAndConcurrentOperationsInPrimaryOwnerTest} but with an * unbounded data container * * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "eviction.ManualEvictionWithPassivationAndConcurrentOperationsInPrimaryOwnerTest") public class ManualEvictionWithPassivationAndConcurrentOperationsInPrimaryOwnerTest extends ManualEvictionWithPassivationAndSizeBasedAndConcurrentOperationsInPrimaryOwnerTest { @Override protected void configureEviction(ConfigurationBuilder builder) { builder.memory().size(-1); } @Override public void testEvictionDuringRemove() { // Ignore this test as it requires size eviction } @Override public void testEvictionDuringWrite() { // Ignore this test as it requires size eviction } }
993
30.0625
122
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/MarshalledValuesManualEvictionTest.java
package org.infinispan.eviction.impl; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.data.CountMarshallingPojo; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "eviction.MarshalledValuesManualEvictionTest") public class MarshalledValuesManualEvictionTest extends SingleCacheManagerTest { public static final String POJO_NAME = MarshalledValuesManualEvictionTest.class.getName(); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.memory().storageType(StorageType.BINARY); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(TestDataSCI.INSTANCE, cfg); cache = cm.getCache(); return cm; } public void testManualEvictCustomKeyValue() { CountMarshallingPojo.reset(POJO_NAME); CountMarshallingPojo p1 = new CountMarshallingPojo(POJO_NAME, 64); CountMarshallingPojo p2 = new CountMarshallingPojo(POJO_NAME, 24); CountMarshallingPojo p3 = new CountMarshallingPojo(POJO_NAME, 97); CountMarshallingPojo p4 = new CountMarshallingPojo(POJO_NAME, 35); cache.put(p1, p2); // 2 writes, key & value cache.put(p3, p4); // 2 writes, key & value assertEquals(2, cache.size()); cache.evict(p1); // 1 write assertEquals(1, cache.size()); assertEquals(p4, cache.get(p3)); // 1 write, 1 read assertEquals(6, CountMarshallingPojo.getMarshallCount(POJO_NAME)); assertEquals(1, CountMarshallingPojo.getUnmarshallCount(POJO_NAME)); } public void testEvictPrimitiveKeyCustomValue() { CountMarshallingPojo.reset(POJO_NAME); CountMarshallingPojo p1 = new CountMarshallingPojo(POJO_NAME, 51); CountMarshallingPojo p2 = new CountMarshallingPojo(POJO_NAME, 78); cache.put("key-isoprene", p1); // 1 write cache.put("key-hexastyle", p2); // 1 write assertEquals(2, cache.size()); cache.evict("key-isoprene"); assertEquals(1, cache.size()); assertEquals(p2, cache.get("key-hexastyle")); // 1 read assertEquals(2, CountMarshallingPojo.getMarshallCount(POJO_NAME)); assertEquals(1, CountMarshallingPojo.getUnmarshallCount(POJO_NAME)); } }
2,594
41.540984
102
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/EvictionFunctionalTest.java
package org.infinispan.eviction.impl; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.context.Flag; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; import org.infinispan.notifications.cachelistener.event.CacheEntriesEvictedEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.ControlledTimeService; import org.infinispan.commons.time.TimeService; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "eviction.EvictionFunctionalTest") public class EvictionFunctionalTest extends SingleCacheManagerTest { private static final int CACHE_SIZE = 64; private StorageType storageType; private EvictionListener evictionListener; private ControlledTimeService timeService; protected EvictionFunctionalTest() { cleanup = CleanupPhase.AFTER_METHOD; } public EvictionFunctionalTest storageType(StorageType storageType) { this.storageType = storageType; return this; } public StorageType getStorageType() { return storageType; } @Factory public Object[] factory() { return new Object[]{ new EvictionFunctionalTest().storageType(StorageType.BINARY), new EvictionFunctionalTest().storageType(StorageType.OBJECT), new EvictionFunctionalTest().storageType(StorageType.OFF_HEAP) }; } @Override protected String parameters() { return "[" + storageType + "]"; } protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); builder.memory().size(CACHE_SIZE).storageType(getStorageType()) .expiration().wakeUpInterval(100L).locking() .useLockStriping(false) // to minimize chances of deadlock in the unit test .invocationBatching(); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(builder); cache = cm.getCache(); evictionListener = new EvictionListener(); cache.addListener(evictionListener); TestingUtil.replaceComponent(cm, TimeService.class, timeService = new ControlledTimeService(), true); return cm; } public void testSimpleEvictionMaxEntries() throws Exception { for (int i = 0; i < CACHE_SIZE * 2; i++) { cache.put("key-" + (i + 1), "value-" + (i + 1)); } assertEquals("cache size too big: " + cache.size(), CACHE_SIZE, cache.size()); assertEquals("eviction events count should be same with case size: " + evictionListener.getEvictedEvents(), CACHE_SIZE, evictionListener.getEvictedEvents().size()); for (int i = 0; i < CACHE_SIZE; i++) { cache.put("key-" + (i + 1), "value-" + (i + 1)); } assertEquals(CACHE_SIZE, cache.size()); // We don't know for sure how many will be evicted due to randomness, but we know they MUST evict // at least a size worth since we are writing more than double assertTrue(evictionListener.evictedEntries.size() > CACHE_SIZE); } public void testEvictNonExistantEntry() { String key = "key"; String value = "some-value"; cache.put(key, value); cache.evict(key); assertEquals(1, evictionListener.evictedEntries.size()); // Make sure if we evict again that it doesn't increase count cache.evict(key); // TODO: this seems like a bug, but many tests rely on this - maybe change later assertEquals(2, evictionListener.evictedEntries.size()); } public void testSimpleExpirationMaxIdle() throws Exception { for (int i = 0; i < CACHE_SIZE * 2; i++) { cache.put("key-" + (i + 1), "value-" + (i + 1), 1, TimeUnit.MILLISECONDS); } timeService.advance(1000); cache.getAdvancedCache().getExpirationManager().processExpiration(); assert 0 == cache.size() : "cache size should be zero: " + cache.size(); } public void testEvictionNotificationSkipped() { String key = "key"; String value = "value"; cache.put(key, value); cache.getAdvancedCache().withFlags(Flag.SKIP_LISTENER_NOTIFICATION).evict(key); assertEquals(0, evictionListener.getEvictedEvents().size()); } @Listener public static class EvictionListener { private List<Map.Entry> evictedEntries = Collections.synchronizedList(new ArrayList<>()); @CacheEntriesEvicted public void nodeEvicted(CacheEntriesEvictedEvent e) { assert e.isPre() || !e.isPre(); Object key = e.getEntries().keySet().iterator().next(); assert key != null; assert e.getCache() != null; assert e.getType() == Event.Type.CACHE_ENTRY_EVICTED; e.getEntries().entrySet().stream().forEach(entry -> evictedEntries.add((Map.Entry) entry)); } public List<Map.Entry> getEvictedEvents() { return evictedEntries; } } }
5,568
35.880795
113
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/ManualEvictionWithSizeBasedAndConcurrentOperationsInPrimaryOwnerTest.java
package org.infinispan.eviction.impl; import static org.infinispan.test.TestingUtil.extractComponent; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.CompletionStage; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.Cache; import org.infinispan.commands.write.EvictCommand; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.impl.AbstractDelegatingInternalDataContainer; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.context.InvocationContext; import org.infinispan.distribution.DistributionManager; import org.infinispan.interceptors.AsyncInterceptor; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.impl.CacheLoaderInterceptor; import org.infinispan.interceptors.impl.CacheWriterInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; import org.infinispan.notifications.cachelistener.event.CacheEntriesEvictedEvent; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.remoting.transport.Address; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.AssertJUnit; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Tests manual eviction with concurrent read and/or write operation. This test has passivation disabled and the * eviction happens in the primary owner * * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "eviction.ManualEvictionWithSizeBasedAndConcurrentOperationsInPrimaryOwnerTest", singleThreaded = true) public class ManualEvictionWithSizeBasedAndConcurrentOperationsInPrimaryOwnerTest extends EvictionWithConcurrentOperationsTest { protected EmbeddedCacheManager otherCacheManager; @AfterMethod(alwaysRun = true) public void stopSecondCacheManager() { if (otherCacheManager != null) { otherCacheManager.getCache().stop(); otherCacheManager.stop(); otherCacheManager = null; } } @BeforeMethod(alwaysRun = true) public void startSecondCacheManager() throws Exception { if (otherCacheManager == null) { otherCacheManager = createCacheManager(); } else { AssertJUnit.fail("Other cache manager should not be set!"); } Cache otherCache = otherCacheManager.getCache(); TestingUtil.waitForNoRebalance(cache, otherCache); } @Override public void testScenario1() throws Exception { final Object key1 = createSameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final AfterPassivationOrCacheWriter controller = new AfterPassivationOrCacheWriter().injectThis(cache); final Latch latch = new Latch(); controller.beforeEvict = () -> latch.blockIfNeeded(); //this will trigger the eviction of key1. key1 eviction will be blocked in the latch latch.enable(); Future<Void> evict = evictWithFuture(key1); latch.waitToBlock(30, TimeUnit.SECONDS); //the eviction was trigger and it blocked before passivation assertEquals("Wrong value for key " + key1 + " in get operation.", "v1", cache.get(key1)); //let the eviction continue and wait for put latch.disable(); evict.get(30, TimeUnit.SECONDS); assertNotInMemory(key1, "v1"); } @Override public void testScenario2() throws Exception { final Object key1 = createSameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final Latch latch = new Latch(); replaceControlledDataContainer(latch); //this will trigger the eviction of key1. key1 eviction will be blocked in the latch latch.enable(); Future<Void> evict = evictWithFuture(key1); latch.waitToBlock(30, TimeUnit.SECONDS); //the eviction was trigger and it blocked before passivation assertEquals("Wrong value for key " + key1 + " in get operation.", "v1", cache.get(key1)); //let the eviction continue and wait for put latch.disable(); evict.get(30, TimeUnit.SECONDS); assertNotInMemory(key1, "v1"); } @Override public void testScenario3() throws Exception { final Object key1 = createSameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final Latch latch = new Latch(); final SyncEvictionListener evictionListener = new SyncEvictionListener() { @CacheEntriesEvicted @Override public void evicted(CacheEntriesEvictedEvent event) { if (event.getEntries().containsKey(key1)) { latch.blockIfNeeded(); } } }; cache.addListener(evictionListener); //this will trigger the eviction of key1. key1 eviction will be blocked in the latch latch.enable(); Future<Void> evict = evictWithFuture(key1); latch.waitToBlock(30, TimeUnit.SECONDS); if (passivation) { Future<Object> getFuture = fork(() -> cache.get(key1)); // Get will be blocked because eviction notification is not yet complete - which is holding orderer // CacheLoader requires acquiring orderer so it can update the data container properly TestingUtil.assertNotDone(getFuture); //let the eviction continue and wait for get to complete (which will put it back in memory) latch.disable(); evict.get(30, TimeUnit.SECONDS); assertEquals("v1", getFuture.get(10, TimeUnit.SECONDS)); assertInMemory(key1, "v1"); } else { //the eviction was triggered and the key is no longer in the map assertEquals("Wrong value for key " + key1 + " in get operation.", "v1", cache.get(key1)); //let the eviction continue and wait for put latch.disable(); evict.get(30, TimeUnit.SECONDS); assertInMemory(key1, "v1"); } } @Override public void testScenario4() throws Exception { final Object key1 = createSameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final Latch readLatch = new Latch(); final Latch writeLatch = new Latch(); final AtomicBoolean firstGet = new AtomicBoolean(false); final AfterEntryWrappingInterceptor afterEntryWrappingInterceptor = new AfterEntryWrappingInterceptor() .injectThis(cache); afterEntryWrappingInterceptor.beforeGet = () -> { if (firstGet.compareAndSet(false, true)) { readLatch.blockIfNeeded(); } }; final SyncEvictionListener evictionListener = new SyncEvictionListener() { @CacheEntriesEvicted @Override public void evicted(CacheEntriesEvictedEvent event) { if (event.getEntries().containsKey(key1)) { writeLatch.blockIfNeeded(); } } }; cache.addListener(evictionListener); //this will trigger the eviction of key1. key1 eviction will be blocked in the latch readLatch.enable(); Future<Void> evict = evictWithFuture(key1); writeLatch.waitToBlock(30, TimeUnit.SECONDS); //the eviction was trigger and the key is no longer in the map Future<Object> get = fork(() -> cache.get(key1)); readLatch.waitToBlock(30, TimeUnit.SECONDS); //the first read is blocked. it has check the data container and it didn't found any value //this second get should not block anywhere and it should fetch the value from persistence assertEquals("Wrong value for key " + key1 + " in get operation.", "v1", cache.get(key1)); //let the eviction continue and wait for put writeLatch.disable(); evict.get(30, TimeUnit.SECONDS); //let the second get continue readLatch.disable(); assertEquals("Wrong value for key " + key1 + " in get operation.", "v1", get.get(30, TimeUnit.SECONDS)); assertInMemory(key1, "v1"); } @Override public void testScenario5() throws Exception { final Object key1 = createSameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final Latch readLatch = new Latch(); final Latch writeLatch = new Latch(); final AfterEntryWrappingInterceptor afterEntryWrappingInterceptor = new AfterEntryWrappingInterceptor() .injectThis(cache); afterEntryWrappingInterceptor.beforeGet = () -> readLatch.blockIfNeeded(); final SyncEvictionListener evictionListener = new SyncEvictionListener() { @CacheEntriesEvicted @Override public void evicted(CacheEntriesEvictedEvent event) { if (event.getEntries().containsKey(key1)) { writeLatch.blockIfNeeded(); } } }; cache.addListener(evictionListener); //this will trigger the eviction of key1. key1 eviction will be blocked in the latch readLatch.enable(); Future<Void> evict = evictWithFuture(key1); writeLatch.waitToBlock(30, TimeUnit.SECONDS); //the eviction was trigger and the key is no longer in the map Future<Object> get = fork(() -> cache.get(key1)); readLatch.waitToBlock(30, TimeUnit.SECONDS); //let the eviction continue writeLatch.disable(); //the first read is blocked. it has check the data container and it didn't found any value //this second get should not block anywhere and it should fetch the value from persistence assertEquals("Wrong value for key " + key1 + " in put operation.", "v1", cache.put(key1, "v3")); evict.get(30, TimeUnit.SECONDS); //let the get continue readLatch.disable(); assertEquals("Wrong value for key " + key1 + " in get operation.", "v3", get.get(30, TimeUnit.SECONDS)); assertInMemory(key1, "v3"); } @Override public void testScenario6() throws Exception { final Object key1 = createSameHashCodeKey("key1"); initializeKeyAndCheckData(key1, "v1"); final Latch readLatch = new Latch(); final Latch writeLatch = new Latch(); final Latch writeLatch2 = new Latch(); final AfterEntryWrappingInterceptor afterEntryWrappingInterceptor = new AfterEntryWrappingInterceptor() .injectThis(cache); afterEntryWrappingInterceptor.beforeGet = () -> readLatch.blockIfNeeded(); afterEntryWrappingInterceptor.afterPut = () -> writeLatch2.blockIfNeeded(); final SyncEvictionListener evictionListener = new SyncEvictionListener() { @CacheEntriesEvicted @Override public void evicted(CacheEntriesEvictedEvent event) { if (event.getEntries().containsKey(key1)) { writeLatch.blockIfNeeded(); } } }; cache.addListener(evictionListener); //this will trigger the eviction of key1. key1 eviction will be blocked in the latch readLatch.enable(); Future<Void> evict = evictWithFuture(key1); writeLatch.waitToBlock(30, TimeUnit.SECONDS); //the eviction was trigger and the key is no longer in the map Future<Object> get = fork(() -> cache.get(key1)); readLatch.waitToBlock(30, TimeUnit.SECONDS); //let the eviction continue writeLatch.disable(); Future<Object> put2 = fork(() -> cache.put(key1, "v3")); evict.get(30, TimeUnit.SECONDS); //wait until the 2nd put writes to persistence writeLatch2.waitToBlock(30, TimeUnit.SECONDS); //let the get continue readLatch.disable(); assertPossibleValues(key1, get.get(30, TimeUnit.SECONDS), "v1", "v3"); writeLatch2.disable(); assertEquals("Wrong value for key " + key1 + " in get operation.", "v1", put2.get(30, TimeUnit.SECONDS)); assertInMemory(key1, "v3"); } @Override protected void configurePersistence(ConfigurationBuilder builder) { builder.persistence().passivation(false).addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(storeName + storeNamePrefix.getAndIncrement()); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(false); builder.clustering().cacheMode(CacheMode.DIST_SYNC) .hash().numOwners(2).numSegments(2); configurePersistence(builder); configureEviction(builder); return TestCacheManagerFactory.createClusteredCacheManager(new EvictionWithConcurrentOperationsSCIImpl(), builder); } protected Object createSameHashCodeKey(String name) { final Address address = cache.getAdvancedCache().getRpcManager().getAddress(); DistributionManager distributionManager = cache.getAdvancedCache().getDistributionManager(); int hashCode = 0; SameHashCodeKey key = new SameHashCodeKey(name, hashCode); while (!distributionManager.getCacheTopology().getDistribution(key).primary().equals(address)) { hashCode++; key = new SameHashCodeKey(name, hashCode); } return key; } protected final Future<Void> evictWithFuture(final Object key) { return fork(() -> { cache.evict(key); return null; }); } private void replaceControlledDataContainer(final Latch latch) { InternalDataContainer current = TestingUtil.extractComponent(cache, InternalDataContainer.class); //noinspection unchecked InternalDataContainer controlledDataContainer = new AbstractDelegatingInternalDataContainer() { @Override protected InternalDataContainer delegate() { return current; } @Override public void evict(Object key) { latch.blockIfNeeded(); super.evict(key); } @Override public CompletionStage<Void> evict(int segment, Object key) { latch.blockIfNeeded(); return super.evict(segment, key); } }; TestingUtil.replaceComponent(cache, InternalDataContainer.class, controlledDataContainer, true); } class AfterPassivationOrCacheWriter extends ControlledCommandInterceptor { volatile Runnable beforeEvict; volatile Runnable afterEvict; public AfterPassivationOrCacheWriter injectThis(Cache<Object, Object> injectInCache) { AsyncInterceptorChain chain = extractComponent(injectInCache, AsyncInterceptorChain.class); AsyncInterceptor interceptor = chain.findInterceptorExtending(CacheWriterInterceptor.class); if (interceptor == null) { interceptor = chain.findInterceptorExtending(CacheLoaderInterceptor.class); } if (interceptor == null) { throw new IllegalStateException("Should not happen!"); } chain.addInterceptorAfter(this, interceptor.getClass()); return this; } @Override public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable { return handle(ctx, command, beforeEvict, afterEvict); } } }
15,476
38.482143
143
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/EvictionWithPassivationAndConcurrentOperationsTest.java
package org.infinispan.eviction.impl; import static java.util.concurrent.TimeUnit.SECONDS; import static org.infinispan.test.TestingUtil.extractComponent; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotSame; import static org.testng.AssertJUnit.assertSame; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.manager.PassivationPersistenceManager; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.test.TestingUtil; import org.infinispan.util.concurrent.DataOperationOrderer; import org.testng.AssertJUnit; import org.testng.annotations.Test; /** * Tests size-based eviction with concurrent read and/or write operation with passivation enabled. * * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "eviction.EvictionWithPassivationAndConcurrentOperationsTest") public class EvictionWithPassivationAndConcurrentOperationsTest extends EvictionWithConcurrentOperationsTest { { passivation = true; } @Override public void testEvictionDuringWrite() throws InterruptedException, ExecutionException, TimeoutException { super.testEvictionDuringWrite(); // #1 evicted-key evicted from write of other-key // #2 other-key is evicted when evicted-key is retrieved as last step eventuallyEquals(2L, () -> extractComponent(cache, PassivationManager.class).getPassivations()); } @Override public void testEvictionDuringRemove() throws InterruptedException, ExecutionException, TimeoutException { super.testEvictionDuringRemove(); eventuallyEquals(0L, () -> extractComponent(cache, PassivationManager.class).getPassivations()); } // Cache store loads entry but before releasing orderer the entry is evicted. In this case the entry // should be passivated to ensure data is still around public void testEvictionDuringLoad() throws InterruptedException, ExecutionException, TimeoutException { String key = "evicted-key"; cache.put(key, "loaded"); // Ensures the key is in the store - note this is one passivation cache.evict(key); testEvictionDuring(key, () -> cache.get(key), AssertJUnit::assertNotNull, AssertJUnit::assertNotNull, true); // #1 evict above // #2 evicted-key evicted from write of other-key // #3 other-key is evicted when evicted-key is retrieved as last step eventuallyEquals(3L, () -> extractComponent(cache, PassivationManager.class).getPassivations()); } public void testEvictionDuringWriteWithConcurrentRead() throws TimeoutException, InterruptedException, ExecutionException { String key = "evicted-key"; String value = "value"; // Simulate a write orderer operation to acquire the write orderer for evicted-key // Holding the orderer blocks prevents another passivation or activation of the same key DataOperationOrderer orderer = extractComponent(cache, DataOperationOrderer.class); CompletableFuture<DataOperationOrderer.Operation> delayFuture1 = acquireOrderer(orderer, key, null); log.tracef("delayFuture1=%s", delayFuture1.toString()); // Put the key which will wait on releasing the orderer at the end Future<Object> putEvictedKeyFuture = fork(() -> cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD) .put(key, value)); // Confirm the entry has been inserted in the data container so we can evict eventually(() -> orderer.getCurrentStage(key) != delayFuture1); CompletionStage<DataOperationOrderer.Operation> putEvictedKeyActivationStage = orderer.getCurrentStage(key); // Acquire the write orderer for evicted-key again after put(evicted-key) releases it CompletableFuture<DataOperationOrderer.Operation> delayFuture2 = acquireOrderer(orderer, key, putEvictedKeyActivationStage); log.tracef("delayFuture2=%s", delayFuture2.toString()); // Let put(evicted-key) acquire the orderer and activate evicted-key orderer.completeOperation(key, delayFuture1, DataOperationOrderer.Operation.READ); putEvictedKeyFuture.get(10, SECONDS); assertTrue(putEvictedKeyActivationStage.toCompletableFuture().isDone()); // delayFuture2 blocks the eviction of evicted-key, but it does not prevent put(other-key) from finishing cache.put("other-key", "other-value"); CompletionStage<DataOperationOrderer.Operation> putOtherKeyPassivationStage = orderer.getCurrentStage(key); assertNotSame(delayFuture2, putOtherKeyPassivationStage); // Acquire the write orderer for evicted-key again after put(other-key) releases it CompletableFuture<DataOperationOrderer.Operation> delayFuture3 = acquireOrderer(orderer, key, putOtherKeyPassivationStage); log.tracef("delayFuture3=%s", delayFuture3.toString()); // delayFuture2 is still holding evicted-key's orderer // Start get(evicted-key); it cannot complete yet, but it does register a new orderer stage Future<Object> getFuture = fork(() -> cache.get(key)); eventually(() -> orderer.getCurrentStage(key) != putOtherKeyPassivationStage); CompletionStage<DataOperationOrderer.Operation> getEvictedKeyActivationStage = orderer.getCurrentStage(key); assertFalse(getFuture.isDone()); // Complete delayFuture2 to release the orderer, it will be acquired by put(other-key) orderer.completeOperation(key, delayFuture2, putEvictedKeyActivationStage.toCompletableFuture().join()); // get(evicted-key) can't finish yet because of delayFuture3 TestingUtil.assertNotDone(getFuture); // Let get(evicted-key) acquire the orderer and finish the activation orderer.completeOperation(key, delayFuture3, putOtherKeyPassivationStage.toCompletableFuture().join()); assertEquals(value, getFuture.get(10, SECONDS)); // Wait for the activation to finish eventuallyEquals(null, () -> orderer.getCurrentStage(key)); assertTrue(getEvictedKeyActivationStage.toCompletableFuture().isDone()); // #1 evicted-key evicted by other-key from write // #2 other-key evicted by evicted-key from the get assertEquals(2L, extractComponent(cache, PassivationManager.class).getPassivations()); // #1 evicted key activated from the get assertEquals(1L, extractComponent(cache, ActivationManager.class).getActivationCount()); assertEquals(0L, extractComponent(cache, ActivationManager.class).getPendingActivationCount()); } private CompletableFuture<DataOperationOrderer.Operation> acquireOrderer(DataOperationOrderer orderer, String key, CompletionStage<DataOperationOrderer.Operation> oldFuture) { CompletableFuture<DataOperationOrderer.Operation> newFuture = new CompletableFuture<>(); CompletionStage<DataOperationOrderer.Operation> currentFuture = orderer.orderOn(key, newFuture); assertSame(currentFuture, oldFuture); if (currentFuture != null) { assertFalse(currentFuture.toCompletableFuture().isDone()); } return newFuture; } // This test differs from testEvictionDuringWrite in that it simulates an eviction and acquires the // caffeine lock, but is unable to acquire the orderer as it is already taken by a write operation. In this case // the eviction has removed the entry and the write puts it back - however the passivation should be skipped public void testWriteDuringEviction() throws Exception { String key = "evicted-key"; String initialValue = "value"; cache.put(key, initialValue); // Use delayFuture1 to stop eviction from acquiring the orderer // It blocks eviction from acquiring orderer - but has entry lock DataOperationOrderer orderer = extractComponent(cache, DataOperationOrderer.class); CompletableFuture<DataOperationOrderer.Operation> delayFuture1 = acquireOrderer(orderer, key, null); log.tracef("delayFuture1=%s", delayFuture1.toString()); // This will be stuck evicting the key until it can get the orderer Future<Object> putFuture = fork(() -> cache.put("other-key", "other-value")); eventually(() -> orderer.getCurrentStage(key) != delayFuture1); CompletionStage<DataOperationOrderer.Operation> putOtherKeyPassivationStage = orderer.getCurrentStage(key); String newValue = "value-2"; Future<Object> evictedKeyPutFuture = fork(() -> cache.put(key, newValue)); // Should be blocked waiting on Caffeine lock - but has the orderer TestingUtil.assertNotDone(evictedKeyPutFuture); assertFalse(putOtherKeyPassivationStage.toCompletableFuture().isDone()); // Let the eviction finish, which will let the put happen orderer.completeOperation(key, delayFuture1, DataOperationOrderer.Operation.READ); putFuture.get(10, SECONDS); assertEquals(initialValue, evictedKeyPutFuture.get(10, SECONDS)); assertInMemory(key, newValue); PassivationPersistenceManager ppm = (PassivationPersistenceManager) extractComponent(cache, PersistenceManager.class); eventuallyEquals(0, ppm::pendingPassivations); assertEquals(2L, extractComponent(cache, PassivationManager.class).getPassivations()); } @Override protected void configurePersistence(ConfigurationBuilder builder) { // Enable stats so we can count passivations builder.statistics().enable(); builder.persistence().passivation(true) .addStore(DummyInMemoryStoreConfigurationBuilder.class); } }
10,131
50.431472
136
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/ManualEvictionWithSizeBasedAndConcurrentOperationsInBackupOwnerTest.java
package org.infinispan.eviction.impl; import org.infinispan.Cache; import org.infinispan.distribution.DistributionManager; import org.infinispan.remoting.transport.Address; import org.testng.annotations.Test; /** * Tests manual eviction with concurrent read and/or write operation. This test has passivation disabled and the * eviction happens in the backup owner * * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "eviction.ManualEvictionWithSizeBasedAndConcurrentOperationsInBackupOwnerTest", singleThreaded = true) public class ManualEvictionWithSizeBasedAndConcurrentOperationsInBackupOwnerTest extends ManualEvictionWithSizeBasedAndConcurrentOperationsInPrimaryOwnerTest { @Override protected Object createSameHashCodeKey(String name) { final Cache otherCache = otherCacheManager.getCache(); final Address address = otherCache.getAdvancedCache().getRpcManager().getAddress(); DistributionManager distributionManager = otherCache.getAdvancedCache().getDistributionManager(); int hashCode = 0; SameHashCodeKey key = new SameHashCodeKey(name, hashCode); while (!distributionManager.getCacheTopology().getDistribution(key).primary().equals(address)) { hashCode++; key = new SameHashCodeKey(name, hashCode); } return key; } }
1,345
39.787879
142
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/ExpensiveEvictionTest.java
package org.infinispan.eviction.impl; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @author Sanne Grinovero &lt;sanne@infinispan.org&gt; (C) 2011 Red Hat Inc. */ @Test(groups = "profiling", testName = "eviction.ExpensiveEvictionTest") public class ExpensiveEvictionTest extends SingleCacheManagerTest { private final Integer MAX_CACHE_ELEMENTS = 10 * 1000 * 1000; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.memory().size(MAX_CACHE_ELEMENTS) .expiration().wakeUpInterval(3000L) .build(); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(cfg); cache = cm.getCache(); return cm; } public void testSimpleEvictionMaxEntries() throws Exception { log.tracef("Max entries: ", MAX_CACHE_ELEMENTS); for (int i = 0; i < MAX_CACHE_ELEMENTS; i++) { Integer integer = Integer.valueOf(i); cache.put(integer, integer, 6, TimeUnit.HOURS); if (i % 50000 == 0) { log.tracef("Elements in cache: %s", cache.size()); } } log.debug("Finished filling in cache. Now idle while evicting thread works...."); Thread.sleep(TimeUnit.MILLISECONDS.convert(2, TimeUnit.HOURS)); } }
1,576
34.840909
87
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/DeadlockClusteredCachesTest.java
package org.infinispan.eviction.impl; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.ControlledTimeService; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "stress", testName = "eviction.DeadlockClusteredCachesTest", timeOut = 1*60*1000) public class DeadlockClusteredCachesTest extends SingleCacheManagerTest { protected ControlledTimeService timeService = new ControlledTimeService(); protected int maxEntries; @Factory public Object[] factory() { int max = 10; Object[] data = new Object[max]; for (int i = 0; i < max; i++) { data[i] = new DeadlockClusteredCachesTest().maxEntries(100 * (i + 1)); } return data; } protected DeadlockClusteredCachesTest maxEntries(int maxEntries) { this.maxEntries = maxEntries; return this; } @Override protected String parameters() { return "[" + maxEntries + "]"; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfgBuilder = new ConfigurationBuilder(); cfgBuilder.clustering().cacheMode(CacheMode.DIST_SYNC); cfgBuilder.expiration().disableReaper(); EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(cfgBuilder); cache = cm.getCache(); return cm; } public void testDeadlockReaper() throws InterruptedException { for (int i = 0; i < maxEntries; i++) { cache.put("key-" + (i + 1), "value-" + (i + 1), -1, TimeUnit.MILLISECONDS, 1, TimeUnit.MILLISECONDS); } timeService.advance(1000); Thread t1 = new Thread(() -> { cache.getAdvancedCache().getExpirationManager().processExpiration(); }); Thread t2 = new Thread(() -> { for (int i = 0; i < maxEntries; i++) { cache.get("key-" + (i + 1)); } }); t1.start(); t2.start(); t1.join(); t2.join(); } }
2,261
31.314286
110
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/ManualEvictionWithConcurrentOperationsInBackupOwnerTest.java
package org.infinispan.eviction.impl; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Same as {@link ManualEvictionWithSizeBasedAndConcurrentOperationsInBackupOwnerTest} but with an unbounded data * container * * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "eviction.ManualEvictionWithConcurrentOperationsInBackupOwnerTest", singleThreaded = true) public class ManualEvictionWithConcurrentOperationsInBackupOwnerTest extends ManualEvictionWithSizeBasedAndConcurrentOperationsInBackupOwnerTest { @Override protected void configureEviction(ConfigurationBuilder builder) { builder.memory().size(-1); } @Override public void testEvictionDuringRemove() { // Ignore this test as it requires size eviction } @Override public void testEvictionDuringWrite() { // Ignore this test as it requires size eviction } }
956
28.90625
130
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/ManualEvictionWithPassivationAndConcurrentOperationsInBackupOwnerTest.java
package org.infinispan.eviction.impl; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Same as {@link ManualEvictionWithPassivationAndSizeBasedAndConcurrentOperationsInBackupOwnerTest} but with an * unbounded data container * * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "eviction.ManualEvictionWithPassivationAndConcurrentOperationsInBackupOwnerTest", singleThreaded = true) public class ManualEvictionWithPassivationAndConcurrentOperationsInBackupOwnerTest extends ManualEvictionWithPassivationAndSizeBasedAndConcurrentOperationsInBackupOwnerTest { { passivation = true; } @Override protected void configureEviction(ConfigurationBuilder builder) { builder.memory().size(-1); } @Override public void testEvictionDuringRemove() { // Ignore this test as it requires size eviction } @Override public void testEvictionDuringWrite() { // Ignore this test as it requires size eviction } }
1,048
28.971429
144
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/MemoryBasedEvictionFunctionalStoreAsBinaryTest.java
package org.infinispan.eviction.impl; import static org.testng.AssertJUnit.assertTrue; import java.util.Random; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.test.data.Key; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "eviction.MemoryBasedEvictionFunctionalStoreAsBinaryTest") public class MemoryBasedEvictionFunctionalStoreAsBinaryTest extends MemoryBasedEvictionFunctionalTest { @Override protected void configure(ConfigurationBuilder cb) { super.configure(cb); cb.memory().storageType(storageType); } @Factory public Object[] factory() { return new Object[]{ new MemoryBasedEvictionFunctionalStoreAsBinaryTest().storageType(StorageType.BINARY), }; } public void testCustomClass() throws Exception { long numberInserted = CACHE_SIZE / 10; Random random = new Random(); // Note that there is overhead for the map itself, so we will not get exactly the same amount // More than likely there will be a few hundred byte overhead for (float i = 0; i < numberInserted; i++) { cache.put(new Key(randomStringFullOfInt(random, 10)), new Key(randomStringFullOfInt(random, 10))); } assertTrue(cache.getAdvancedCache().getDataContainer().size() < numberInserted); } }
1,458
34.585366
103
java
null
infinispan-main/core/src/test/java/org/infinispan/eviction/impl/protostream/PrimitiveArrayCtx.java
package org.infinispan.eviction.impl.protostream; import static org.infinispan.protostream.FileDescriptorSource.fromString; import java.io.IOException; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; import org.infinispan.protostream.MessageMarshaller; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; /** * Adds support for primitive and primitive wrapper arrays. */ public class PrimitiveArrayCtx implements SerializationContextInitializer { static class PrimitiveArrayMarshaller implements MessageMarshaller<Object> { private static final String FIELD_NAME = "element"; private final Class<?> primitiveType; public PrimitiveArrayMarshaller(Class<?> primitiveType) { this.primitiveType = primitiveType; } @Override public Object readFrom(ProtoStreamReader reader) throws IOException { switch (primitiveType.getSimpleName()) { case "Byte": Integer[] byteIntegers = reader.readArray(FIELD_NAME, Integer.class); Byte[] bytes = new Byte[byteIntegers.length]; for (int i = 0; i < byteIntegers.length; i++) { bytes[i] = byteIntegers[i].byteValue(); } return bytes; case "Short": Integer[] shortIntegers = reader.readArray(FIELD_NAME, Integer.class); Short[] shorts = new Short[shortIntegers.length]; for (int i = 0; i < shortIntegers.length; i++) { shorts[i] = shortIntegers[i].shortValue(); } return shorts; case "Integer": return reader.readArray(FIELD_NAME, Integer.class); case "Long": List<Long> longs = new ArrayList<>(); reader.readCollection(FIELD_NAME, longs, Long.class); return longs; case "Double": return reader.readArray(FIELD_NAME, Double.class); case "String": return reader.readArray(FIELD_NAME, String.class); case "byte": return reader.readBytes(FIELD_NAME); case "short": int[] ints = reader.readInts(FIELD_NAME); short[] array = new short[ints.length]; for (int i = 0; i < ints.length; i++) { array[i] = (short) ints[i]; } return array; case "int": return reader.readInts(FIELD_NAME); case "long": return reader.readLongs(FIELD_NAME); case "double": return reader.readDoubles(FIELD_NAME); default: throw new IllegalArgumentException("Array type " + primitiveType.getSimpleName() + " not supported"); } } @Override public void writeTo(ProtoStreamWriter writer, Object o) throws IOException { if (o instanceof Byte[]) { Byte[] bytes = (Byte[]) o; Integer[] integers = new Integer[bytes.length]; for (int i = 0; i < bytes.length; i++) { integers[i] = bytes[i].intValue(); } writer.writeArray(FIELD_NAME, integers, Integer.class); return; } if (o instanceof Short[]) { Short[] shorts = (Short[]) o; Integer[] integers = new Integer[shorts.length]; for (int i = 0; i < shorts.length; i++) { integers[i] = shorts[i].intValue(); } writer.writeArray(FIELD_NAME, integers, Integer.class); return; } if (o instanceof Integer[]) { writer.writeArray(FIELD_NAME, (Integer[]) o, Integer.class); return; } if (o instanceof Long[]) { writer.writeArray(FIELD_NAME, (Long[]) o, Long.class); return; } if (o instanceof Double[]) { writer.writeArray(FIELD_NAME, (Double[]) o, Double.class); return; } if (o instanceof String[]) { writer.writeArray(FIELD_NAME, (String[]) o, String.class); return; } if (o instanceof byte[]) { writer.writeBytes(FIELD_NAME, (byte[]) o); return; } if (o instanceof short[]) { short[] s = (short[]) o; int[] widened = new int[s.length]; for (int i = 0; i < s.length; i++) { widened[i] = s[i]; } writer.writeInts(FIELD_NAME, widened); return; } if (o instanceof int[]) { writer.writeInts(FIELD_NAME, (int[]) o); return; } if (o instanceof long[]) { writer.writeLongs(FIELD_NAME, (long[]) o); return; } if (o instanceof float[]) { writer.writeFloats(FIELD_NAME, (float[]) o); return; } if (o instanceof double[]) { writer.writeDoubles(FIELD_NAME, (double[]) o); return; } throw new IllegalArgumentException("Array type " + o.getClass() + " not supported"); } @Override public String getTypeName() { return primitiveType.getSimpleName(); } @Override public Class<?> getJavaClass() { switch (primitiveType.getSimpleName()) { case "byte": return byte[].class; case "short": return short[].class; case "int": return int[].class; case "long": return long[].class; case "float": return float[].class; case "double": return double[].class; case "Byte": return Byte[].class; case "Short": return Short[].class; case "Integer": return Integer[].class; case "Long": return Long[].class; case "Float": return Float[].class; case "Double": return Double[].class; case "String": return String[].class; default: throw new IllegalArgumentException("Type " + primitiveType + " not supported"); } } } @Override public String getProtoFileName() { return "array-primitives.proto"; } @Override public String getProtoFile() throws UncheckedIOException { return "message byte { repeated int64 element = 1;}" + "message Byte { repeated int32 element = 1;}" + "message short { repeated int32 element = 1;}" + "message Short { repeated int32 element = 1;}" + "message int { repeated int32 element = 1;}" + "message Integer { repeated int32 element = 1;}" + "message long { repeated int64 element = 1;}" + "message Long { repeated int64 element = 1;}" + "message double { repeated double element = 1;}" + "message Double { repeated double element = 1;}" + "message String { repeated string element = 1;}"; } @Override public void registerSchema(SerializationContext serCtx) { serCtx.registerProtoFiles(fromString(getProtoFileName(), getProtoFile())); } @Override public void registerMarshallers(SerializationContext serCtx) { serCtx.registerMarshaller(new PrimitiveArrayMarshaller(byte.class)); serCtx.registerMarshaller(new PrimitiveArrayMarshaller(Byte.class)); serCtx.registerMarshaller(new PrimitiveArrayMarshaller(short.class)); serCtx.registerMarshaller(new PrimitiveArrayMarshaller(Short.class)); serCtx.registerMarshaller(new PrimitiveArrayMarshaller(int.class)); serCtx.registerMarshaller(new PrimitiveArrayMarshaller(Integer.class)); serCtx.registerMarshaller(new PrimitiveArrayMarshaller(long.class)); serCtx.registerMarshaller(new PrimitiveArrayMarshaller(Long.class)); serCtx.registerMarshaller(new PrimitiveArrayMarshaller(double.class)); serCtx.registerMarshaller(new PrimitiveArrayMarshaller(Double.class)); serCtx.registerMarshaller(new PrimitiveArrayMarshaller(String.class)); } }
8,393
36.641256
116
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ClusterExpirationLifespanLoaderTest.java
package org.infinispan.expiration.impl; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.testng.annotations.Test; /** * Tests to make sure that when lifespan expiration occurs it occurs across the cluster even if a loader is in use * * @author William Burns * @since 8.0 */ @Test(groups = "functional", testName = "expiration.impl.ClusterExpirationLifespanLoaderTest") public class ClusterExpirationLifespanLoaderTest extends ClusterExpirationLifespanTest { @Override protected void createCluster(ConfigurationBuilder builder, int count) { builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); super.createCluster(builder, count); } @Override public Object[] factory() { return new Object[] { new ClusterExpirationLifespanLoaderTest().cacheMode(CacheMode.DIST_SYNC).transactional(true), new ClusterExpirationLifespanLoaderTest().cacheMode(CacheMode.DIST_SYNC).transactional(false), new ClusterExpirationLifespanLoaderTest().cacheMode(CacheMode.REPL_SYNC).transactional(true), new ClusterExpirationLifespanLoaderTest().cacheMode(CacheMode.REPL_SYNC).transactional(false), }; } }
1,359
41.5
114
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ExpirationStoreListenerFunctionalTest.java
package org.infinispan.expiration.impl; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.test.TestingUtil; import org.testng.annotations.AfterMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "expiration.impl.ExpirationStoreListenerFunctionalTest") public class ExpirationStoreListenerFunctionalTest extends ExpirationStoreFunctionalTest { protected ExpiredCacheListener listener = new ExpiredCacheListener(); @Factory @Override public Object[] factory() { return new Object[]{ // Test is for dummy store with a listener and we don't care about memory storage types new ExpirationStoreListenerFunctionalTest().cacheMode(CacheMode.LOCAL), }; } @Override protected String parameters() { return null; } @Override protected void afterCacheCreated(EmbeddedCacheManager cm) { cache.addListener(listener); } @AfterMethod public void resetListener() { listener.reset(); } @Override public void testSimpleExpirationLifespan() throws Exception { super.testSimpleExpirationLifespan(); processExpiration(); assertExpiredEvents(SIZE); } @Override public void testSimpleExpirationMaxIdle() throws Exception { for (int i = 0; i < SIZE; i++) { cache.put("key-" + i, "value-" + i, -1, null, 1, TimeUnit.MILLISECONDS); } timeService.advance(2); // We have to process expiration for store and max idle processExpiration(); assertEquals(0, cache.size()); assertExpiredEvents(SIZE); } public void testExpirationOfStoreWhenDataNotInMemory() throws Exception { String key = "k"; cache.put(key, "v", 10, TimeUnit.MILLISECONDS); removeFromContainer(key); // At this point data should only be in store - we assume size won't ressurect value into memory assertEquals(1, cache.size()); assertEquals(0, listener.getInvocationCount()); timeService.advance(11); assertNull(cache.get(key)); // Stores do not expire entries on load, thus we need to purge them processExpiration(); assertEquals(1, listener.getInvocationCount()); CacheEntryExpiredEvent event = listener.getEvents().iterator().next(); assertEquals(Event.Type.CACHE_ENTRY_EXPIRED, event.getType()); assertEquals(cache, event.getCache()); assertFalse(event.isPre()); assertNotNull(event.getKey()); assertEquals("v", event.getValue()); // Metadata only currently works with dummy in memory store if (TestingUtil.getFirstStore(cache) instanceof DummyInMemoryStore) { assertNotNull(event.getMetadata()); } } protected void removeFromContainer(String key) { cache.getAdvancedCache().getDataContainer().remove(key); } private void assertExpiredEvents(int count) { eventuallyEquals(count, () -> listener.getInvocationCount()); listener.getEvents().forEach(event -> { log.tracef("Checking event %s", event); assertEquals(Event.Type.CACHE_ENTRY_EXPIRED, event.getType()); assertEquals(cache, event.getCache()); assertFalse(event.isPre()); assertNotNull(event.getKey()); assertNotNull(event.getValue()); assertNotNull(event.getMetadata()); }); } }
3,895
34.418182
102
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/CustomLoaderNonNullWithExpirationTest.java
package org.infinispan.expiration.impl; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.commands.read.GetKeyValueCommand; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.ConfigurationFor; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.AbstractStoreConfiguration; import org.infinispan.configuration.cache.AbstractStoreConfigurationBuilder; import org.infinispan.configuration.cache.AsyncStoreConfiguration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; import org.infinispan.container.entries.NullCacheEntry; import org.infinispan.context.InvocationContext; import org.infinispan.interceptors.BaseCustomAsyncInterceptor; import org.infinispan.interceptors.impl.EntryWrappingInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.metadata.Metadata; import org.infinispan.persistence.dummy.Element; import org.infinispan.persistence.spi.CacheLoader; import org.infinispan.persistence.spi.InitializationContext; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.MarshallableEntryFactory; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.ControlledTimeService; import org.testng.annotations.Test; /** * Test to verify that a loader that always returns a non null value * @author wburns * @since 9.4 */ @Test(groups = "functional", testName = "expiration.impl.CustomLoaderNonNullWithExpirationTest") public class CustomLoaderNonNullWithExpirationTest extends SingleCacheManagerTest { private ControlledTimeService timeService = new ControlledTimeService(); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); builder.persistence().addStore(SimpleLoaderConfigurationBuilder.class) .segmented(false); // Effectively disabling reaper builder.expiration().wakeUpInterval(1, TimeUnit.DAYS); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(builder); TestingUtil.replaceComponent(cm, TimeService.class, timeService, true); cache = cm.getCache(); return cm; } @BuiltBy(SimpleLoaderConfigurationBuilder.class) @ConfigurationFor(SimpleLoader.class) public static class SimpleLoaderConfiguration extends AbstractStoreConfiguration<SimpleLoaderConfiguration> { public SimpleLoaderConfiguration(AttributeSet attributes, AsyncStoreConfiguration async) { super(Element.DUMMY_STORE, attributes, async); } } public static class SimpleLoaderConfigurationBuilder extends AbstractStoreConfigurationBuilder<SimpleLoaderConfiguration, SimpleLoaderConfigurationBuilder> { public SimpleLoaderConfigurationBuilder(PersistenceConfigurationBuilder builder) { super(builder, SimpleLoaderConfiguration.attributeDefinitionSet()); } @Override public SimpleLoaderConfiguration create() { return new SimpleLoaderConfiguration(attributes.protect(), async.create()); } @Override public SimpleLoaderConfigurationBuilder self() { return this; } } public static class SimpleLoader<K, V> implements CacheLoader<K, V> { static final String VALUE = "some-value"; private MarshallableEntryFactory<K, V> factory; private TimeService timeService; @Override public void init(InitializationContext ctx) { factory = ctx.getMarshallableEntryFactory(); timeService = ctx.getTimeService(); } @Override public MarshallableEntry<K, V> loadEntry(Object key) { Metadata metadata = new EmbeddedMetadata.Builder() .lifespan(1, TimeUnit.SECONDS).build(); long now = timeService.wallClockTime(); return factory.create(key, VALUE, metadata, null, now, now); } @Override public boolean contains(Object key) { return true; } @Override public void start() { } @Override public void stop() { } } public void testEntryExpired() { String key = "some-key"; Object value = cache.get(key); assertEquals(SimpleLoader.VALUE, value); // Should expire the in memory entry timeService.advance(TimeUnit.SECONDS.toMillis(2)); value = cache.get(key); assertEquals(SimpleLoader.VALUE, value); } public void testExpireAfterWrapping() { // Every time a get is invoked it increases time by 2 seconds - causing entry to expire cache.getAdvancedCache().getAsyncInterceptorChain().addInterceptorAfter(new BaseCustomAsyncInterceptor() { @Override public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { timeService.advance(TimeUnit.SECONDS.toMillis(2)); return super.visitGetKeyValueCommand(ctx, command); } }, EntryWrappingInterceptor.class); String key = "some-key"; Object value = cache.get(key); assertEquals(SimpleLoader.VALUE, value); value = cache.get(key); assertEquals(SimpleLoader.VALUE, value); } public void testConcurrentReadExpiration() throws InterruptedException, TimeoutException, BrokenBarrierException, ExecutionException { AtomicBoolean blockFirst = new AtomicBoolean(true); CyclicBarrier barrier = new CyclicBarrier(2); String key = "some-key"; // We block the first get attempt, which will have no entry in data container in EntryWrappingInterceptor // But after we unblock it, the data container will have an expired entry cache.getAdvancedCache().getAsyncInterceptorChain().addInterceptorAfter(new BaseCustomAsyncInterceptor() { @Override public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { if (blockFirst.getAndSet(false)) { assertEquals(NullCacheEntry.getInstance(), ctx.lookupEntry(key)); barrier.await(10, TimeUnit.SECONDS); barrier.await(10, TimeUnit.SECONDS); } return super.visitGetKeyValueCommand(ctx, command); } }, EntryWrappingInterceptor.class); // This method will block above Future<Void> future = fork(() -> assertEquals(SimpleLoader.VALUE, cache.get(key))); // Make sure forked thread is blocked after EntryWrappingInterceptor, but before CacheLoaderInterceptor barrier.await(10, TimeUnit.SECONDS); // Now we read the key which should load the value Object value = cache.get(key); assertEquals(SimpleLoader.VALUE, value); // This will cause it to expire timeService.advance(TimeUnit.SECONDS.toMillis(2)); // Finally let the fork complete - should be fine barrier.await(10, TimeUnit.SECONDS); future.get(10, TimeUnit.SECONDS); } }
7,677
37.39
160
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ExpirationThreadCountTest.java
package org.infinispan.expiration.impl; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.factories.threads.DefaultThreadFactory; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Tests eviction thread counts under several distinct circumstances. * * @author Galder Zamarreño * @since 4.2 */ @Test(groups = "functional", testName = "eviction.ExpirationThreadCountTest") public class ExpirationThreadCountTest extends SingleCacheManagerTest { private static String EXPIRATION_THREAD_NAME_PREFIX = ExpirationThreadCountTest.class.getSimpleName() + "-thread"; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder globalCfg = new GlobalConfigurationBuilder(); globalCfg.expirationThreadPool().threadFactory(new DefaultThreadFactory(null, 1, EXPIRATION_THREAD_NAME_PREFIX, null, null)); return TestCacheManagerFactory.createCacheManager(globalCfg, new ConfigurationBuilder()); } public void testDefineMultipleCachesWithExpiration() { for (int i = 0; i < 50; i++) { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg .expiration().wakeUpInterval(100L); String cacheName = Integer.toString(i); cacheManager.defineConfiguration(cacheName, cfg.build()); cacheManager.getCache(cacheName); } ThreadMXBean threadMBean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threadInfos = threadMBean.dumpAllThreads(false, false); String pattern = EXPIRATION_THREAD_NAME_PREFIX; int evictionThreadCount = 0; for (ThreadInfo threadInfo : threadInfos) { if (threadInfo.getThreadName().startsWith(pattern)) evictionThreadCount++; } assert evictionThreadCount == 1 : "Thread should only be one expiration thread with pattern '" + pattern + "', instead there were " + evictionThreadCount; } }
2,317
38.288136
131
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ClusterExpirationLifespanTest.java
package org.infinispan.expiration.impl; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.lang.invoke.MethodHandles; import java.util.Arrays; import java.util.Iterator; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Stream; import org.infinispan.Cache; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.triangle.BackupWriteCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.distribution.MagicKey; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.transaction.LockingMode; import org.infinispan.util.ControlledRpcManager; import org.infinispan.util.ControlledTimeService; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.SkipException; import org.testng.annotations.Test; /** * Tests to make sure that when lifespan expiration occurs it occurs across the cluster * * @author William Burns * @since 8.0 */ @Test(groups = "functional", testName = "expiration.impl.ClusterExpirationLifespanTest") public class ClusterExpirationLifespanTest extends MultipleCacheManagersTest { protected static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); protected ControlledTimeService ts0; protected ControlledTimeService ts1; protected ControlledTimeService ts2; protected Cache<Object, Object> cache0; protected Cache<Object, Object> cache1; protected Cache<Object, Object> cache2; protected ConfigurationBuilder configurationBuilder; @Override public Object[] factory() { return Arrays.stream(StorageType.values()) .flatMap(type -> Stream.builder() .add(new ClusterExpirationLifespanTest().storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC)) .add(new ClusterExpirationLifespanTest().storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.PESSIMISTIC)) .add(new ClusterExpirationLifespanTest().storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(false)) .add(new ClusterExpirationLifespanTest().storageType(type).cacheMode(CacheMode.REPL_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC)) .add(new ClusterExpirationLifespanTest().storageType(type).cacheMode(CacheMode.REPL_SYNC).transactional(true).lockingMode(LockingMode.PESSIMISTIC)) .add(new ClusterExpirationLifespanTest().storageType(type).cacheMode(CacheMode.REPL_SYNC).transactional(false)) .build() ).toArray(); } @Override protected void createCacheManagers() throws Throwable { configurationBuilder = new ConfigurationBuilder(); configurationBuilder.clustering().cacheMode(cacheMode); configurationBuilder.transaction().transactionMode(transactionMode()).lockingMode(lockingMode); configurationBuilder.expiration().disableReaper(); if (storageType != null) { configurationBuilder.memory().storage(storageType); } createCluster(TestDataSCI.INSTANCE, configurationBuilder, 3); waitForClusterToForm(); injectTimeServices(); cache0 = cache(0); cache1 = cache(1); cache2 = cache(2); } @Override protected GlobalConfigurationBuilder defaultGlobalConfigurationBuilder() { GlobalConfigurationBuilder globalConfigurationBuilder = super.defaultGlobalConfigurationBuilder(); globalConfigurationBuilder .serialization().marshaller(new JavaSerializationMarshaller()) .allowList().addClasses(ExpirationFunctionalTest.NoEquals.class, MagicKey.class); return globalConfigurationBuilder; } protected void injectTimeServices() { ts0 = new ControlledTimeService(); TestingUtil.replaceComponent(manager(0), TimeService.class, ts0, true); ts1 = new ControlledTimeService(); TestingUtil.replaceComponent(manager(1), TimeService.class, ts1, true); ts2 = new ControlledTimeService(); TestingUtil.replaceComponent(manager(2), TimeService.class, ts2, true); } public void testLifespanExpiredOnPrimaryOwner() throws Exception { testLifespanExpiredEntryRetrieval(cache0, cache1, ts0, true); } public void testLifespanExpiredOnBackupOwner() throws Exception { testLifespanExpiredEntryRetrieval(cache0, cache1, ts1, false); } private void testLifespanExpiredEntryRetrieval(Cache<Object, Object> primaryOwner, Cache<Object, Object> backupOwner, ControlledTimeService timeService, boolean expireOnPrimary) throws Exception { Object key = createKey(primaryOwner, backupOwner); primaryOwner.put(key, key.toString(), 10, TimeUnit.MILLISECONDS); assertEquals(key.toString(), primaryOwner.get(key)); assertEquals(key.toString(), backupOwner.get(key)); // Now we expire on cache0, it should still exist on cache1 // Note this has to be within the buffer in RemoveExpiredCommand (100 ms the time of this commit) timeService.advance(11); Cache<?, ?> expiredCache; Cache<?, ?> otherCache; if (expireOnPrimary) { expiredCache = primaryOwner; otherCache = backupOwner; } else { expiredCache = backupOwner; otherCache = primaryOwner; } assertEquals(key.toString(), otherCache.get(key)); // By calling get on an expired key it will remove it all over Object expiredValue = expiredCache.get(key); assertNull(expiredValue); // This should be expired on the other node soon - note expiration is done asynchronously on a get eventually(() -> !otherCache.containsKey(key), 10, TimeUnit.SECONDS); } private Object createKey(Cache<Object, ?> primaryOwner, Cache<Object, ?> backupOwner) { if (storageType == StorageType.OBJECT) { return new MagicKey(primaryOwner, backupOwner); } else { // BINARY and OFF heap can't use MagicKey as they are serialized LocalizedCacheTopology primaryLct = primaryOwner.getAdvancedCache().getDistributionManager().getCacheTopology(); LocalizedCacheTopology backupLct = backupOwner.getAdvancedCache().getDistributionManager().getCacheTopology(); ThreadLocalRandom tlr = ThreadLocalRandom.current(); int attempt = 0; while (true) { int key = tlr.nextInt(); // We test ownership based on the stored key instance Object wrappedKey = primaryOwner.getAdvancedCache().getKeyDataConversion().toStorage(key); if (primaryLct.getDistribution(wrappedKey).isPrimary() && backupLct.getDistribution(wrappedKey).isWriteBackup()) { log.tracef("Found key %s for primary owner %s and backup owner %s", wrappedKey, primaryOwner, backupOwner); // Return the actual key not the stored one, else it will be wrapped again :( return key; } if (++attempt == 1_000) { throw new AssertionError("Unable to find key that maps to primary " + primaryOwner + " and backup " + backupOwner); } } } } public void testLifespanExpiredOnBoth() { Object key = createKey(cache0, cache1); cache0.put(key, key.toString(), 10, TimeUnit.MINUTES); assertEquals(key.toString(), cache0.get(key)); assertEquals(key.toString(), cache1.get(key)); // Now we expire on cache0, it should still exist on cache1 ts0.advance(TimeUnit.MINUTES.toMillis(10) + 1); ts1.advance(TimeUnit.MINUTES.toMillis(10) + 1); // Both should be null assertNull(cache0.get(key)); assertNull(cache1.get(key)); } private void incrementAllTimeServices(long time, TimeUnit unit) { for (ControlledTimeService cts : Arrays.asList(ts0, ts1, ts2)) { cts.advance(unit.toMillis(time)); } } @Test(groups = "unstable", description = "https://issues.redhat.com/browse/ISPN-11422") public void testWriteExpiredEntry() { String key = "key"; String value = "value"; for (int i = 0; i < 100; ++i) { Cache<Object, Object> cache = cache0; Object prev = cache.get(key); if (prev == null) { prev = cache.putIfAbsent(key, value, 1, TimeUnit.SECONDS); // Should be guaranteed to be null assertNull(prev); // We should always have a value still assertNotNull(cache.get(key)); } long secondOneMilliAdvanced = TimeUnit.SECONDS.toMillis(1); ts0.advance(secondOneMilliAdvanced); ts1.advance(secondOneMilliAdvanced); ts2.advance(secondOneMilliAdvanced); } } // Simpler test for https://issues.redhat.com/browse/ISPN-11422 // public void testBackupExpirationWritePrimary() { // testExpirationButOnBackupDuringWrite(true); // } // // public void testBackupExpirationWriteBackup() { // testExpirationButOnBackupDuringWrite(false); // } // // private void testExpirationButOnBackupDuringWrite(boolean primary) { // Object key = createKey(cache0, cache1); // String value = key.toString(); // assertNull(cache0.put(key, value, 10, TimeUnit.SECONDS)); // // // Advance the backup so it is expired there // ts1.advance(TimeUnit.SECONDS.toMillis(11)); // // assertEquals(value, ((primary ? cache0 : cache1).put(key, "replacement-value"))); // } public void testPrimaryNotExpiredButBackupWas() throws InterruptedException, ExecutionException, TimeoutException { if (transactional) { throw new SkipException("Test isn't supported in transactional mode"); } Object key = createKey(cache0, cache1); String value = key.toString(); cache0.put(key, value,10, TimeUnit.SECONDS); final ControlledRpcManager controlledRpcManager = ControlledRpcManager.replaceRpcManager(cache0); Class<? extends ReplicableCommand> commandToExpect; if (cacheMode == CacheMode.DIST_SYNC) { controlledRpcManager.excludeCommands(PutKeyValueCommand.class); commandToExpect = BackupWriteCommand.class; } else { commandToExpect = PutKeyValueCommand.class; } try { Future<Object> result = fork(() -> cache0.put(key, value + "-expire-backup")); ControlledRpcManager.BlockedRequest<? extends ReplicableCommand> blockedRequest = controlledRpcManager.expectCommand(commandToExpect); incrementAllTimeServices(11, TimeUnit.SECONDS); ControlledRpcManager.SentRequest sentRequest = blockedRequest.send(); if (sentRequest != null) { sentRequest.expectAllResponses().receive(); } assertEquals(value, result.get(10, TimeUnit.SECONDS)); } finally { controlledRpcManager.revertRpcManager(); } assertEquals(value + "-expire-backup", cache0.get(key)); assertEquals(value + "-expire-backup", cache1.get(key)); assertEquals(value + "-expire-backup", cache2.get(key)); } public void testExpirationWithNoValueEquals() { Object key = createKey(cache0, cache1); cache0.put(key, new ExpirationFunctionalTest.NoEquals("value"), 10, TimeUnit.MINUTES); assertEquals(1, cache0.getAdvancedCache().getDataContainer().sizeIncludingExpired()); assertEquals(1, cache1.getAdvancedCache().getDataContainer().sizeIncludingExpired()); // Now we expire on cache0, it should still exist on cache1 ts0.advance(TimeUnit.MINUTES.toMillis(10) + 1); ts1.advance(TimeUnit.MINUTES.toMillis(10) + 1); assertEquals(1, cache0.getAdvancedCache().getDataContainer().sizeIncludingExpired()); assertEquals(1, cache1.getAdvancedCache().getDataContainer().sizeIncludingExpired()); cache0.getAdvancedCache().getExpirationManager().processExpiration(); verifyNoValue(cache0.getAdvancedCache().getDataContainer().iteratorIncludingExpired()); verifyNoValue(cache1.getAdvancedCache().getDataContainer().iteratorIncludingExpired()); } private void verifyNoValue(Iterator<InternalCacheEntry<Object, Object>> iter) { if (iter.hasNext()) { assertNull(iter.next().getValue()); } assertFalse(iter.hasNext()); } }
13,301
41.228571
168
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ExpirationManagerTest.java
package org.infinispan.expiration.impl; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.infinispan.AdvancedCache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.factories.KnownComponentNames; import org.infinispan.factories.impl.TestComponentAccessors; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.mockito.Answers; import org.testng.annotations.Test; @Test(groups = "unit", testName = "expiration.impl.ExpirationManagerTest") public class ExpirationManagerTest extends AbstractInfinispanTest { private ConfigurationBuilder getCfg() { ConfigurationBuilder builder = new ConfigurationBuilder(); return builder; } public void testNoExpirationThread() { ExpirationManagerImpl em = new ExpirationManagerImpl(); Configuration cfg = getCfg().expiration().wakeUpInterval(0L).build(); ScheduledExecutorService mockService = mock(ScheduledExecutorService.class); TestingUtil.inject(em, cfg, mock(AdvancedCache.class, Answers.RETURNS_MOCKS), new TestComponentAccessors.NamedComponent(KnownComponentNames.EXPIRATION_SCHEDULED_EXECUTOR, mockService)); em.start(); assertNull("Expiration task is not null! Should not have scheduled anything!", em.expirationTask); } public void testWakeupInterval() { ExpirationManagerImpl em = new ExpirationManagerImpl(); Configuration cfg = getCfg().expiration().wakeUpInterval(789L).build(); ScheduledExecutorService mockService = mock(ScheduledExecutorService.class); TestingUtil.inject(em, cfg, mock(AdvancedCache.class, Answers.RETURNS_MOCKS), new TestComponentAccessors.NamedComponent(KnownComponentNames.EXPIRATION_SCHEDULED_EXECUTOR, mockService)); ScheduledFuture mockFuture = mock(ScheduledFuture.class); when(mockService.scheduleWithFixedDelay(isA(ExpirationManagerImpl.ScheduledTask.class), eq(789l), eq(789l), eq(TimeUnit.MILLISECONDS))) .thenReturn(mockFuture); em.start(); assertEquals(mockFuture, em.expirationTask); verify(mockService).scheduleWithFixedDelay(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class)); // expect that the executor was never used!! } }
2,898
43.6
158
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ExpiredCacheListener.java
package org.infinispan.expiration.impl; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired; import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; @Listener public class ExpiredCacheListener { private final static Log log = LogFactory.getLog(ExpiredCacheListener.class); private final List<CacheEntryExpiredEvent> events = Collections.synchronizedList(new ArrayList<>()); private final AtomicInteger invocationCount = new AtomicInteger(); public void reset() { events.clear(); invocationCount.set(0); } public List<CacheEntryExpiredEvent> getEvents() { return events; } public int getInvocationCount() { return invocationCount.get(); } // handler @CacheEntryExpired public void handle(CacheEntryExpiredEvent e) { log.trace("Received event: " + e); events.add(e); invocationCount.incrementAndGet(); } }
1,210
26.522727
103
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ExpirationFileStoreDistListenerFunctionalTest.java
package org.infinispan.expiration.impl; import static org.infinispan.expiration.impl.ExpirationFileStoreListenerFunctionalTest.FileStoreToUse.SINGLE; import static org.infinispan.expiration.impl.ExpirationFileStoreListenerFunctionalTest.FileStoreToUse.SOFT_INDEX; import static org.infinispan.test.fwk.TestCacheManagerFactory.createClusteredCacheManager; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.distribution.MagicKey; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TransportFlags; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "expiration.impl.ExpirationFileStoreDistListenerFunctionalTest") public class ExpirationFileStoreDistListenerFunctionalTest extends ExpirationStoreListenerFunctionalTest { private static final String PERSISTENT_LOCATION = CommonsTestingUtil.tmpDirectory(ExpirationFileStoreDistListenerFunctionalTest.class); private static final String EXTRA_MANAGER_LOCATION = CommonsTestingUtil.tmpDirectory(ExpirationFileStoreDistListenerFunctionalTest.class + "2"); private EmbeddedCacheManager extraManager; private Cache<Object, Object> extraCache; private ExpirationFileStoreListenerFunctionalTest.FileStoreToUse fileStoreToUse; ExpirationStoreFunctionalTest fileStoreToUse(ExpirationFileStoreListenerFunctionalTest.FileStoreToUse fileStoreToUse) { this.fileStoreToUse = fileStoreToUse; return this; } @Factory @Override public Object[] factory() { return new Object[]{ // Test is for single file store with a listener in a dist cache and we don't care about memory storage types new ExpirationFileStoreDistListenerFunctionalTest().fileStoreToUse(SINGLE).cacheMode(CacheMode.DIST_SYNC), new ExpirationFileStoreDistListenerFunctionalTest().fileStoreToUse(SOFT_INDEX).cacheMode(CacheMode.DIST_SYNC), }; } @Override protected String parameters() { return "[ " + fileStoreToUse + "]"; } @Override protected void configure(ConfigurationBuilder config) { config // Prevent the reaper from running, reaperEnabled(false) doesn't work when a store is present .expiration().wakeUpInterval(Long.MAX_VALUE) .clustering().cacheMode(cacheMode); switch (fileStoreToUse) { case SINGLE: config.persistence().addSingleFileStore(); break; case SOFT_INDEX: config.persistence().addSoftIndexFileStore(); break; } } @AfterClass(alwaysRun = true) protected void clearTempDir() { Util.recursiveFileRemove(PERSISTENT_LOCATION); Util.recursiveFileRemove(EXTRA_MANAGER_LOCATION); } protected void removeFromContainer(String key) { super.removeFromContainer(key); extraCache.getAdvancedCache().getDataContainer().remove(key); } @Override protected void processExpiration() { // Invoking process expiration only removes primary owned entries - so we need to invoke it on the extra cache // in addition to the original cache super.processExpiration(); TestingUtil.extractComponent(extraCache, InternalExpirationManager.class).processExpiration(); } @AfterMethod(alwaysRun = true) @Override protected void clearContent() { super.clearContent(); // We also have to clear the content of the extraManager TestingUtil.clearContent(extraManager); } @Override protected EmbeddedCacheManager createCacheManager(ConfigurationBuilder builder) { GlobalConfigurationBuilder globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); configure(globalBuilder); // Make sure each cache writes to a different location globalBuilder.globalState().enable().persistentLocation(EXTRA_MANAGER_LOCATION); extraManager = createClusteredCacheManager(false, globalBuilder, builder, new TransportFlags()); // Inject our time service into the new CacheManager as well TestingUtil.replaceComponent(extraManager, TimeService.class, timeService, true); extraCache = extraManager.getCache(); globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); configure(globalBuilder); // Make sure each cache writes to a different location globalBuilder.globalState().enable().persistentLocation(PERSISTENT_LOCATION); EmbeddedCacheManager returned = createClusteredCacheManager(false, globalBuilder, builder, new TransportFlags()); // Unfortunately we can't reinject timeservice once a cache has been started, thus we have to inject // here as well, since we need the cache to verify the cluster was formed TestingUtil.replaceComponent(returned, TimeService.class, timeService, true); Cache<Object, Object> checkCache = returned.getCache(); TestingUtil.blockUntilViewReceived(checkCache, 2, TimeUnit.SECONDS.toMillis(10)); return returned; } @Override protected Object keyToUseWithExpiration() { return new MagicKey(cache); } }
5,608
41.492424
147
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ExpirationListenerFunctionalTest.java
package org.infinispan.expiration.impl; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.StorageType; import org.infinispan.expiration.ExpirationManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.cachelistener.event.Event; import org.testng.annotations.AfterMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "expiration.impl.ExpirationListenerFunctionalTest") public class ExpirationListenerFunctionalTest extends ExpirationFunctionalTest { protected ExpiredCacheListener listener = new ExpiredCacheListener(); protected ExpirationManager manager; @Factory @Override public Object[] factory() { return new Object[]{ new ExpirationListenerFunctionalTest().cacheMode(CacheMode.LOCAL).withStorage(StorageType.BINARY), new ExpirationListenerFunctionalTest().cacheMode(CacheMode.LOCAL).withStorage(StorageType.OBJECT), new ExpirationListenerFunctionalTest().cacheMode(CacheMode.LOCAL).withStorage(StorageType.OFF_HEAP), new ExpirationListenerFunctionalTest().cacheMode(CacheMode.DIST_SYNC).withStorage(StorageType.BINARY), new ExpirationListenerFunctionalTest().cacheMode(CacheMode.DIST_SYNC).withStorage(StorageType.OBJECT), new ExpirationListenerFunctionalTest().cacheMode(CacheMode.DIST_SYNC).withStorage(StorageType.OFF_HEAP) }; } @Override protected void afterCacheCreated(EmbeddedCacheManager cm) { cache.addListener(listener); manager = cache.getAdvancedCache().getExpirationManager(); } @AfterMethod public void resetListener() { listener.reset(); } @Override public void testSimpleExpirationLifespan() throws Exception { super.testSimpleExpirationLifespan(); manager.processExpiration(); assertExpiredEvents(SIZE); } @Override public void testSimpleExpirationMaxIdle() throws Exception { super.testSimpleExpirationMaxIdle(); manager.processExpiration(); assertExpiredEvents(SIZE); } private void assertExpiredEvents(int count) { assertEquals(count, listener.getInvocationCount()); listener.getEvents().forEach(event -> { assertEquals(Event.Type.CACHE_ENTRY_EXPIRED, event.getType()); assertEquals(cache, event.getCache()); assertFalse(event.isPre()); assertNotNull(event.getKey()); assertNotNull(event.getValue()); assertNotNull(event.getMetadata()); }); } public void testExpiredEventBetweenCreateEvent() { cache.put("foo", "bar", 1, TimeUnit.SECONDS); timeService.advance(2000); cache.put("foo", "bar2"); assertExpiredEvents(1); } }
3,007
36.135802
115
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ExpirationWithClusteredWriteSkewTest.java
package org.infinispan.expiration.impl; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.CacheEntry; import org.infinispan.expiration.ExpirationManager; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.TransactionMode; import org.infinispan.util.ControlledConsistentHashFactory; import org.infinispan.util.ControlledTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; /** * Test that the default expiration parameters are set properly with clustered write skew checks enabled. * * See https://issues.jboss.org/browse/ISPN-7105 */ @Test(groups = "functional", testName = "expiration.impl.ExpirationWithClusteredWriteSkewTest") public class ExpirationWithClusteredWriteSkewTest extends MultipleCacheManagersTest { public static final String KEY = "key"; public static final String VALUE = "value"; private ControlledTimeService timeService = new ControlledTimeService(); private ExpirationManager expirationManager1; private ExpirationManager expirationManager2; @Override protected void createCacheManagers() throws Throwable { ControlledConsistentHashFactory chf = new ControlledConsistentHashFactory.Default(0, 1); ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(true); builder .clustering() .cacheMode(CacheMode.REPL_SYNC) .hash() .numSegments(1) .consistentHashFactory(chf) .expiration() .lifespan(10, TimeUnit.SECONDS) .transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .lockingMode(LockingMode.OPTIMISTIC) .locking() .isolationLevel(IsolationLevel.REPEATABLE_READ); createCluster(builder, 2); TestingUtil.replaceComponent(manager(0), TimeService.class, timeService, true); expirationManager1 = cache(0).getAdvancedCache().getExpirationManager(); TestingUtil.replaceComponent(manager(1), TimeService.class, timeService, true); expirationManager2 = cache(1).getAdvancedCache().getExpirationManager(); } public void testDefaultExpirationInTransaction() throws Exception { Cache<Object, Object> cache0 = cache(0); tm(0).begin(); assertNull(cache0.get(KEY)); cache0.put(KEY, VALUE); CacheEntry entryInTx = cache0.getAdvancedCache().getCacheEntry(KEY); assertEquals(10000, entryInTx.getLifespan()); tm(0).commit(); CacheEntry entryAfterCommit = cache0.getAdvancedCache().getCacheEntry(KEY); assertEquals(10000, entryAfterCommit.getLifespan()); timeService.advance(TimeUnit.SECONDS.toMillis(10) + 1); // Required since cache loader size calls to store - we have to make sure the store expires entries expirationManager1.processExpiration(); expirationManager2.processExpiration(); assertEquals(0, cache0.size()); } }
3,440
40.457831
105
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/MaxIdlePessimisticTxTest.java
package org.infinispan.expiration.impl; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.replaceComponent; import static org.infinispan.test.TestingUtil.v; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.lang.reflect.Method; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.infinispan.Cache; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.context.Flag; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.transaction.LockingMode; import org.infinispan.util.ControlledTimeService; import org.testng.annotations.Test; /** * Test to verify clustered max idle in a pessimistic transaction * * @author Pedro Ruivo * @since 12.0 */ @Test(groups = "functional", testName = "expiration.impl.MaxIdlePessimisticTxTest") public class MaxIdlePessimisticTxTest extends MultipleCacheManagersTest { private static final int NUM_NODES = 3; private static final long MAX_IDLE = 10; private final ControlledTimeService timeService = new ControlledTimeService(); public void testWriteLock(Method method) throws Exception { final String key = k(method); final String value = v(method, 0); final String value2 = v(method, 1); Cache<String, String> cache = findNonOwnerCache(key); cache.put(key, value, -1, TimeUnit.SECONDS, MAX_IDLE, TimeUnit.MILLISECONDS); long lastWallClock = timeService.wallClockTime(); timeService.advance(MAX_IDLE - 1); assertNotExpired(key); assertLastUsed(key, lastWallClock); cache.getAdvancedCache().getTransactionManager().begin(); assertEquals(value, cache.put(key, value2, -1, TimeUnit.SECONDS, MAX_IDLE, TimeUnit.MILLISECONDS)); assertEquals(value2, cache.get(key)); // rollback the transaction cache.getAdvancedCache().getTransactionManager().rollback(); lastWallClock = timeService.wallClockTime(); assertNotExpired(key); assertLastUsed(key, lastWallClock); // the tx touches the key, this advance should not expire it timeService.advance(2); assertNotExpired(key); assertLastUsed(key, lastWallClock); // expire the key timeService.advance(MAX_IDLE); assertExpired(key); assertLastUsed(key, lastWallClock); assertNull(cache(0).get(key)); } public void testReadLock(Method method) throws Exception { final String key = k(method); final String value = v(method, 0); Cache<String, String> cache = findNonOwnerCache(key); cache.put(key, value, -1, TimeUnit.SECONDS, MAX_IDLE, TimeUnit.MILLISECONDS); long lastWallClock = timeService.wallClockTime(); timeService.advance(MAX_IDLE - 1); assertNotExpired(key); assertLastUsed(key, lastWallClock); cache.getAdvancedCache().getTransactionManager().begin(); assertEquals(value, cache.getAdvancedCache().withFlags(Flag.FORCE_WRITE_LOCK).get(key)); // rollback the transaction cache.getAdvancedCache().getTransactionManager().rollback(); lastWallClock = timeService.wallClockTime(); assertNotExpired(key); assertLastUsed(key, lastWallClock); // the tx touches the key, this advance should not expire it timeService.advance(2); assertNotExpired(key); assertLastUsed(key, lastWallClock); // expire the key timeService.advance(MAX_IDLE); assertExpired(key); assertLastUsed(key, lastWallClock); assertNull(cache(0).get(key)); } public void testReadLockExpired(Method method) throws Exception { final String key = k(method); final String value = v(method, 0); Cache<String, String> cache = findNonOwnerCache(key); cache.put(key, value, -1, TimeUnit.SECONDS, MAX_IDLE, TimeUnit.MILLISECONDS); long lastWallClock = timeService.wallClockTime(); timeService.advance(MAX_IDLE + 1); assertExpired(key); assertLastUsed(key, lastWallClock); cache.getAdvancedCache().getTransactionManager().begin(); assertNull(cache.getAdvancedCache().withFlags(Flag.FORCE_WRITE_LOCK).get(key)); // rollback the transaction cache.getAdvancedCache().getTransactionManager().rollback(); assertExpired(key); assertLastUsed(key, lastWallClock); assertNull(cache(0).get(key)); } public void testWriteLockExpired(Method method) throws Exception { final String key = k(method); final String value = v(method, 0); final String value2 = v(method, 1); Cache<String, String> cache = findNonOwnerCache(key); cache.put(key, value, -1, TimeUnit.SECONDS, MAX_IDLE, TimeUnit.MILLISECONDS); long lastWallClock = timeService.wallClockTime(); timeService.advance(MAX_IDLE + 1); assertExpired(key); assertLastUsed(key, lastWallClock); cache.getAdvancedCache().getTransactionManager().begin(); assertNull(cache.put(key, value2, -1, TimeUnit.SECONDS, MAX_IDLE, TimeUnit.MILLISECONDS)); assertEquals(value2, cache.get(key)); // rollback the transaction cache.getAdvancedCache().getTransactionManager().rollback(); lastWallClock = timeService.wallClockTime(); assertExpired(key); assertLastUsed(key, lastWallClock); assertNull(cache(0).get(key)); } private Cache<String, String> findNonOwnerCache(String key) { for (Cache<String, String> cache : this.<String, String>caches()) { if (!extractComponent(cache, ClusteringDependentLogic.class).getCacheTopology().isReadOwner(key)) { return cache; } } fail(); throw new IllegalStateException(); } private void assertNotExpired(String key) { getKeyFromAllCaches(key).forEach(entry -> assertFalse(entry.isExpired(timeService.wallClockTime()))); } private void assertLastUsed(String key, long expected) { getKeyFromAllCaches(key).forEach(entry -> assertEquals(expected, entry.getLastUsed())); } private void assertExpired(String key) { getKeyFromAllCaches(key).forEach(entry -> assertTrue(entry.isExpired(timeService.wallClockTime()))); } private Stream<? extends InternalCacheEntry<?, ?>> getKeyFromAllCaches(String key) { return caches().stream().map(cache -> { InternalDataContainer<?, ?> dc = extractComponent(cache, InternalDataContainer.class); KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); return dc.peek(keyPartitioner.getSegment(key), key); }).filter(Objects::nonNull); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); builder.transaction().lockingMode(LockingMode.PESSIMISTIC); createCluster(builder, NUM_NODES); cacheManagers.forEach(cm -> replaceComponent(cm, TimeService.class, timeService, true)); } }
7,634
35.357143
108
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ClusterExpirationMaxIdleLoaderTest.java
package org.infinispan.expiration.impl; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.expiration.TouchMode; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.testng.annotations.Test; /** * Tests to make sure that when max-idle expiration occurs it occurs across the cluster even if a loader is in use * * @author William Burns * @since 8.0 */ @Test(groups = "functional", testName = "expiration.impl.ClusterExpirationMaxIdleLoaderTest") public class ClusterExpirationMaxIdleLoaderTest extends ClusterExpirationMaxIdleTest { @Override protected void createCluster(ConfigurationBuilder builder, int count) { builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); super.createCluster(builder, count); } @Override public Object[] factory() { return new Object[] { new ClusterExpirationMaxIdleLoaderTest().cacheMode(CacheMode.DIST_SYNC).transactional(true), new ClusterExpirationMaxIdleLoaderTest().cacheMode(CacheMode.DIST_SYNC).transactional(false), new ClusterExpirationMaxIdleLoaderTest().cacheMode(CacheMode.REPL_SYNC).transactional(true), new ClusterExpirationMaxIdleLoaderTest().cacheMode(CacheMode.REPL_SYNC).transactional(false), new ClusterExpirationMaxIdleLoaderTest().touch(TouchMode.ASYNC).cacheMode(CacheMode.DIST_SYNC).transactional(false), new ClusterExpirationMaxIdleLoaderTest().touch(TouchMode.ASYNC).cacheMode(CacheMode.REPL_SYNC).transactional(false), }; } }
1,654
46.285714
128
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ExpirationStoreFunctionalTest.java
package org.infinispan.expiration.impl; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "expiration.impl.ExpirationStoreFunctionalTest") public class ExpirationStoreFunctionalTest extends ExpirationFunctionalTest { private boolean passivationEnabled; private final int MAX_IN_MEMORY = 5; ExpirationStoreFunctionalTest passivation(boolean enable) { this.passivationEnabled = enable; return this; } @Factory @Override public Object[] factory() { return new Object[]{ // Test is for dummy store and we don't care about memory storage types new ExpirationStoreFunctionalTest().passivation(true).cacheMode(CacheMode.LOCAL), new ExpirationStoreFunctionalTest().passivation(false).cacheMode(CacheMode.LOCAL), }; } @Override protected String parameters() { return "[passivation= " + passivationEnabled + "]"; } @Override protected void configure(ConfigurationBuilder config) { config .memory().maxCount(passivationEnabled ? MAX_IN_MEMORY : -1) // Prevent the reaper from running, reaperEnabled(false) doesn't work when a store is present .expiration().wakeUpInterval(Long.MAX_VALUE) .persistence().passivation(passivationEnabled) .addStore(DummyInMemoryStoreConfigurationBuilder.class); } @Override protected int maxInMemory() { return passivationEnabled ? MAX_IN_MEMORY : super.maxInMemory(); } public void testMaxIdleWithPassivation() { cache.put("will-expire", "uh oh", -1, null, 1, TimeUnit.MILLISECONDS); // Approximately half of these will be in memory with passivation, with rest in the store for (int i = 0; i < SIZE; i++) { cache.put("key-" + i, "value-" + i, -1, null, 10, TimeUnit.MILLISECONDS); } assertEquals(SIZE + 1, cache.size()); timeService.advance(6); assertEquals(SIZE, cache.size()); // Now we read just a few of them assertNotNull(cache.get("key-" + 1)); assertNotNull(cache.get("key-" + 6)); assertNotNull(cache.get("key-" + 3)); processExpiration(); // This will expire all but the 3 we touched above timeService.advance(6); assertEquals(3, cache.size()); // This will expire the rest timeService.advance(6); assertEquals(0, cache.size()); processExpiration(); assertEquals(0, cache.getAdvancedCache().getDataContainer().sizeIncludingExpired()); } }
2,918
31.076923
105
java