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/client/hotrod/src/main/java/org/infinispan/hotrod/impl/TimeUnitParam.java
package org.infinispan.hotrod.impl; import java.time.Duration; import java.util.EnumMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.api.common.CacheEntryExpiration; /** * Time unit representation for HotRod * * @since 14.0 */ public class TimeUnitParam { private static final Map<TimeUnit, Byte> timeUnitToByte = new EnumMap<>(TimeUnit.class); static { timeUnitToByte.put(TimeUnit.SECONDS, (byte) 0); timeUnitToByte.put(TimeUnit.MILLISECONDS, (byte) 1); timeUnitToByte.put(TimeUnit.NANOSECONDS, (byte) 2); timeUnitToByte.put(TimeUnit.MICROSECONDS, (byte) 3); timeUnitToByte.put(TimeUnit.MINUTES, (byte) 4); timeUnitToByte.put(TimeUnit.HOURS, (byte) 5); timeUnitToByte.put(TimeUnit.DAYS, (byte) 6); } private static final byte TIME_UNIT_DEFAULT = (byte) 7; private static final byte TIME_UNIT_INFINITE = (byte) 8; private static byte encodeDuration(Duration duration) { return duration == Duration.ZERO ? TIME_UNIT_DEFAULT : duration == null ? TIME_UNIT_INFINITE : 0; } public static byte encodeTimeUnits(CacheEntryExpiration.Impl expiration) { byte encodedLifespan = encodeDuration(expiration.rawLifespan()); byte encodedMaxIdle = encodeDuration(expiration.rawMaxIdle()); return (byte) (encodedLifespan << 4 | encodedMaxIdle); } }
1,375
31.761905
103
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/HotRodTransport.java
package org.infinispan.hotrod.impl; import static org.infinispan.hotrod.impl.Util.await; import static org.infinispan.hotrod.impl.Util.checkTransactionSupport; import static org.infinispan.hotrod.impl.logging.Log.HOTROD; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.regex.Matcher; import java.util.regex.Pattern; import jakarta.transaction.TransactionManager; import org.infinispan.api.common.CacheOptions; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.commons.executors.ExecutorFactory; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.marshall.UTF8StringMarshaller; import org.infinispan.commons.marshall.UserContextInitializerImpl; import org.infinispan.commons.time.DefaultTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.GlobUtils; import org.infinispan.commons.util.Util; import org.infinispan.commons.util.Version; import org.infinispan.counter.api.CounterManager; import org.infinispan.hotrod.configuration.HotRodConfiguration; import org.infinispan.hotrod.configuration.NearCacheConfiguration; import org.infinispan.hotrod.configuration.RemoteCacheConfiguration; import org.infinispan.hotrod.configuration.TransactionMode; import org.infinispan.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.hotrod.exceptions.HotRodClientException; import org.infinispan.hotrod.impl.cache.ClientStatistics; import org.infinispan.hotrod.impl.cache.InvalidatedNearRemoteCache; import org.infinispan.hotrod.impl.cache.MBeanHelper; import org.infinispan.hotrod.impl.cache.RemoteCache; import org.infinispan.hotrod.impl.cache.RemoteCacheImpl; import org.infinispan.hotrod.impl.counter.RemoteCounterManager; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.hotrod.impl.operations.CacheOperationsFactory; import org.infinispan.hotrod.impl.operations.PingResponse; import org.infinispan.hotrod.impl.protocol.Codec; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transaction.SyncModeTransactionTable; import org.infinispan.hotrod.impl.transaction.TransactionOperationFactory; import org.infinispan.hotrod.impl.transaction.TransactionTable; import org.infinispan.hotrod.impl.transaction.TransactionalRemoteCacheImpl; import org.infinispan.hotrod.impl.transaction.XaModeTransactionTable; import org.infinispan.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.hotrod.marshall.BytesOnlyMarshaller; import org.infinispan.hotrod.near.NearCacheService; import org.infinispan.hotrod.transaction.lookup.GenericTransactionManagerLookup; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; /** * @since 14.0 **/ public class HotRodTransport implements AutoCloseable { private final static Log log = LogFactory.getLog(HotRodTransport.class); private static final String JSON_STRING_ARRAY_ELEMENT_REGEX = "(?:\")([^\"]*)(?:\",?)"; private final MarshallerRegistry marshallerRegistry; private final HotRodConfiguration configuration; private final RemoteCounterManager counterManager; private final TransactionTable syncTransactionTable; private final XaModeTransactionTable xaTransactionTable; private final ChannelFactory channelFactory; private final Codec codec; private final ExecutorService asyncExecutorService; private final Marshaller marshaller; private ClientListenerNotifier listenerNotifier; private TimeService timeService = DefaultTimeService.INSTANCE; private volatile boolean started = false; private final ConcurrentMap<RemoteCacheKey, CompletionStage<RemoteCache<Object, Object>>> cacheName2RemoteCache = new ConcurrentHashMap<>(); private final MBeanHelper mBeanHelper; public HotRodTransport(HotRodConfiguration configuration) { this.configuration = configuration; counterManager = new RemoteCounterManager(); syncTransactionTable = new SyncModeTransactionTable(configuration.transactionTimeout()); xaTransactionTable = new XaModeTransactionTable(configuration.transactionTimeout()); channelFactory = createChannelFactory(); codec = Codec.forProtocol(configuration.version()); marshallerRegistry = new MarshallerRegistry(); marshallerRegistry.registerMarshaller(BytesOnlyMarshaller.INSTANCE); marshallerRegistry.registerMarshaller(new UTF8StringMarshaller()); marshallerRegistry.registerMarshaller(new JavaSerializationMarshaller(configuration.getClassAllowList())); try { ProtoStreamMarshaller protoMarshaller = new ProtoStreamMarshaller(); marshallerRegistry.registerMarshaller(protoMarshaller); initProtoStreamMarshaller(protoMarshaller); } catch (NoClassDefFoundError e) { // Ignore the error, if the protostream dependency is missing } marshaller = initMarshaller(); ExecutorFactory executorFactory = configuration.asyncExecutorFactory().factory(); if (executorFactory == null) { executorFactory = Util.getInstance(configuration.asyncExecutorFactory().factoryClass()); } asyncExecutorService = executorFactory.getExecutor(configuration.asyncExecutorFactory().properties()); mBeanHelper = MBeanHelper.getInstance(this); } private Marshaller initMarshaller() { boolean customMarshallerInstance = true; Marshaller marshaller = configuration.marshaller(); if (marshaller == null) { Class<? extends Marshaller> clazz = configuration.marshallerClass(); marshaller = marshallerRegistry.getMarshaller(clazz); if (marshaller == null) { marshaller = Util.getInstance(clazz); } else { customMarshallerInstance = false; } } if (customMarshallerInstance) { if (configuration.serialAllowList().length > 0) { marshaller.initialize(configuration.getClassAllowList()); } if (marshaller instanceof ProtoStreamMarshaller) { initProtoStreamMarshaller((ProtoStreamMarshaller) marshaller); } // Replace any default marshaller with the same media type marshallerRegistry.registerMarshaller(marshaller); } return marshaller; } protected ChannelFactory createChannelFactory() { return new ChannelFactory(); } public MBeanHelper getMBeanHelper() { return mBeanHelper; } private void initProtoStreamMarshaller(ProtoStreamMarshaller protoMarshaller) { SerializationContext ctx = protoMarshaller.getSerializationContext(); // Register some useful builtin schemas, which the user can override later. registerDefaultSchemas(ctx, "org.infinispan.protostream.types.java.CommonContainerTypesSchema", "org.infinispan.protostream.types.java.CommonTypesSchema"); registerSerializationContextInitializer(ctx, new UserContextInitializerImpl()); // Register the configured schemas. for (SerializationContextInitializer sci : configuration.getContextInitializers()) { registerSerializationContextInitializer(ctx, sci); } } private static void registerSerializationContextInitializer(SerializationContext ctx, SerializationContextInitializer sci) { sci.registerSchema(ctx); sci.registerMarshallers(ctx); } private static void registerDefaultSchemas(SerializationContext ctx, String... classNames) { for (String className : classNames) { SerializationContextInitializer sci; try { Class<?> clazz = Class.forName(className); Object instance = clazz.getDeclaredConstructor().newInstance(); sci = (SerializationContextInitializer) instance; } catch (Exception e) { HOTROD.failedToCreatePredefinedSerializationContextInitializer(className, e); continue; } registerSerializationContextInitializer(ctx, sci); } } public HotRodConfiguration getConfiguration() { return configuration; } public TimeService getTimeService() { return timeService; } public MarshallerRegistry getMarshallerRegistry() { return marshallerRegistry; } public ChannelFactory getChannelFactory() { return channelFactory; } public Marshaller getMarshaller() { return marshaller; } public CounterManager getCounterManager() { return counterManager; } public Codec getCodec() { return codec; } public XaModeTransactionTable getXaTransactionTable() { return xaTransactionTable; } public TransactionTable getTransactionTable(TransactionMode transactionMode) { switch (transactionMode) { case NON_XA: return syncTransactionTable; case NON_DURABLE_XA: case FULL_XA: return xaTransactionTable; default: throw new IllegalStateException(); } } public <K, V> NearCacheService<K, V> createNearCacheService(String cacheName, NearCacheConfiguration cfg) { return NearCacheService.create(cfg, listenerNotifier); } public CacheOperationsFactory createCacheOperationFactory(String cacheName, ClientStatistics stats) { return new CacheOperationsFactory(channelFactory, cacheName, codec, listenerNotifier, configuration, stats); } public void start() { if (!started) { HOTROD.debugf("Starting Hot Rod client %x", System.identityHashCode(this)); channelFactory.start(codec, configuration, marshaller, asyncExecutorService, listenerNotifier, marshallerRegistry); counterManager.start(channelFactory, codec, configuration, listenerNotifier); listenerNotifier = new ClientListenerNotifier(codec, channelFactory, configuration); TransactionOperationFactory txOperationFactory = new TransactionOperationFactory(configuration, channelFactory, codec); syncTransactionTable.start(txOperationFactory); xaTransactionTable.start(txOperationFactory); HOTROD.debugf("Infinispan version: %s", Version.printVersion()); started = true; } } @Override public void close() { if (started) { listenerNotifier.stop(); counterManager.stop(); channelFactory.destroy(); started = false; } mBeanHelper.close(); } public boolean isStarted() { return started; } public <K, V> CompletionStage<RemoteCache<K, V>> getRemoteCache(String cacheName) { RemoteCacheConfiguration cacheConfiguration = findConfiguration(cacheName); return getRemoteCache(cacheName, cacheConfiguration); } public <K, V> CompletionStage<RemoteCache<K, V>> getRemoteCache(String cacheName, RemoteCacheConfiguration cacheConfiguration) { boolean forceReturnValue = (cacheConfiguration != null ? cacheConfiguration.forceReturnValues() : configuration.forceReturnValues()); RemoteCacheKey key = new RemoteCacheKey(cacheName, forceReturnValue); CompletionStage<RemoteCache<Object, Object>> remoteCache = cacheName2RemoteCache.computeIfAbsent(key, k -> pingRemoteCache(cacheName, cacheConfiguration) ); return (CompletionStage) remoteCache; } private <K, V> CompletionStage<RemoteCache<K, V>> pingRemoteCache(String cacheName, RemoteCacheConfiguration cacheConfiguration) { CacheOperationsFactory cacheOperationsFactory = createOperationFactory(cacheName, codec, null); CompletionStage<PingResponse> pingResponse; if (started) { // Verify if the cache exists on the server first CompletionStage<PingResponse> cs = cacheOperationsFactory.newFaultTolerantPingOperation().execute(); pingResponse = cs.thenCompose(ping -> { if (ping.isCacheNotFound()) { return createRemoteCache(cacheOperationsFactory, cacheName, cacheConfiguration); } else { return cs; } }); } else { pingResponse = CompletableFuture.completedFuture(PingResponse.EMPTY); } return pingResponse.thenApply(ping -> { TransactionMode transactionMode = cacheConfiguration != null ? cacheConfiguration.transactionMode() : TransactionMode.NONE; RemoteCache<K, V> remoteCache; if (transactionMode == TransactionMode.NONE) { if (cacheConfiguration != null && cacheConfiguration.nearCache().mode().enabled()) { NearCacheConfiguration nearCache = cacheConfiguration.nearCache(); if (log.isTraceEnabled()) { log.tracef("Enabling near-caching for cache '%s'", cacheName); } NearCacheService<K, V> nearCacheService = createNearCacheService(cacheName, nearCache); remoteCache = InvalidatedNearRemoteCache.delegatingNearCache( new RemoteCacheImpl<>(this, cacheName, timeService, nearCacheService), nearCacheService); } else { remoteCache = new RemoteCacheImpl<>(this, cacheName, timeService, null); } } else { if (!await(checkTransactionSupport(cacheName, cacheOperationsFactory).toCompletableFuture())) { throw HOTROD.cacheDoesNotSupportTransactions(cacheName); } else { TransactionManager transactionManager = getTransactionManager(cacheConfiguration); remoteCache = createRemoteTransactionalCache(cacheName, transactionMode == TransactionMode.FULL_XA, transactionMode, transactionManager); } } remoteCache.resolveStorage(ping.isObjectStorage()); return remoteCache; }); } private CompletionStage<PingResponse> createRemoteCache(CacheOperationsFactory cacheOperationsFactory, String cacheName, RemoteCacheConfiguration cacheConfiguration) { Map<String, byte[]> params = new HashMap<>(2); params.put("name", cacheName.getBytes(HotRodConstants.HOTROD_STRING_CHARSET)); if (cacheConfiguration != null && cacheConfiguration.templateName() != null) { params.put("template", cacheConfiguration.templateName().getBytes(HotRodConstants.HOTROD_STRING_CHARSET)); } else if (cacheConfiguration != null && cacheConfiguration.configuration() != null) { params.put("configuration", new StringConfiguration(cacheConfiguration.configuration()).toStringConfiguration(cacheName).getBytes(HotRodConstants.HOTROD_STRING_CHARSET)); } else { // We cannot create the cache throw new HotRodClientException("Cache " + cacheName + " does not exist"); } // Create and re-ping CacheOperationsFactory adminCacheOperationsFactory = new CacheOperationsFactory(channelFactory, codec, listenerNotifier, configuration); return adminCacheOperationsFactory.newAdminOperation("@@cache@getorcreate", params, CacheOptions.DEFAULT).execute().thenCompose(s -> cacheOperationsFactory.newFaultTolerantPingOperation().execute()); } public CompletionStage<Void> removeCache(String cacheName) { Map<String, byte[]> params = new HashMap<>(2); params.put("name", cacheName.getBytes(HotRodConstants.HOTROD_STRING_CHARSET)); CacheOperationsFactory adminCacheOperationsFactory = new CacheOperationsFactory(channelFactory, codec, listenerNotifier, configuration); return adminCacheOperationsFactory.newAdminOperation("@@cache@remove", params, CacheOptions.DEFAULT).execute().thenApply(s -> null); // TODO: do something with the return message } public CompletionStage<Set<String>> getCacheNames() { return getConfigurationNames("@@cache@names"); } public CompletionStage<Set<String>> getTemplateNames() { return getConfigurationNames("@@cache@templates"); } private CompletionStage<Set<String>> getConfigurationNames(String taskName) { CacheOperationsFactory adminCacheOperationsFactory = new CacheOperationsFactory(channelFactory, codec, listenerNotifier, configuration); return adminCacheOperationsFactory.newAdminOperation(taskName, Collections.emptyMap(), CacheOptions.DEFAULT).execute().thenApply(names -> { Set<String> cacheNames = new HashSet<>(); // Simple pattern that matches the result which is represented as a JSON string array, e.g. ["cache1","cache2"] Pattern pattern = Pattern.compile(JSON_STRING_ARRAY_ELEMENT_REGEX); Matcher matcher = pattern.matcher(names); while (matcher.find()) { cacheNames.add(matcher.group(1)); } return cacheNames; }); } private RemoteCacheConfiguration findConfiguration(String cacheName) { if (configuration.remoteCaches().containsKey(cacheName)) { return configuration.remoteCaches().get(cacheName); } // Search for wildcard configurations for (Map.Entry<String, RemoteCacheConfiguration> c : configuration.remoteCaches().entrySet()) { String key = c.getKey(); if (GlobUtils.isGlob(key) && cacheName.matches(GlobUtils.globToRegex(key))) { return c.getValue(); } } return null; } private TransactionManager getTransactionManager(RemoteCacheConfiguration cacheConfiguration) { try { return (cacheConfiguration == null ? GenericTransactionManagerLookup.getInstance().getTransactionManager() : cacheConfiguration.transactionManagerLookup().getTransactionManager()); } catch (Exception e) { throw new HotRodClientException(e); } } private <K, V> TransactionalRemoteCacheImpl<K, V> createRemoteTransactionalCache(String cacheName, boolean recoveryEnabled, TransactionMode transactionMode, TransactionManager transactionManager) { return new TransactionalRemoteCacheImpl<>(this, cacheName, recoveryEnabled, transactionManager, getTransactionTable(transactionMode), timeService); } private CacheOperationsFactory createOperationFactory(String cacheName, Codec codec, ClientStatistics stats) { return new CacheOperationsFactory(channelFactory, cacheName, codec, listenerNotifier, configuration, stats); } public static byte[] cacheNameBytes(String cacheName) { return cacheName.getBytes(HotRodConstants.HOTROD_STRING_CHARSET); } public static byte[] cacheNameBytes() { return HotRodConstants.DEFAULT_CACHE_NAME_BYTES; } private static class RemoteCacheKey { final String cacheName; final boolean forceReturnValue; RemoteCacheKey(String cacheName, boolean forceReturnValue) { this.cacheName = cacheName; this.forceReturnValue = forceReturnValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RemoteCacheKey)) return false; RemoteCacheKey that = (RemoteCacheKey) o; if (forceReturnValue != that.forceReturnValue) return false; return Objects.equals(cacheName, that.cacheName); } @Override public int hashCode() { int result = cacheName != null ? cacheName.hashCode() : 0; result = 31 * result + (forceReturnValue ? 1 : 0); return result; } } }
20,143
44.165919
205
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/ClientTopology.java
package org.infinispan.hotrod.impl; import java.util.Objects; import org.infinispan.hotrod.configuration.ClientIntelligence; /** * Keeps the Hot Rod client topology information together: topology id and client intelligence. * * @since 14.0 */ public final class ClientTopology { private final int topologyId; private final ClientIntelligence clientIntelligence; public ClientTopology(int topologyId, ClientIntelligence clientIntelligence) { this.topologyId = topologyId; this.clientIntelligence = Objects.requireNonNull(clientIntelligence); } public int getTopologyId() { return topologyId; } public ClientIntelligence getClientIntelligence() { return clientIntelligence; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClientTopology that = (ClientTopology) o; return topologyId == that.topologyId && clientIntelligence == that.clientIntelligence; } @Override public int hashCode() { int result = topologyId; result = 31 * result + clientIntelligence.hashCode(); return result; } @Override public String toString() { return "ClientTopology{" + "topologyId=" + topologyId + ", clientIntelligence=" + clientIntelligence + '}'; } }
1,390
24.290909
95
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/MarshallerRegistry.java
package org.infinispan.hotrod.impl; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.Marshaller; /** * A registry of {@link Marshaller} along with its {@link MediaType}. * * @since 14.0 */ public final class MarshallerRegistry { public static final Log log = LogFactory.getLog(MarshallerRegistry.class, Log.class); private final Map<MediaType, Marshaller> marshallerByMediaType = new ConcurrentHashMap<>(); public void registerMarshaller(Marshaller marshaller) { marshallerByMediaType.put(marshaller.mediaType().withoutParameters(), marshaller); } public Marshaller getMarshaller(MediaType mediaType) { return marshallerByMediaType.get(mediaType); } public Marshaller getMarshaller(Class<? extends Marshaller> marshallerClass) { return marshallerByMediaType.values().stream() .filter(m -> m.getClass().equals(marshallerClass)).findFirst().orElse(null); } }
1,140
30.694444
94
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/VersionedOperationResponse.java
package org.infinispan.hotrod.impl; /** * @author Mircea.Markus@jboss.com * @since 14.0 */ public class VersionedOperationResponse<V> { public enum RspCode { SUCCESS(true), NO_SUCH_KEY(false), MODIFIED_KEY(false); private boolean isModified; RspCode(boolean modified) { isModified = modified; } public boolean isUpdated() { return isModified; } } private V value; private RspCode code; public VersionedOperationResponse(V value, RspCode code) { this.value = value; this.code = code; } public V getValue() { return value; } public RspCode getCode() { return code; } }
685
16.15
61
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/Util.java
package org.infinispan.hotrod.impl; import static org.infinispan.hotrod.impl.logging.Log.HOTROD; import java.net.SocketTimeoutException; import java.util.Collections; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.transaction.xa.Xid; import org.infinispan.commons.CacheException; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.hotrod.exceptions.HotRodClientException; import org.infinispan.hotrod.exceptions.TransportException; import org.infinispan.hotrod.impl.operations.CacheOperationsFactory; import org.infinispan.hotrod.impl.transaction.operations.PrepareTransactionOperation; public class Util { private final static long BIG_DELAY_NANOS = TimeUnit.DAYS.toNanos(1); private static final Xid DUMMY_XID = new Xid() { @Override public int getFormatId() { return 0; } @Override public byte[] getGlobalTransactionId() { return new byte[]{1}; } @Override public byte[] getBranchQualifier() { return new byte[]{1}; } }; private Util() { } public static <T> T await(CompletionStage<T> cf) { return await(cf.toCompletableFuture()); } public static <T> T await(CompletableFuture<T> cf) { try { // timed wait does not do busy waiting return cf.get(BIG_DELAY_NANOS, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { // Need to restore interrupt status because InterruptedException cannot be sent back as is Thread.currentThread().interrupt(); throw new HotRodClientException(e); } catch (ExecutionException e) { throw rewrap(e); } catch (TimeoutException e) { throw new IllegalStateException(e); } } public static <T> T await(CompletableFuture<T> cf, long timeoutMillis) { try { return cf.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // Need to restore interrupt status because InterruptedException cannot be sent back as is Thread.currentThread().interrupt(); throw new HotRodClientException(e); } catch (ExecutionException e) { throw rewrap(e); } catch (TimeoutException e) { cf.cancel(false); throw new TransportException(new SocketTimeoutException(), null); } } protected static RuntimeException rewrap(ExecutionException e) { if (e.getCause() instanceof HotRodClientException) { return (HotRodClientException) e.getCause(); } else if (e.getCause() instanceof CacheException) { return (CacheException) e.getCause(); } else { return new TransportException(e.getCause(), null); } } public static CompletionStage<Boolean> checkTransactionSupport(String cacheName, CacheOperationsFactory factory) { PrepareTransactionOperation op = factory.newPrepareTransactionOperation(DUMMY_XID, true, Collections.emptyList(), false, 60000); return op.execute().handle((integer, throwable) -> { if (throwable != null) { HOTROD.invalidTxServerConfig(cacheName, throwable); } return throwable == null; }); } public static WrappedByteArray wrapBytes(byte[] cacheName) { WrappedByteArray wrappedCacheName; if (cacheName == null || cacheName.length == 0) { wrappedCacheName = WrappedByteArray.EMPTY_BYTES; } else { wrappedCacheName = new WrappedByteArray(cacheName); } return wrappedCacheName; } }
3,743
33.348624
119
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/security/BasicCallbackHandler.java
package org.infinispan.hotrod.impl.security; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.sasl.AuthorizeCallback; import javax.security.sasl.RealmCallback; /** * A basic {@link CallbackHandler}. This can be used for PLAIN and CRAM-MD mechanisms * * @since 14.0 */ public class BasicCallbackHandler implements CallbackHandler { private final String username; private final String realm; private final char[] password; public BasicCallbackHandler() { this(null, null, null); } public BasicCallbackHandler(String username, char[] password) { this(username, null, password); } public BasicCallbackHandler(String username, String realm, char[] password) { this.username = username; this.password = password; this.realm = realm; } public String getUsername() { return username; } public String getRealm() { return realm; } public char[] getPassword() { return password; } @Override public void handle(Callback[] callbacks) throws UnsupportedCallbackException { for (Callback callback : callbacks) { if (callback instanceof NameCallback) { NameCallback nameCallback = (NameCallback) callback; nameCallback.setName(username); } else if (callback instanceof PasswordCallback) { PasswordCallback passwordCallback = (PasswordCallback) callback; passwordCallback.setPassword(password); } else if (callback instanceof AuthorizeCallback) { AuthorizeCallback authorizeCallback = (AuthorizeCallback) callback; authorizeCallback.setAuthorized(authorizeCallback.getAuthenticationID().equals( authorizeCallback.getAuthorizationID())); } else if (callback instanceof RealmCallback) { if (realm == null) throw new UnsupportedCallbackException(callback, "The mech requests a realm, but none has been supplied"); RealmCallback realmCallback = (RealmCallback) callback; realmCallback.setText(realm); } else { throw new UnsupportedCallbackException(callback); } } } }
2,528
34.619718
126
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/security/TokenCallbackHandler.java
package org.infinispan.hotrod.impl.security; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import org.wildfly.security.auth.callback.CredentialCallback; import org.wildfly.security.credential.BearerTokenCredential; /** * @since 14.0 **/ public class TokenCallbackHandler implements CallbackHandler { private volatile String token; public TokenCallbackHandler(String token) { this.token = token; } @Override public void handle(Callback[] callbacks) { for (Callback callback : callbacks) { if (callback instanceof CredentialCallback) { CredentialCallback cc = (CredentialCallback) callback; cc.setCredential(new BearerTokenCredential(token)); } } } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
915
23.756757
66
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/security/VoidCallbackHandler.java
package org.infinispan.hotrod.impl.security; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; /** * * No-op {@link javax.security.auth.callback.CallbackHandler}. Convenient CallbackHandler which comes handy when * no auth. callback is needed. This applies namely to SASL EXTERNAL auth. mechanism when auth. information is obtained * from external channel, like TLS certificate. * * @since 14.0 */ public class VoidCallbackHandler implements CallbackHandler { @Override public void handle(Callback[] callbacks) { // NO-OP } }
604
29.25
119
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/iteration/KeyTracker.java
package org.infinispan.hotrod.impl.iteration; import java.util.Set; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.util.IntSet; /** * @since 14.0 */ public interface KeyTracker { boolean track(byte[] key, short status, ClassAllowList allowList); void segmentsFinished(IntSet finishedSegments); Set<Integer> missedSegments(); }
387
19.421053
69
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/iteration/NoOpSegmentKeyTracker.java
package org.infinispan.hotrod.impl.iteration; import java.util.Set; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.util.IntSet; /** * @since 14.0 */ class NoOpSegmentKeyTracker implements KeyTracker { @Override public boolean track(byte[] key, short status, ClassAllowList allowList) { return true; } @Override public void segmentsFinished(IntSet finishedSegments) { } @Override public Set<Integer> missedSegments() { return null; } }
526
17.821429
77
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/iteration/KeyTrackerFactory.java
package org.infinispan.hotrod.impl.iteration; import java.util.Set; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.consistenthash.ConsistentHash; import org.infinispan.hotrod.impl.consistenthash.SegmentConsistentHash; /** * @since 14.0 */ final class KeyTrackerFactory { private KeyTrackerFactory() { } public static KeyTracker create(DataFormat dataFormat, ConsistentHash hash, int topologyId, Set<Integer> segments) { if (topologyId == -1) return new NoOpSegmentKeyTracker(); if (hash == null) return new ReplKeyTracker(); return new SegmentKeyTracker(dataFormat, (SegmentConsistentHash) hash, segments); } }
682
27.458333
119
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/iteration/SegmentKeyTracker.java
package org.infinispan.hotrod.impl.iteration; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.function.IntConsumer; import java.util.stream.IntStream; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.Util; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.consistenthash.SegmentConsistentHash; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; /** * @since 14.0 */ class SegmentKeyTracker implements KeyTracker { private static final Log log = LogFactory.getLog(SegmentKeyTracker.class); private final AtomicReferenceArray<Set<WrappedByteArray>> keysPerSegment; private final SegmentConsistentHash segmentConsistentHash; private final DataFormat dataFormat; public SegmentKeyTracker(DataFormat dataFormat, SegmentConsistentHash segmentConsistentHash, Set<Integer> segments) { this.dataFormat = dataFormat; int numSegments = segmentConsistentHash.getNumSegments(); keysPerSegment = new AtomicReferenceArray<>(numSegments); if (log.isTraceEnabled()) log.tracef("Created SegmentKeyTracker with %d segments, filter %s", numSegments, segments); this.segmentConsistentHash = segmentConsistentHash; IntStream segmentStream = segments == null ? IntStream.range(0, segmentConsistentHash.getNumSegments()) : segments.stream().mapToInt(i -> i); segmentStream.forEach(i -> keysPerSegment.set(i, new HashSet<>())); } public boolean track(byte[] key, short status, ClassAllowList allowList) { int segment = dataFormat.isObjectStorage() ? segmentConsistentHash.getSegment(dataFormat.keyToObj(key, allowList)) : segmentConsistentHash.getSegment(key); Set<WrappedByteArray> keys = keysPerSegment.get(segment); if (keys == null) throw new IllegalStateException("Segment " + segment + " already completed"); boolean result = keys.add(new WrappedByteArray(key)); if (log.isTraceEnabled()) log.trackingSegmentKey(Util.printArray(key), segment, !result); return result; } public Set<Integer> missedSegments() { int length = keysPerSegment.length(); if (length == 0) return null; Set<Integer> missed = new HashSet<>(length); for (int i = 0; i < keysPerSegment.length(); i++) { if (keysPerSegment.get(i) != null) { missed.add(i); } } return missed; } public void segmentsFinished(IntSet finishedSegments) { if (finishedSegments != null) { if (log.isTraceEnabled()) log.tracef("Removing completed segments %s", finishedSegments); finishedSegments.forEach((IntConsumer) seg -> keysPerSegment.set(seg, null)); } } }
2,977
39.794521
120
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/iteration/RemoteInnerPublisherHandler.java
package org.infinispan.hotrod.impl.iteration; import java.lang.invoke.MethodHandles; import java.net.SocketAddress; import java.util.List; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import org.infinispan.api.common.CacheEntry; import org.infinispan.commons.reactive.AbstractAsyncPublisherHandler; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.logging.TraceException; import org.infinispan.hotrod.exceptions.RemoteIllegalLifecycleStateException; import org.infinispan.hotrod.exceptions.TransportException; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.hotrod.impl.operations.IterationNextResponse; import org.infinispan.hotrod.impl.operations.IterationStartResponse; import io.netty.channel.Channel; class RemoteInnerPublisherHandler<K, E> extends AbstractAsyncPublisherHandler<Map.Entry<SocketAddress, IntSet>, CacheEntry<K, E>, IterationStartResponse, IterationNextResponse<K, E>> { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); protected final RemotePublisher<K, E> publisher; // Need to be volatile since cancel can come on a different thread protected volatile Channel channel; private volatile byte[] iterationId; private AtomicBoolean cancelled = new AtomicBoolean(); protected RemoteInnerPublisherHandler(RemotePublisher<K, E> parent, int batchSize, Supplier<Map.Entry<SocketAddress, IntSet>> supplier, Map.Entry<SocketAddress, IntSet> firstTarget) { super(batchSize, supplier, firstTarget); this.publisher = parent; } private String iterationId() { return publisher.iterationId(iterationId); } @Override protected void sendCancel(Map.Entry<SocketAddress, IntSet> target) { if (!cancelled.getAndSet(true)) { actualCancel(); } } private void actualCancel() { if (iterationId != null && channel != null) { // Just let cancel complete asynchronously publisher.sendCancel(iterationId, channel); } } @Override protected CompletionStage<IterationStartResponse> sendInitialCommand( Map.Entry<SocketAddress, IntSet> target, int batchSize) { SocketAddress address = target.getKey(); IntSet segments = target.getValue(); log.tracef("Starting iteration with segments %s", segments); return publisher.newIteratorStartOperation(address, segments, batchSize); } @Override protected CompletionStage<IterationNextResponse<K, E>> sendNextCommand(Map.Entry<SocketAddress, IntSet> target, int batchSize) { return publisher.newIteratorNextOperation(iterationId, channel); } @Override protected long handleInitialResponse(IterationStartResponse startResponse, Map.Entry<SocketAddress, IntSet> target) { this.channel = startResponse.getChannel(); this.iterationId = startResponse.getIterationId(); if (log.isDebugEnabled()) { log.iterationTransportObtained(channel.remoteAddress(), iterationId()); log.startedIteration(iterationId()); } // We could have been cancelled while the initial response was sent if (cancelled.get()) { actualCancel(); } return 0; } @Override protected long handleNextResponse(IterationNextResponse<K, E> nextResponse, Map.Entry<SocketAddress, IntSet> target) { if (!nextResponse.hasMore()) { // server doesn't clean up when complete sendCancel(target); publisher.completeSegments(target.getValue()); targetComplete(); } IntSet completedSegments = nextResponse.getCompletedSegments(); if (completedSegments != null && log.isTraceEnabled()) { IntSet targetSegments = target.getValue(); if (targetSegments != null) { targetSegments.removeAll(completedSegments); } } publisher.completeSegments(completedSegments); List<CacheEntry<K, E>> entries = nextResponse.getEntries(); for (CacheEntry<K, E> entry : entries) { if (!onNext(entry)) { break; } } return entries.size(); } @Override protected void handleThrowableInResponse(Throwable t, Map.Entry<SocketAddress, IntSet> target) { if (t instanceof TransportException || t instanceof RemoteIllegalLifecycleStateException) { log.throwableDuringPublisher(t); if (log.isTraceEnabled()) { IntSet targetSegments = target.getValue(); if (targetSegments != null) { log.tracef("There are still outstanding segments %s that will need to be retried", targetSegments); } } publisher.erroredServer(target.getKey()); // Try next target if possible targetComplete(); accept(0); } else { t.addSuppressed(new TraceException()); super.handleThrowableInResponse(t, target); } } }
5,099
36.5
131
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/iteration/ReplKeyTracker.java
package org.infinispan.hotrod.impl.iteration; import java.util.HashSet; import java.util.Set; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.util.IntSet; /** * Tracks all keys seen during iteration. Depends on ISPN-5451 to be done more efficiently, by discarding segments as * soon as they are completed iterating. * * @since 14.0 */ class ReplKeyTracker implements KeyTracker { private Set<WrappedByteArray> keys = new HashSet<>(); @Override public boolean track(byte[] key, short status, ClassAllowList allowList) { return keys.add(new WrappedByteArray(key)); } @Override public void segmentsFinished(IntSet finishedSegments) { } @Override public Set<Integer> missedSegments() { return null; } }
852
24.088235
117
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/iteration/RemotePublisher.java
package org.infinispan.hotrod.impl.iteration; import static org.infinispan.hotrod.impl.logging.Log.HOTROD; import java.lang.invoke.MethodHandles; import java.net.SocketAddress; import java.util.AbstractMap; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheOptions; import org.infinispan.commons.reactive.RxJavaInterop; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.consistenthash.SegmentConsistentHash; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.hotrod.impl.operations.CacheOperationsFactory; import org.infinispan.hotrod.impl.operations.IterationEndResponse; import org.infinispan.hotrod.impl.operations.IterationNextOperation; import org.infinispan.hotrod.impl.operations.IterationNextResponse; import org.infinispan.hotrod.impl.operations.IterationStartOperation; import org.infinispan.hotrod.impl.operations.IterationStartResponse; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import io.netty.channel.Channel; import io.reactivex.rxjava3.core.Flowable; public class RemotePublisher<K, E> implements Publisher<CacheEntry<K, E>> { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); private final CacheOperationsFactory cacheOperationsFactory; private final String filterConverterFactory; private final byte[][] filterParams; private final IntSet segments; private final int batchSize; private final boolean metadata; private final DataFormat dataFormat; private final KeyTracker segmentKeyTracker; private final Set<SocketAddress> failedServers = ConcurrentHashMap.newKeySet(); public RemotePublisher(CacheOperationsFactory cacheOperationsFactory, String filterConverterFactory, byte[][] filterParams, Set<Integer> segments, int batchSize, boolean metadata, DataFormat dataFormat) { this.cacheOperationsFactory = cacheOperationsFactory; this.filterConverterFactory = filterConverterFactory; this.filterParams = filterParams; SegmentConsistentHash segmentConsistentHash = (SegmentConsistentHash) cacheOperationsFactory.getConsistentHash(); if (segments == null) { if (segmentConsistentHash != null) { int maxSegment = segmentConsistentHash.getNumSegments(); this.segments = IntSets.concurrentSet(maxSegment); for (int i = 0; i < maxSegment; ++i) { this.segments.set(i); } } else { this.segments = null; } } else { this.segments = IntSets.concurrentCopyFrom(IntSets.from(segments), Collections.max(segments) + 1); } this.batchSize = batchSize; this.metadata = metadata; this.dataFormat = dataFormat; this.segmentKeyTracker = KeyTrackerFactory.create(dataFormat, segmentConsistentHash, cacheOperationsFactory.getTopologyId(), segments); } @Override public void subscribe(Subscriber<? super CacheEntry<K, E>> subscriber) { // Segments can be null if we weren't provided any and we don't have a ConsistentHash if (segments == null) { AtomicBoolean shouldRetry = new AtomicBoolean(true); RemoteInnerPublisherHandler<K, E> innerHandler = new RemoteInnerPublisherHandler<K, E>(this, batchSize, () -> { // Note that this publisher will continue to return empty entries until it has completed a given // target without encountering a Throwable if (shouldRetry.getAndSet(false)) { return new AbstractMap.SimpleImmutableEntry<>(null, null); } return null; }, null) { @Override protected void handleThrowableInResponse(Throwable t, Map.Entry<SocketAddress, IntSet> target) { // Let it retry again if necessary shouldRetry.set(true); super.handleThrowableInResponse(t, target); } }; innerHandler.startPublisher().subscribe(subscriber); return; } Flowable.just(segments) .map(segments -> { Map<SocketAddress, Set<Integer>> segmentsByAddress = cacheOperationsFactory.getPrimarySegmentsByAddress(); Map<SocketAddress, IntSet> actualTargets = new HashMap<>(segmentsByAddress.size()); for (Map.Entry<SocketAddress, Set<Integer>> entry : segmentsByAddress.entrySet()) { SocketAddress targetAddress = entry.getKey(); if (failedServers.contains(targetAddress)) { targetAddress = null; } IntSet segmentsNeeded = null; Set<Integer> targetSegments = entry.getValue(); for (int targetSegment : targetSegments) { if (segments.contains(targetSegment)) { if (segmentsNeeded == null) { segmentsNeeded = IntSets.mutableEmptySet(); } segmentsNeeded.set(targetSegment); } } if (segmentsNeeded != null) { actualTargets.put(targetAddress, segmentsNeeded); } } // If no addresses could handle the segments directly - then just send to any node all segments if (actualTargets.isEmpty()) { actualTargets.put(null, segments); } return actualTargets; }).flatMap(actualTargets -> { int batchSize = (this.batchSize / actualTargets.size()) + 1; return Flowable.fromIterable(actualTargets.entrySet()) .map(entry -> { RemoteInnerPublisherHandler<K, E> innerHandler = new RemoteInnerPublisherHandler<>(this, batchSize, () -> null, entry); return innerHandler.startPublisher(); }).flatMap(RxJavaInterop.identityFunction(), actualTargets.size()); }) .repeatUntil(() -> { log.tracef("Segments left to process are %s", segments); return segments.isEmpty(); }).subscribe(subscriber); } void erroredServer(SocketAddress socketAddress) { failedServers.add(socketAddress); } CompletionStage<Void> sendCancel(byte[] iterationId, Channel channel) { CompletionStage<IterationEndResponse> endResponseStage = cacheOperationsFactory.newIterationEndOperation(iterationId, CacheOptions.DEFAULT, channel).execute(); return endResponseStage.handle((endResponse, t) -> { if (t != null) { HOTROD.ignoringErrorDuringIterationClose(iterationId(iterationId), t); } else { short status = endResponse.getStatus(); if (HotRodConstants.isSuccess(status) && HOTROD.isDebugEnabled()) { HOTROD.iterationClosed(iterationId(iterationId)); } if (HotRodConstants.isInvalidIteration(status)) { throw HOTROD.errorClosingIteration(iterationId(iterationId)); } } return null; }); } String iterationId(byte[] iterationId) { return new String(iterationId, HotRodConstants.HOTROD_STRING_CHARSET); } void completeSegments(IntSet completedSegments) { if (segments != null) { segments.removeAll(completedSegments); } } CompletionStage<IterationStartResponse> newIteratorStartOperation(SocketAddress address, IntSet segments, int batchSize) { IterationStartOperation iterationStartOperation = cacheOperationsFactory.newIterationStartOperation(filterConverterFactory, filterParams, segments, batchSize, metadata, CacheOptions.DEFAULT, dataFormat, address); return iterationStartOperation.execute(); } CompletionStage<IterationNextResponse<K, E>> newIteratorNextOperation(byte[] iterationId, Channel channel) { IterationNextOperation<K, E> iterationNextOperation = cacheOperationsFactory.newIterationNextOperation(iterationId, channel, segmentKeyTracker, CacheOptions.DEFAULT, dataFormat); return iterationNextOperation.execute(); } }
8,781
44.739583
165
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/async/DefaultAsyncExecutorFactory.java
package org.infinispan.hotrod.impl.async; import static org.infinispan.hotrod.impl.logging.Log.HOTROD; import java.util.Properties; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.hotrod.impl.ConfigurationProperties; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.commons.executors.ExecutorFactory; import org.infinispan.commons.executors.NonBlockingResource; /** * Default implementation for {@link org.infinispan.commons.executors.ExecutorFactory} based on an {@link * ThreadPoolExecutor}. * * @since 14.0 */ public class DefaultAsyncExecutorFactory implements ExecutorFactory { public static final String THREAD_NAME = "HotRod-client-async-pool"; private static final Log log = LogFactory.getLog(DefaultAsyncExecutorFactory.class); private static final AtomicInteger factoryCounter = new AtomicInteger(0); private final AtomicInteger threadCounter = new AtomicInteger(0); @Override public ThreadPoolExecutor getExecutor(Properties p) { ConfigurationProperties cp = new ConfigurationProperties(p); int factoryIndex = DefaultAsyncExecutorFactory.factoryCounter.incrementAndGet(); String threadNamePrefix = cp.getDefaultExecutorFactoryThreadNamePrefix(); String threadNameSuffix = cp.getDefaultExecutorFactoryThreadNameSuffix(); ISPNNonBlockingThreadGroup nonBlockingThreadGroup = new ISPNNonBlockingThreadGroup(threadNamePrefix + "-group"); ThreadFactory tf = r -> { int threadIndex = threadCounter.incrementAndGet(); Thread th = new Thread(nonBlockingThreadGroup, r, threadNamePrefix + "-" + factoryIndex + "-" + threadIndex + threadNameSuffix); th.setDaemon(true); return th; }; log.debugf("Creating executor %s-%d", threadNamePrefix, factoryIndex); return new ThreadPoolExecutor(cp.getDefaultExecutorFactoryPoolSize(), cp.getDefaultExecutorFactoryPoolSize(), 0L, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), tf, (r, executor) -> { int poolSize = cp.getDefaultExecutorFactoryPoolSize(); HOTROD.cannotCreateAsyncThread(poolSize); throw new RejectedExecutionException("Too few threads: " + poolSize); }); } static final class ISPNNonBlockingThreadGroup extends ThreadGroup implements NonBlockingResource { ISPNNonBlockingThreadGroup(String name) { super(name); } } }
2,700
43.278689
137
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/logging/Log.java
package org.infinispan.hotrod.impl.logging; import static org.jboss.logging.Logger.Level.DEBUG; import static org.jboss.logging.Logger.Level.ERROR; import static org.jboss.logging.Logger.Level.INFO; import static org.jboss.logging.Logger.Level.TRACE; import static org.jboss.logging.Logger.Level.WARN; import java.lang.reflect.Method; import java.net.SocketAddress; import java.util.Collection; import java.util.List; import java.util.NoSuchElementException; import javax.transaction.xa.Xid; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.CacheListenerException; import org.infinispan.hotrod.configuration.ExhaustedAction; import org.infinispan.hotrod.event.IncorrectClientListenerException; import org.infinispan.hotrod.exceptions.CacheNotTransactionalException; import org.infinispan.hotrod.exceptions.HotRodClientException; import org.infinispan.hotrod.exceptions.InvalidResponseException; import org.infinispan.hotrod.exceptions.TransportException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.Param; import io.netty.channel.Channel; /** * Log abstraction for the hot rod client. For this module, message ids * ranging from 4001 to 5000 inclusively have been reserved. * * @since 14.0 */ @MessageLogger(projectCode = "ISPN") public interface Log extends BasicLogger { String LOG_ROOT = "org.infinispan."; Log HOTROD = Logger.getMessageLogger(Log.class, LOG_ROOT + "HOTROD"); @LogMessage(level = WARN) @Message(value = "Could not find '%s' file in classpath, using defaults.", id = 4001) void couldNotFindPropertiesFile(String propertiesFile); @LogMessage(level = INFO) @Message(value = "Cannot perform operations on a cache associated with an unstarted RemoteCacheManager. Use RemoteCacheManager.start before using the remote cache.", id = 4002) void unstartedRemoteCacheManager(); @Message(value = "Invalid magic number. Expected %#x and received %#x", id = 4003) InvalidResponseException invalidMagicNumber(short expectedMagicNumber, short receivedMagic); // @LogMessage(level = ERROR) // @Message(value = "Invalid message id. Expected %d and received %d", id = 4004) // void invalidMessageId(long expectedMsgId, long receivedMsgId); @LogMessage(level = WARN) @Message(value = "Error received from the server: %s", id = 4005) void errorFromServer(String message); @LogMessage(level = INFO) @Message(value = "Server sent new topology view (id=%d, age=%d) containing %d addresses: %s", id = 4006) void newTopology(int viewId, int age, int topologySize, Collection<? extends SocketAddress> addresses); @LogMessage(level = ERROR) @Message(value = "Exception encountered. Retry %d out of %d", id = 4007) void exceptionAndNoRetriesLeft(int retry, int maxRetries, @Cause Throwable te); // id = 4008 is now logged to TRACE(ISPN-1794) // id = 4009 removed: errorClosingSocket @LogMessage(level = WARN) @Message(value = "No hash function configured for version: %d", id = 4011) void noHasHFunctionConfigured(int hashFunctionVersion); // id = 4012 removed: couldNoInvalidateConnection // id = 4013 removed: couldNotReleaseConnection @LogMessage(level = INFO) @Message(value = "New server added(%s), adding to the pool.", id = 4014) void newServerAdded(SocketAddress server); @LogMessage(level = WARN) @Message(value = "Failed adding new server %s", id = 4015) void failedAddingNewServer(SocketAddress server, @Cause Throwable e); @LogMessage(level = INFO) @Message(value = "Server not in cluster anymore(%s), removing from the pool.", id = 4016) void removingServer(SocketAddress server); // @LogMessage(level = WARN) // @Message(value = "Unable to convert string property [%s] to an int! Using default value of %d", id = 4018) // void unableToConvertStringPropertyToInt(String value, int defaultValue); // // @LogMessage(level = WARN) // @Message(value = "Unable to convert string property [%s] to a long! Using default value of %d", id = 4019) // void unableToConvertStringPropertyToLong(String value, long defaultValue); // // @LogMessage(level = WARN) // @Message(value = "Unable to convert string property [%s] to a boolean! Using default value of %b", id = 4020) // void unableToConvertStringPropertyToBoolean(String value, boolean defaultValue); // @LogMessage(level = INFO) // @Message(value = "Infinispan version: %s", id = 4021) // void version(String version); @Message(value = "SSL Enabled but no TrustStore specified", id = 4024) CacheConfigurationException noSSLTrustManagerConfiguration(); @Message(value = "A password is required to open the KeyStore '%s'", id = 4025) CacheConfigurationException missingKeyStorePassword(String keyStore); @Message(value = "A password is required to open the TrustStore '%s'", id = 4026) CacheConfigurationException missingTrustStorePassword(String trustStore); @Message(value = "Cannot configure custom KeyStore and/or TrustStore when specifying a SSLContext", id = 4027) CacheConfigurationException xorSSLContext(); @Message(value = "Unable to parse server IP address %s", id = 4028) CacheConfigurationException parseErrorServerAddress(String server); @Message(value = "Invalid max_retries (value=%s). Value should be greater or equal than zero.", id = 4029) CacheConfigurationException invalidMaxRetries(int retriesPerServer); @Message(value = "Cannot enable authentication without specifying either a username, a token, a client Subject or a CallbackHandler", id = 4030) CacheConfigurationException invalidAuthenticationConfiguration(); @Message(value = "The selected authentication mechanism '%s' is not among the supported server mechanisms: %s", id = 4031) SecurityException unsupportedMech(String authMech, List<String> serverMechs); // @Message(value = "'%s' is an invalid SASL mechanism", id = 4032) // CacheConfigurationException invalidSaslMechanism(String saslMechanism); // // @Message(value = "Connection dedicated to listener with id=%s but received event for listener with id=%s", id = 4033) // IllegalStateException unexpectedListenerId(String expectedListenerId, String receivedListenerId); @Message(value = "Unable to unmarshall bytes %s", id = 4034) HotRodClientException unableToUnmarshallBytes(String bytes, @Cause Exception e); @Message(value = "Caught exception [%s] while invoking method [%s] on listener instance: %s", id = 4035) CacheListenerException exceptionInvokingListener(String name, Method m, Object target, @Cause Throwable cause); @Message(value = "Methods annotated with %s must accept exactly one parameter, of assignable from type %s", id = 4036) IncorrectClientListenerException incorrectClientListener(String annotationName, Collection<?> allowedParameters); @Message(value = "Methods annotated with %s should have a return type of void.", id = 4037) IncorrectClientListenerException incorrectClientListener(String annotationName); @LogMessage(level = ERROR) @Message(value = "Unexpected error consuming event %s", id = 4038) void unexpectedErrorConsumingEvent(Object event, @Cause Throwable t); @LogMessage(level = WARN) @Message(value = "Unable to complete reading event from server %s", id = 4039) void unableToReadEventFromServer(@Cause Throwable t, SocketAddress server); @Message(value = "Cache listener class %s must be annotated with org.infinispan.hotrod.annotation.ClientListener", id = 4040) IncorrectClientListenerException missingClientListenerAnnotation(String className); @Message(value = "Unknown event type %s received", id = 4041) HotRodClientException unknownEvent(short eventTypeId); @LogMessage(level = ERROR) @Message(value = "Unable to set method %s accessible", id = 4042) void unableToSetAccesible(Method m, @Cause Exception e); // @LogMessage(level = ERROR) // @Message(value = "Unrecoverable error reading event from server %s, exiting listener %s", id = 4043) // void unrecoverableErrorReadingEvent(@Cause Throwable t, SocketAddress server, String listenerId); // // @LogMessage(level = ERROR) // @Message(value = "Unable to read %s bytes %s", id = 4044) // void unableToUnmarshallBytesError(String element, String bytes, @Cause Exception e); @Message(value = "When enabling near caching, number of max entries must be configured", id = 4045) CacheConfigurationException nearCacheMaxEntriesUndefined(); @LogMessage(level = DEBUG) @Message(value = "Successfully closed remote iterator '%s'", id = 4046) void iterationClosed(String iterationId); @Message(value = "Invalid iteration id '%s'", id = 4047) IllegalStateException errorClosingIteration(String iterationId); @Message(value = "Invalid iteration id '%s'", id = 4048) NoSuchElementException errorRetrievingNext(String iterationId); @LogMessage(level = INFO) @Message(value = "Switched to cluster '%s'", id = 4050) void switchedToCluster(String clusterName); @LogMessage(level = INFO) @Message(value = "Switched back to main cluster", id = 4051) void switchedBackToMainCluster(); @LogMessage(level = INFO) @Message(value = "Manually switched to cluster '%s'", id = 4052) void manuallySwitchedToCluster(String clusterName); @LogMessage(level = INFO) @Message(value = "Manually switched back to main cluster", id = 4053) void manuallySwitchedBackToMainCluster(); @Message(value = "Name of the failover cluster needs to be specified", id = 4054) CacheConfigurationException missingClusterNameDefinition(); @Message(value = "Host needs to be specified in server definition of failover cluster", id = 4055) CacheConfigurationException missingHostDefinition(); @Message(value = "At least one server address needs to be specified for failover cluster %s", id = 4056) CacheConfigurationException missingClusterServersDefinition(String siteName); @Message(value = "Duplicate failover cluster %s has been specified", id = 4057) CacheConfigurationException duplicateClusterDefinition(String siteName); @Message(value = "The client listener must use raw data when it uses a query as a filter: %s", id = 4058) IncorrectClientListenerException clientListenerMustUseRawData(String className); @Message(value = "The client listener must use the '%s' filter/converter factory", id = 4059) IncorrectClientListenerException clientListenerMustUseDesignatedFilterConverterFactory(String filterConverterFactoryName); @LogMessage(level = WARN) @Message(value = "Ignoring error when closing iteration '%s'", id = 4061) void ignoringErrorDuringIterationClose(String iterationId, @Cause Throwable e); @LogMessage(level = DEBUG) @Message(value = "Started iteration '%s'", id = 4062) void startedIteration(String iterationId); @LogMessage(level = DEBUG) @Message(value = "Channel to %s obtained for iteration '%s'", id = 4063) void iterationTransportObtained(SocketAddress address, String iterationId); @LogMessage(level = TRACE) @Message(value = "Tracking key %s belonging to segment %d, already tracked? = %b", id = 4064) void trackingSegmentKey(String key, int segment, boolean isTracked); // @LogMessage(level = WARN) // @Message(value = "Classpath does not look correct. Make sure you are not mixing uber and jars", id = 4065) // void warnAboutUberJarDuplicates(); // @LogMessage(level = WARN) // @Message(value = "Unable to convert property [%s] to an enum! Using default value of %d", id = 4066) // void unableToConvertStringPropertyToEnum(String value, String defaultValue); @Message(value = "Cannot specify both a callback handler and a username/token for authentication", id = 4067) CacheConfigurationException callbackHandlerAndUsernameMutuallyExclusive(); // @Message(value = "Class '%s' blocked by Java standard deserialization white list. Adjust the client configuration java serialization white list regular expression to include this class.", id = 4068) // CacheException classNotInWhitelist(String className); @Message(value = "Connection to %s is not active.", id = 4069) TransportException channelInactive(@Param SocketAddress address1, SocketAddress address2); @Message(value = "Failed to add client listener %s, server responded with status %d", id = 4070) HotRodClientException failedToAddListener(Object listener, short status); @Message(value = "Connection to %s was closed while waiting for response.", id = 4071) TransportException connectionClosed(@Param SocketAddress address1, SocketAddress address2); @LogMessage(level = ERROR) @Message(value = "Cannot create another async thread. Please increase 'infinispan.client.hotrod.default_executor_factory.pool_size' (current value is %d).", id = 4072) void cannotCreateAsyncThread(int maxPoolSize); // @LogMessage(level = WARN) // @Message(value = "TransportFactory is deprecated, this setting is not used anymore.", id = 4073) // void transportFactoryDeprecated(); @LogMessage(level = INFO) @Message(value = "Native Epoll transport not available, using NIO instead: %s", id = 4074) void epollNotAvailable(String cause); @Message(value = "TrustStoreFileName and TrustStorePath are mutually exclusive", id = 4075) CacheConfigurationException trustStoreFileAndPathExclusive(); @Message(value = "Unknown message id %d; cannot find matching request", id = 4076) IllegalStateException unknownMessageId(long messageId); @Message(value = "Closing channel %s due to error in unknown operation.", id = 4077) TransportException errorFromUnknownOperation(Channel channel, @Cause Throwable cause, @Param SocketAddress address); @Message(value = "This channel is about to be closed and does not accept any further operations.", id = 4078) HotRodClientException noMoreOperationsAllowed(); @Message(value = "Unexpected listenerId %s", id = 4079) IllegalStateException unexpectedListenerId(String listenerId); @Message(value = "Event should use messageId of previous Add Client Listener operation but id is %d and operation is %s", id = 4080) IllegalStateException operationIsNotAddClientListener(long messageId, String operation); @Message(value = "TransactionMode must be non-null.", id = 4082) CacheConfigurationException invalidTransactionMode(); @Message(value = "TransactionManagerLookup must be non-null", id = 4083) CacheConfigurationException invalidTransactionManagerLookup(); @Message(value = "Cache %s doesn't support transactions. Please check the documentation how to configure it properly.", id = 4084) CacheNotTransactionalException cacheDoesNotSupportTransactions(String name); @LogMessage(level = ERROR) @Message(value = "Error checking server configuration for transactional cache %s", id = 4085) void invalidTxServerConfig(String name, @Cause Throwable throwable); @LogMessage(level = WARN) @Message(value = "Exception caught while preparing transaction %s", id = 4086) void exceptionDuringPrepare(Xid xid, @Cause Exception e); @LogMessage(level = WARN) @Message(value = "Use of maxIdle expiration with a near cache is unsupported.", id = 4087) void nearCacheMaxIdleUnsupported(); @Message(value = "Transactions timeout must be positive", id = 4088) HotRodClientException invalidTransactionTimeout(); @Message(value = "TransactionTable is not started!", id = 4089) HotRodClientException transactionTableNotStarted(); @Message(value = "[%s] Invalid response operation. Expected %#x and received %#x", id = 4090) InvalidResponseException invalidResponse(String cacheName, short opRespCode, double receivedOpCode); @Message(value = "MBean registration failed", id = 4091) HotRodClientException jmxRegistrationFailure(@Cause Throwable cause); @Message(value = "MBean unregistration failed", id = 4092) HotRodClientException jmxUnregistrationFailure(@Cause Throwable cause); @Message(value = "OAUTHBEARER mechanism selected without providing a token", id = 4093) CacheConfigurationException oauthBearerWithoutToken(); @Message(value = "Cannot specify both template name and configuration for '%s'", id = 4094) CacheConfigurationException remoteCacheTemplateNameXorConfiguration(String name); @Message(value = "Not a Hot Rod URI: %s", id = 4095) IllegalArgumentException notaHotRodURI(String uri); @Message(value = "Invalid property format in URI: %s", id = 4096) IllegalArgumentException invalidPropertyFormat(String part); @Message(value = "Illegal attempt to redefine an already existing cache configuration: %s", id = 4097) IllegalArgumentException duplicateCacheConfiguration(String name); @LogMessage(level = WARN) @Message(value = "Closing connection %s due to transport error", id = 4098) void closingChannelAfterError(Channel channel, @Cause Throwable t); @LogMessage(level = WARN) @Message(value = "Remote iteration over the entire result set of query '%s' without using pagination options is inefficient for large result sets. Please consider using 'startOffset' and 'maxResults' options.", id = 4099) void warnPerfRemoteIterationWithoutPagination(String query); @LogMessage(level = WARN) @Message(value = "Error reaching the server during iteration", id = 4100) void throwableDuringPublisher(@Cause Throwable t); @LogMessage(level = WARN) @Message(value = "Configuration property '%s' has been deprecated", id = 4101) void deprecatedConfigurationProperty(String property); @Message(value = "Near cache number of max entries must be a positive number when using bloom filter optimization, it was %d", id = 4102) CacheConfigurationException nearCacheMaxEntriesPositiveWithBloom(int maxEntries); @Message(value = "Near cache with bloom filter requires pool max active to be 1, was %s, and exhausted action to be WAIT, was %s", id = 4103) CacheConfigurationException bloomFilterRequiresMaxActiveOneAndWait(int maxActive, ExhaustedAction action); @LogMessage(level = WARN) @Message(value = "Failed to load and create an optional ProtoStream serialization context initializer: %s", id = 4104) void failedToCreatePredefinedSerializationContextInitializer(String className, @Cause Throwable throwable); @LogMessage(level = WARN) @Message(value = "Reverting to the initial server list for caches %s", id = 4105) void revertCacheToInitialServerList(Collection<String> cacheName); @LogMessage(level = WARN) @Message(value = "Invalid active count after closing channel %s", id = 4106) void invalidActiveCountAfterClose(Channel channel); @LogMessage(level = WARN) @Message(value = "Invalid created count after closing channel %s", id = 4107) void invalidCreatedCountAfterClose(Channel channel); @LogMessage(level = INFO) @Message(value = "Native IOUring transport not available, using NIO instead: %s", id = 4108) void ioUringNotAvailable(String cause); @LogMessage(level = DEBUG) @Message(value = "OpenTelemetry API is not present in the classpath. Client context tracing will not be propagated.", id = 4109) void noOpenTelemetryAPI(@Cause Throwable throwable); }
19,491
48.472081
224
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/logging/LogFactory.java
package org.infinispan.hotrod.impl.logging; import org.jboss.logging.Logger; /** * Factory that creates {@link Log} instances. * * @since 14.0 */ public class LogFactory { public static Log getLog(Class<?> clazz) { return Logger.getMessageLogger(Log.class, clazz.getName()); } public static <T> T getLog(Class<?> clazz, Class<T> logClass) { return Logger.getMessageLogger(logClass, clazz.getName()); } }
437
19.857143
66
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/TopologyInfo.java
package org.infinispan.hotrod.impl.cache; import static org.infinispan.hotrod.impl.Util.wrapBytes; import static org.infinispan.hotrod.impl.logging.Log.HOTROD; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.BiConsumer; import java.util.function.Supplier; import java.util.stream.Collectors; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.marshall.WrappedBytes; import org.infinispan.hotrod.configuration.FailoverRequestBalancingStrategy; import org.infinispan.hotrod.configuration.HotRodConfiguration; import org.infinispan.hotrod.impl.consistenthash.ConsistentHashFactory; import org.infinispan.hotrod.impl.consistenthash.SegmentConsistentHash; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.topology.CacheInfo; import org.infinispan.hotrod.impl.topology.ClusterInfo; import net.jcip.annotations.NotThreadSafe; /** * Maintains topology information about caches. * */ @NotThreadSafe public final class TopologyInfo { private static final Log log = LogFactory.getLog(TopologyInfo.class, Log.class); private final Supplier<FailoverRequestBalancingStrategy> balancerFactory; private final ConsistentHashFactory hashFactory = new ConsistentHashFactory(); private final ConcurrentMap<WrappedBytes, CacheInfo> caches = new ConcurrentHashMap<>(); private volatile ClusterInfo cluster; public TopologyInfo(HotRodConfiguration configuration, ClusterInfo clusterInfo) { this.balancerFactory = configuration.balancingStrategyFactory(); this.hashFactory.init(configuration); this.cluster = clusterInfo.withTopologyAge(0); } public Map<SocketAddress, Set<Integer>> getPrimarySegmentsByServer(byte[] cacheName) { WrappedByteArray key = wrapBytes(cacheName); CacheInfo cacheInfo = caches.get(key); if (cacheInfo != null) { return cacheInfo.getPrimarySegments(); } else { return Collections.emptyMap(); } } public List<InetSocketAddress> getServers(WrappedBytes cacheName) { return getCacheInfo(cacheName).getServers(); } public Collection<InetSocketAddress> getAllServers() { return caches.values().stream().flatMap(ct -> ct.getServers().stream()).collect(Collectors.toSet()); } public SegmentConsistentHash createConsistentHash(int numSegments, short hashFunctionVersion, SocketAddress[][] segmentOwners) { SegmentConsistentHash hash = null; if (hashFunctionVersion > 0) { hash = hashFactory.newConsistentHash(hashFunctionVersion); if (hash == null) { HOTROD.noHasHFunctionConfigured(hashFunctionVersion); } else { hash.init(segmentOwners, numSegments); } } return hash; } public ConsistentHashFactory getConsistentHashFactory() { return hashFactory; } public CacheTopologyInfo getCacheTopologyInfo(byte[] cacheName) { WrappedByteArray key = wrapBytes(cacheName); return caches.get(key).getCacheTopologyInfo(); } public CacheInfo getCacheInfo(WrappedBytes cacheName) { return caches.get(cacheName); } public CacheInfo getOrCreateCacheInfo(WrappedBytes cacheName) { return caches.computeIfAbsent(cacheName, cn -> { // TODO Do we still need locking, in case the cluster switch iteration misses this cache? ClusterInfo cluster = this.cluster; CacheInfo cacheInfo = new CacheInfo(cn, balancerFactory.get(), cluster.getTopologyAge(), cluster.getInitialServers(), cluster.getIntelligence()); cacheInfo.updateBalancerServers(); if (log.isTraceEnabled()) log.tracef("Creating cache info %s with topology age %d", cacheInfo.getCacheName(), cluster.getTopologyAge()); return cacheInfo; }); } /** * Switch to another cluster and update the topologies of all caches with its initial server list. */ public void switchCluster(ClusterInfo newCluster) { ClusterInfo oldCluster = this.cluster; int newTopologyAge = oldCluster.getTopologyAge() + 1; if (log.isTraceEnabled()) { log.tracef("Switching cluster: %s -> %s with servers %s", oldCluster.getName(), newCluster.getName(), newCluster.getInitialServers()); } // Stop accepting topology updates from old requests caches.forEach((name, oldCacheInfo) -> { CacheInfo newCacheInfo = oldCacheInfo.withNewServers(newTopologyAge, HotRodConstants.SWITCH_CLUSTER_TOPOLOGY, newCluster.getInitialServers(), newCluster.getIntelligence()); updateCacheInfo(name, oldCacheInfo, newCacheInfo); }); // Update the topology age for new requests so that the topology updates from their responses are accepted this.cluster = newCluster.withTopologyAge(newTopologyAge); } /** * Reset a single ache to the initial server list. * * <p>Useful if there are still live servers in the cluster, but all the server in this cache's * current topology are unreachable.</p> */ public void reset(WrappedBytes cacheName) { if (log.isTraceEnabled()) log.tracef("Switching to initial server list for cache %s, cluster %s", cacheName, cluster.getName()); CacheInfo oldCacheInfo = caches.get(cacheName); CacheInfo newCacheInfo = oldCacheInfo.withNewServers(cluster.getTopologyAge(), HotRodConstants.DEFAULT_CACHE_TOPOLOGY, cluster.getInitialServers(), cluster.getIntelligence()); updateCacheInfo(cacheName, oldCacheInfo, newCacheInfo); } public ClusterInfo getCluster() { return cluster; } public int getTopologyAge() { return cluster.getTopologyAge(); } public void updateCacheInfo(WrappedBytes cacheName, CacheInfo oldCacheInfo, CacheInfo newCacheInfo) { if (log.isTraceEnabled()) log.tracef("Updating topology for %s: %s -> %s", newCacheInfo.getCacheName(), oldCacheInfo.getTopologyId(), newCacheInfo.getTopologyId()); CacheInfo existing = caches.put(cacheName, newCacheInfo); assert existing == oldCacheInfo : "Locking should have prevented concurrent updates"; // The new CacheInfo doesn't have a new balancer instance, so the server update affects both newCacheInfo.updateBalancerServers(); // Update the topology id for new requests newCacheInfo.updateClientTopologyRef(); } public void forEachCache(BiConsumer<WrappedBytes, CacheInfo> action) { caches.forEach(action); } }
7,186
40.068571
154
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/Versioned.java
package org.infinispan.hotrod.impl.cache; /** * Versioned * @since 14.0 */ public interface Versioned { long getVersion(); }
131
13.666667
41
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/VersionedValueImpl.java
package org.infinispan.hotrod.impl.cache; /** * @since 14.0 */ public class VersionedValueImpl<V> implements VersionedValue<V> { private long version; private V value; public VersionedValueImpl(long version, V value) { this.version = version; this.value = value; } @Override public long getVersion() { return version; } @Override public V getValue() { return value; } @Override public String toString() { return "VersionedValueImpl{" + "version=" + version + ", value=" + value + '}'; } }
603
16.257143
65
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/RemoteCacheImpl.java
package org.infinispan.hotrod.impl.cache; import static org.infinispan.hotrod.impl.logging.Log.HOTROD; import java.net.SocketAddress; import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Flow; import java.util.stream.Collectors; import jakarta.transaction.TransactionManager; import org.infinispan.api.async.AsyncCacheEntryProcessor; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryVersion; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.api.common.events.cache.CacheEntryEvent; import org.infinispan.api.common.events.cache.CacheEntryEventType; import org.infinispan.api.common.events.cache.CacheListenerOptions; import org.infinispan.api.common.process.CacheEntryProcessorResult; import org.infinispan.api.common.process.CacheProcessorOptions; import org.infinispan.api.configuration.CacheConfiguration; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.Closeables; import org.infinispan.commons.util.Util; import org.infinispan.hotrod.exceptions.RemoteCacheManagerNotStartedException; import org.infinispan.hotrod.filter.Filters; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.HotRodTransport; import org.infinispan.hotrod.impl.iteration.RemotePublisher; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.hotrod.impl.operations.CacheOperationsFactory; import org.infinispan.hotrod.impl.operations.ClearOperation; import org.infinispan.hotrod.impl.operations.GetAllParallelOperation; import org.infinispan.hotrod.impl.operations.GetAndRemoveOperation; import org.infinispan.hotrod.impl.operations.GetOperation; import org.infinispan.hotrod.impl.operations.GetWithMetadataOperation; import org.infinispan.hotrod.impl.operations.PingResponse; import org.infinispan.hotrod.impl.operations.PutAllParallelOperation; import org.infinispan.hotrod.impl.operations.PutIfAbsentOperation; import org.infinispan.hotrod.impl.operations.PutOperation; import org.infinispan.hotrod.impl.operations.RemoveIfUnmodifiedOperation; import org.infinispan.hotrod.impl.operations.RemoveOperation; import org.infinispan.hotrod.impl.operations.ReplaceIfUnmodifiedOperation; import org.infinispan.hotrod.impl.operations.RetryAwareCompletionStage; import org.infinispan.hotrod.impl.operations.SetIfAbsentOperation; import org.infinispan.hotrod.impl.operations.SetOperation; import org.infinispan.hotrod.near.NearCacheService; import org.reactivestreams.FlowAdapters; import org.reactivestreams.Publisher; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Maybe; import io.reactivex.rxjava3.core.Single; /** * @author Mircea.Markus@jboss.com * @since 4.1 */ public class RemoteCacheImpl<K, V> implements RemoteCache<K, V> { private static final Log log = LogFactory.getLog(RemoteCacheImpl.class, Log.class); private final String name; private final HotRodTransport hotRodTransport; private final CacheOperationsFactory cacheOperationsFactory; private volatile boolean isObjectStorage; private final DataFormat dataFormat; private final ClientStatistics clientStatistics; public RemoteCacheImpl(HotRodTransport hotRodTransport, String name, TimeService timeService, NearCacheService<K, V> nearCacheService) { this(hotRodTransport, name, new ClientStatistics(hotRodTransport.getConfiguration().statistics().enabled(), timeService, nearCacheService), DataFormat.builder().build()); hotRodTransport.getMBeanHelper().register(this); } private RemoteCacheImpl(RemoteCacheImpl<?, ?> instance, DataFormat dataFormat) { this(instance.hotRodTransport, instance.name, instance.clientStatistics, dataFormat); } private RemoteCacheImpl(HotRodTransport hotRodTransport, String name, ClientStatistics clientStatistics, DataFormat dataFormat) { this.name = name; this.hotRodTransport = hotRodTransport; this.dataFormat = dataFormat; this.clientStatistics = clientStatistics; this.cacheOperationsFactory = hotRodTransport.createCacheOperationFactory(name, clientStatistics); } @Override public String getName() { return name; } @Override public DataFormat getDataFormat() { return dataFormat; } @Override public CompletionStage<CacheConfiguration> configuration() { throw new UnsupportedOperationException(); } @Override public HotRodTransport getHotRodTransport() { return hotRodTransport; } @Override public CacheOperationsFactory getOperationsFactory() { return cacheOperationsFactory; } @Override public CompletionStage<V> get(K key, CacheOptions options) { byte[] keyBytes = keyToBytes(key); GetOperation<K, V> gco = cacheOperationsFactory.newGetKeyOperation(keyAsObjectIfNeeded(key), keyBytes, options, dataFormat); CompletionStage<V> result = gco.execute(); if (log.isTraceEnabled()) { result.thenAccept(value -> log.tracef("For key(%s) returning %s", key, value)); } return result; } @Override public K keyAsObjectIfNeeded(Object key) { return isObjectStorage ? (K) key : null; } @Override public void close() { hotRodTransport.getMBeanHelper().unregister(this); } @Override public SocketAddress addNearCacheListener(Object listener, int bloomBits) { throw new UnsupportedOperationException("Adding a near cache listener to a RemoteCache is not supported!"); } private byte[][] marshallParams(Object[] params) { if (params == null) return org.infinispan.commons.util.Util.EMPTY_BYTE_ARRAY_ARRAY; byte[][] marshalledParams = new byte[params.length][]; for (int i = 0; i < marshalledParams.length; i++) { byte[] bytes = keyToBytes(params[i]);// should be small marshalledParams[i] = bytes; } return marshalledParams; } public CompletionStage<PingResponse> ping() { return cacheOperationsFactory.newFaultTolerantPingOperation().execute(); } @Override public byte[] keyToBytes(Object o) { return dataFormat.keyToBytes(o); } @Override public byte[] valueToBytes(Object o) { return dataFormat.valueToBytes(o); } @Override public RetryAwareCompletionStage<CacheEntry<K, V>> getEntry(K key, CacheOptions options) { GetWithMetadataOperation<K, V> op = cacheOperationsFactory.newGetWithMetadataOperation(keyAsObjectIfNeeded(key), keyToBytes(key), options, dataFormat); return op.internalExecute(); } @Override public RetryAwareCompletionStage<CacheEntry<K, V>> getEntry(K key, CacheOptions options, SocketAddress listenerAddress) { GetWithMetadataOperation<K, V> op = cacheOperationsFactory.newGetWithMetadataOperation(keyAsObjectIfNeeded(key), keyToBytes(key), options, dataFormat, listenerAddress); return op.internalExecute(); } @Override public CompletionStage<CacheEntry<K, V>> putIfAbsent(K key, V value, CacheWriteOptions options) { PutIfAbsentOperation<K, V> op = cacheOperationsFactory.newPutIfAbsentOperation(keyAsObjectIfNeeded(key), keyToBytes(key), valueToBytes(value), options, dataFormat); return op.execute(); } @Override public CompletionStage<Boolean> setIfAbsent(K key, V value, CacheWriteOptions options) { SetIfAbsentOperation<K> op = cacheOperationsFactory.newSetIfAbsentOperation(keyAsObjectIfNeeded(key), keyToBytes(key), valueToBytes(value), options, dataFormat); return op.execute(); } @Override public CompletionStage<CacheEntry<K, V>> put(K key, V value, CacheWriteOptions options) { PutOperation<K, V> op = cacheOperationsFactory.newPutKeyValueOperation(keyAsObjectIfNeeded(key), keyToBytes(key), valueToBytes(value), options, dataFormat); return op.execute(); } @Override public CompletionStage<Void> set(K key, V value, CacheWriteOptions options) { SetOperation<K> op = cacheOperationsFactory.newSetKeyValueOperation(keyAsObjectIfNeeded(key), keyToBytes(key), valueToBytes(value), options, dataFormat); return op.execute(); } @Override public CompletionStage<CacheEntry<K, V>> getAndRemove(K key, CacheOptions options) { GetAndRemoveOperation<K, V> op = cacheOperationsFactory.newGetAndRemoveOperation(keyAsObjectIfNeeded(key), keyToBytes(key), options, dataFormat); return op.execute(); } @Override public CompletionStage<Boolean> replace(K key, V value, CacheEntryVersion version, CacheWriteOptions options) { if (!(Objects.requireNonNull(version) instanceof CacheEntryVersionImpl)) { throw new IllegalArgumentException("Only CacheEntryVersionImpl instances are supported!"); } ReplaceIfUnmodifiedOperation<K, V> op = cacheOperationsFactory.newReplaceIfUnmodifiedOperation(keyAsObjectIfNeeded(key), keyToBytes(key), valueToBytes(value), ((CacheEntryVersionImpl) version).version(), options, dataFormat); // TODO: add new op to prevent requiring return value? return op.execute().thenApply(r -> r.getCode().isUpdated()); } @Override public CompletionStage<CacheEntry<K, V>> getOrReplaceEntry(K key, V value, CacheEntryVersion version, CacheWriteOptions options) { if (!(Objects.requireNonNull(version) instanceof CacheEntryVersionImpl)) { throw new IllegalArgumentException("Only CacheEntryVersionImpl instances are supported!"); } ReplaceIfUnmodifiedOperation<K, V> op = cacheOperationsFactory.newReplaceIfUnmodifiedOperation(keyAsObjectIfNeeded(key), keyToBytes(key), valueToBytes(value), ((CacheEntryVersionImpl) version).version(), options, dataFormat); return op.execute().thenApply(r -> { if (r.getCode().isUpdated()) { return null; } return r.getValue(); }); } @Override public CompletionStage<Boolean> remove(K key, CacheOptions options) { RemoveOperation<K> op = cacheOperationsFactory.newRemoveOperation(keyAsObjectIfNeeded(key), keyToBytes(key), options, dataFormat); return op.execute(); } @Override public CompletionStage<Boolean> remove(K key, CacheEntryVersion version, CacheOptions options) { if (!(Objects.requireNonNull(version) instanceof CacheEntryVersionImpl)) { throw new IllegalArgumentException("Only CacheEntryVersionImpl instances are supported!"); } RemoveIfUnmodifiedOperation<K, V> op = cacheOperationsFactory.newRemoveIfUnmodifiedOperation(key, keyToBytes(key), ((CacheEntryVersionImpl) version).version(), options, dataFormat); // TODO: add new op to prevent requiring return value? return op.execute().thenApply(r -> r.getValue() != null); } @Override public Flow.Publisher<K> keys(CacheOptions options) { assertRemoteCacheManagerIsStarted(); Flowable<K> flowable = Flowable.fromPublisher(new RemotePublisher<K, Object>(cacheOperationsFactory, "org.infinispan.server.hotrod.HotRodServer$ToEmptyBytesKeyValueFilterConverter", Util.EMPTY_BYTE_ARRAY_ARRAY, null, 128, false, dataFormat)) .map(CacheEntry::key); return FlowAdapters.toFlowPublisher(flowable); } @Override public Flow.Publisher<CacheEntry<K, V>> entries(CacheOptions options) { assertRemoteCacheManagerIsStarted(); return FlowAdapters.toFlowPublisher(new RemotePublisher<>(cacheOperationsFactory, null, Util.EMPTY_BYTE_ARRAY_ARRAY, null, 128, false, dataFormat)); } @Override public CompletionStage<Void> putAll(Map<K, V> entries, CacheWriteOptions options) { PutAllParallelOperation putAllParallelOperation = cacheOperationsFactory.newPutAllOperation( entries.entrySet().stream().collect(Collectors.toMap(node -> keyToBytes(node.getKey()), node -> valueToBytes(node.getValue()))), options, dataFormat); return putAllParallelOperation.execute(); } @Override public CompletionStage<Void> putAll(Flow.Publisher<CacheEntry<K, V>> entries, CacheWriteOptions options) { // TODO: this ignores the metadata, however expiration is part of options... is that okay? return Flowable.fromPublisher(FlowAdapters.toPublisher(entries)) .collect(Collectors.toMap(CacheEntry::key, CacheEntry::value)) .concatMapCompletable(map -> Completable.fromCompletionStage(putAll(map, options))) .toCompletionStage(null); } @Override public Flow.Publisher<CacheEntry<K, V>> getAll(Set<K> keys, CacheOptions options) { GetAllParallelOperation<K, V> op = cacheOperationsFactory.newGetAllOperation(keys.stream().map(this::keyToBytes).collect(Collectors.toSet()), options, dataFormat); Flowable<CacheEntry<K, V>> flowable = Flowable.defer(() -> Flowable.fromCompletionStage(op.execute()) .concatMapIterable(Map::entrySet) // TODO: need to worry about metadata .map(e -> new CacheEntryImpl<>(e.getKey(), e.getValue(), null))); return FlowAdapters.toFlowPublisher(flowable); } @Override public Flow.Publisher<CacheEntry<K, V>> getAll(CacheOptions options, K[] keys) { GetAllParallelOperation<K, V> op = cacheOperationsFactory.newGetAllOperation(Arrays.stream(keys).map(this::keyToBytes).collect(Collectors.toSet()), options, dataFormat); Flowable<CacheEntry<K, V>> flowable = Flowable.defer(() -> Flowable.fromCompletionStage(op.execute()) .concatMapIterable(Map::entrySet) // TODO: need to worry about metadata .map(e -> new CacheEntryImpl<>(e.getKey(), e.getValue(), null))); return FlowAdapters.toFlowPublisher(flowable); } private Flow.Publisher<K> removeAll(Flowable<K> keys, CacheWriteOptions options) { Flowable<K> keyFlowable = keys.concatMapMaybe(k -> Single.fromCompletionStage(remove(k, options)).mapOptional(removed -> removed ? Optional.of(k) : Optional.empty())); return FlowAdapters.toFlowPublisher(keyFlowable); } @Override public Flow.Publisher<K> removeAll(Set<K> keys, CacheWriteOptions options) { return removeAll(Flowable.fromIterable(keys), options); } @Override public Flow.Publisher<K> removeAll(Flow.Publisher<K> keys, CacheWriteOptions options) { return removeAll(Flowable.fromPublisher(FlowAdapters.toPublisher(keys)), options); } private Flow.Publisher<CacheEntry<K, V>> getAndRemoveAll(Flowable<K> keys, CacheWriteOptions options) { // TODO: eventually support a batch getAndRemoveAll by owner Flowable<CacheEntry<K, V>> entryFlowable = keys .concatMapMaybe(k -> Maybe.fromCompletionStage(getAndRemove(k, options))); return FlowAdapters.toFlowPublisher(entryFlowable); } @Override public Flow.Publisher<CacheEntry<K, V>> getAndRemoveAll(Set<K> keys, CacheWriteOptions options) { return getAndRemoveAll(Flowable.fromIterable(keys), options); } @Override public Flow.Publisher<CacheEntry<K, V>> getAndRemoveAll(Flow.Publisher<K> keys, CacheWriteOptions options) { return getAndRemoveAll(Flowable.fromPublisher(FlowAdapters.toPublisher(keys)), options); } @Override public CompletionStage<Long> estimateSize(CacheOptions options) { throw new UnsupportedOperationException(); } @Override public CompletionStage<Void> clear(CacheOptions options) { // Currently, no options are used by clear (what about timeout?) ClearOperation op = cacheOperationsFactory.newClearOperation(); return op.execute(); } @Override public Flow.Publisher<CacheEntryEvent<K, V>> listen(CacheListenerOptions options, CacheEntryEventType[] types) { throw new UnsupportedOperationException(); } @Override public <T> Flow.Publisher<CacheEntryProcessorResult<K, T>> process(Set<K> keys, AsyncCacheEntryProcessor<K, V, T> task, CacheOptions options) { throw new UnsupportedOperationException(); } @Override public <T> Flow.Publisher<CacheEntryProcessorResult<K, T>> processAll(AsyncCacheEntryProcessor<K, V, T> processor, CacheProcessorOptions options) { throw new UnsupportedOperationException(); } protected void assertRemoteCacheManagerIsStarted() { if (!hotRodTransport.isStarted()) { String message = "Cannot perform operations on a cache associated with an unstarted RemoteCacheManager. Use RemoteCacheManager.start before using the remote cache."; HOTROD.unstartedRemoteCacheManager(); throw new RemoteCacheManagerNotStartedException(message); } } @Override public <K1, V1> RemoteCache<K1, V1> withDataFormat(DataFormat newDataFormat) { Objects.requireNonNull(newDataFormat, "Data Format must not be null").initialize(hotRodTransport, name, isObjectStorage); return new RemoteCacheImpl<K1, V1>(this, newDataFormat); } @Override public void resolveStorage(boolean objectStorage) { this.isObjectStorage = objectStorage; this.dataFormat.initialize(hotRodTransport, name, isObjectStorage); } public boolean isObjectStorage() { return isObjectStorage; } @Override public CompletionStage<Void> updateBloomFilter() { return CompletableFuture.completedFuture(null); } @Override public String toString() { return "RemoteCacheImpl " + name; } public ClientStatistics getClientStatistics() { return clientStatistics; } @Override public CloseableIterator<CacheEntry<Object, Object>> retrieveEntries(String filterConverterFactory, Object[] filterConverterParams, Set<Integer> segments, int batchSize) { Publisher<CacheEntry<K, Object>> remotePublisher = publishEntries(filterConverterFactory, filterConverterParams, segments, batchSize); //noinspection unchecked return Closeables.iterator((Publisher) remotePublisher, batchSize); } @Override public <E> Publisher<CacheEntry<K, E>> publishEntries(String filterConverterFactory, Object[] filterConverterParams, Set<Integer> segments, int batchSize) { assertRemoteCacheManagerIsStarted(); if (segments != null && segments.isEmpty()) { return Flowable.empty(); } byte[][] params = marshallParams(filterConverterParams); return new RemotePublisher<>(cacheOperationsFactory, filterConverterFactory, params, segments, batchSize, false, dataFormat); } @Override public CloseableIterator<CacheEntry<Object, Object>> retrieveEntriesByQuery(RemoteQuery query, Set<Integer> segments, int batchSize) { Publisher<CacheEntry<K, Object>> remotePublisher = publishEntriesByQuery(query, segments, batchSize); //noinspection unchecked return Closeables.iterator((Publisher) remotePublisher, batchSize); } @Override public <E> Publisher<CacheEntry<K, E>> publishEntriesByQuery(RemoteQuery query, Set<Integer> segments, int batchSize) { return publishEntries(Filters.ITERATION_QUERY_FILTER_CONVERTER_FACTORY_NAME, query.toFactoryParams(), segments, batchSize); } @Override public CloseableIterator<CacheEntry<Object, Object>> retrieveEntriesWithMetadata(Set<Integer> segments, int batchSize) { Publisher<CacheEntry<K, V>> remotePublisher = publishEntriesWithMetadata(segments, batchSize); //noinspection unchecked return Closeables.iterator((Publisher) remotePublisher, batchSize); } @Override public Publisher<CacheEntry<K, V>> publishEntriesWithMetadata(Set<Integer> segments, int batchSize) { return new RemotePublisher<>(cacheOperationsFactory, null, null, segments, batchSize, true, dataFormat); } @Override public TransactionManager getTransactionManager() { throw new UnsupportedOperationException(); } @Override public boolean isTransactional() { return false; } }
20,248
42.359743
176
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/VersionedValue.java
package org.infinispan.hotrod.impl.cache; /** * Besides the key and value, also contains an version. To be used in versioned operations, e.g. {@link * RemoteCache#removeWithVersion(Object, long)}. * */ public interface VersionedValue<V> extends Versioned { V getValue(); }
282
22.583333
103
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/MBeanHelper.java
package org.infinispan.hotrod.impl.cache; import static org.infinispan.hotrod.impl.logging.Log.HOTROD; import java.util.HashMap; import java.util.Map; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.hotrod.configuration.StatisticsConfiguration; import org.infinispan.hotrod.impl.HotRodTransport; /** * @since 14.0 **/ public interface MBeanHelper extends AutoCloseable { void register(RemoteCacheImpl<?, ?> remoteCache); void unregister(RemoteCacheImpl<?, ?> remoteCache); void close(); static MBeanHelper getInstance(HotRodTransport transport) { if (transport.getConfiguration().statistics().jmxEnabled()) { return new Impl(transport); } else { return new NoOp(); } } class Impl implements MBeanHelper { private final MBeanServer mBeanServer; private final ObjectName transportMBean; private final Map<String, ObjectName> cacheMBeans = new HashMap<>(); Impl(HotRodTransport transport) { StatisticsConfiguration configuration = transport.getConfiguration().statistics(); try { mBeanServer = configuration.mbeanServerLookup().getMBeanServer(); transportMBean = new ObjectName(String.format("%s:type=HotRodClient,name=%s", configuration.jmxDomain(), configuration.jmxName())); mBeanServer.registerMBean(this, transportMBean); } catch (Exception e) { throw HOTROD.jmxRegistrationFailure(e); } } @Override public void close() { unregister(transportMBean); } public void register(RemoteCacheImpl<?, ?> remoteCache) { StatisticsConfiguration configuration = remoteCache.getHotRodTransport().getConfiguration().statistics(); try { ObjectName mbeanObjectName = new ObjectName(String.format("%s:type=HotRodClient,name=%s,cache=%s", transportMBean.getDomain(), configuration.jmxName(), remoteCache.getName())); mBeanServer.registerMBean(remoteCache.getClientStatistics(), mbeanObjectName); cacheMBeans.put(remoteCache.getName(), mbeanObjectName); } catch (Exception e) { throw HOTROD.jmxRegistrationFailure(e); } } public void unregister(RemoteCacheImpl<?, ?> remoteCache) { unregister(cacheMBeans.remove(remoteCache.getName())); } private void unregister(ObjectName objectName) { if (objectName != null) { try { if (mBeanServer.isRegistered(objectName)) { mBeanServer.unregisterMBean(objectName); } else { HOTROD.debugf("MBean not registered: %s", objectName); } } catch (Exception e) { throw HOTROD.jmxUnregistrationFailure(e); } } } } class NoOp implements MBeanHelper { @Override public void close() { } @Override public void register(RemoteCacheImpl<?, ?> remoteCache) { } @Override public void unregister(RemoteCacheImpl<?, ?> remoteCache) { } } }
3,147
31.453608
188
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/InvalidatedNearRemoteCache.java
package org.infinispan.hotrod.impl.cache; import static org.infinispan.hotrod.impl.Util.await; import static org.infinispan.hotrod.impl.logging.Log.HOTROD; import java.lang.invoke.MethodHandles; import java.net.SocketAddress; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryVersion; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.hotrod.impl.operations.CacheOperationsFactory; import org.infinispan.hotrod.impl.operations.ClientListenerOperation; import org.infinispan.hotrod.impl.operations.RetryAwareCompletionStage; import org.infinispan.hotrod.impl.operations.UpdateBloomFilterOperation; import org.infinispan.hotrod.near.NearCacheService; /** * Near cache implementation enabling * * @param <K> * @param <V> */ public class InvalidatedNearRemoteCache<K, V> extends DelegatingRemoteCache<K, V> { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); private static final boolean trace = log.isTraceEnabled(); private final NearCacheService<K, V> nearcache; private final ClientStatistics clientStatistics; // This field is used to control updating the near cache with updating the remote server's bloom filter // representation. This value will be non null when bloom filter is enabled, otherwise null. When this // value is even it means there is no bloom filter update being sent and the near cache can be updated // locally from reads. When a bloom filter is being replicated though the value will be odd and the // near cache cannot be updated. private final AtomicInteger bloomFilterUpdateVersion; private volatile SocketAddress listenerAddress; InvalidatedNearRemoteCache(RemoteCache<K, V> remoteCache, ClientStatistics clientStatistics, NearCacheService<K, V> nearcache) { super(remoteCache); this.clientStatistics = clientStatistics; this.nearcache = nearcache; this.bloomFilterUpdateVersion = nearcache.getBloomFilterBits() > 0 ? new AtomicInteger() : null; } @Override <Key, Value> RemoteCache<Key, Value> newDelegatingCache(RemoteCache<Key, Value> innerCache) { return new InvalidatedNearRemoteCache<>(innerCache, clientStatistics, (NearCacheService<Key, Value>) nearcache); } public static <K, V> InvalidatedNearRemoteCache<K, V> delegatingNearCache(RemoteCacheImpl<K, V> remoteCache, NearCacheService<K, V> nearCacheService) { return new InvalidatedNearRemoteCache<>(remoteCache, remoteCache.getClientStatistics(), nearCacheService); } @Override public CompletionStage<V> get(K key, CacheOptions options) { return getEntry(key, options).thenApply(v -> v != null ? v.value() : null); } private int getCurrentVersion() { if (bloomFilterUpdateVersion != null) { return bloomFilterUpdateVersion.get(); } return 0; } @Override public CompletionStage<CacheEntry<K, V>> getEntry(K key, CacheOptions options) { CacheEntry<K, V> nearValue = nearcache.get(key); if (nearValue == null) { clientStatistics.incrementNearCacheMisses(); int prevVersion = getCurrentVersion(); RetryAwareCompletionStage<CacheEntry<K, V>> remoteValue = super.getEntry(key, options, listenerAddress); return remoteValue.thenApply(e -> { // We cannot cache the value if a retry was required - which means we did not talk to the listener node if (e != null) { // If previous version is odd we can't cache as that means it was started during // a bloom filter update. We also can't cache if the new version doesn't match the prior // as it overlapped a bloom update. if ((prevVersion & 1) == 1 || prevVersion != getCurrentVersion()) { if (trace) { log.tracef("Unable to cache returned value for key %s as operation was performed during a" + " bloom filter update"); } } // Having a listener address means it has a bloom filter. When we have a bloom filter we cannot // cache values upon a retry as we can't guarantee the bloom filter is updated on the server properly else if (listenerAddress != null && remoteValue.wasRetried()) { if (trace) { log.tracef("Unable to cache returned value for key %s as operation was retried", key); } } else { nearcache.putIfAbsent(e); e.metadata().expiration().maxIdle().ifPresent(m -> HOTROD.nearCacheMaxIdleUnsupported()); } } return e; }); } else { clientStatistics.incrementNearCacheHits(); return CompletableFuture.completedFuture(nearValue); } } @Override public CompletionStage<CacheEntry<K, V>> put(K key, V value, CacheWriteOptions options) { options.expiration().maxIdle().ifPresent(m -> HOTROD.nearCacheMaxIdleUnsupported()); return super.put(key, value, options).thenApply(v -> { nearcache.remove(key); return v; }); } @Override public CompletionStage<CacheEntry<K, V>> putIfAbsent(K key, V value, CacheWriteOptions options) { options.expiration().maxIdle().ifPresent(m -> HOTROD.nearCacheMaxIdleUnsupported()); return super.putIfAbsent(key, value, options).thenApply(v -> { nearcache.remove(key); return v; }); } @Override public CompletionStage<Boolean> setIfAbsent(K key, V value, CacheWriteOptions options) { options.expiration().maxIdle().ifPresent(m -> HOTROD.nearCacheMaxIdleUnsupported()); return super.setIfAbsent(key, value, options).thenApply(v -> { nearcache.remove(key); return v; }); } @Override public CompletionStage<Void> set(K key, V value, CacheWriteOptions options) { options.expiration().maxIdle().ifPresent(m -> HOTROD.nearCacheMaxIdleUnsupported()); return super.set(key, value, options).thenApply(v -> { nearcache.remove(key); return v; }); } @Override public CompletionStage<Boolean> replace(K key, V value, CacheEntryVersion version, CacheWriteOptions options) { options.expiration().maxIdle().ifPresent(m -> HOTROD.nearCacheMaxIdleUnsupported()); return super.replace(key, value, version, options).thenApply(v -> { if (v) { nearcache.remove(key); } return v; }); } @Override public CompletionStage<CacheEntry<K, V>> getOrReplaceEntry(K key, V value, CacheEntryVersion version, CacheWriteOptions options) { options.expiration().maxIdle().ifPresent(m -> HOTROD.nearCacheMaxIdleUnsupported()); return super.getOrReplaceEntry(key, value, version, options).thenApply(v -> { nearcache.remove(key); return v; }); } @Override public CompletionStage<Boolean> remove(K key, CacheOptions options) { return super.remove(key, options).thenApply(v -> { if (v) { nearcache.remove(key); } return v; }); } @Override public CompletionStage<Boolean> remove(K key, CacheEntryVersion version, CacheOptions options) { return super.remove(key, version, options).thenApply(v -> { if (v) { nearcache.remove(key); } return v; }); } @Override public CompletionStage<CacheEntry<K, V>> getAndRemove(K key, CacheOptions options) { return super.getAndRemove(key, options).thenApply(v -> { nearcache.remove(key); return v; }); } @Override public CompletionStage<Void> clear(CacheOptions options) { return super.clear(options).thenRun(nearcache::clear); } @Override public CompletionStage<Void> putAll(Map<K, V> entries, CacheWriteOptions options) { options.expiration().maxIdle().ifPresent(m -> HOTROD.nearCacheMaxIdleUnsupported()); return super.putAll(entries, options).thenRun(() -> entries.keySet().forEach(nearcache::remove)); } public void start() { listenerAddress = nearcache.start(this); } public void stop() { nearcache.stop(this); } public void clearNearCache() { nearcache.clear(); } // Increments the bloom filter version if it is even and returns whether it was incremented private boolean incrementBloomVersionIfEven() { if (bloomFilterUpdateVersion != null) { int prev; do { prev = bloomFilterUpdateVersion.get(); // Odd number means we are already sending bloom filter if ((prev & 1) == 1) { return false; } } while (!bloomFilterUpdateVersion.compareAndSet(prev, prev + 1)); } return true; } CompletionStage<Void> incrementBloomVersionUponCompletion(CompletionStage<Void> stage) { if (bloomFilterUpdateVersion != null) { return stage .whenComplete((ignore, t) -> bloomFilterUpdateVersion.incrementAndGet()); } return stage; } @Override public CompletionStage<Void> updateBloomFilter() { // Not being able to increment the even version means we have a concurrent update - so skip if (!incrementBloomVersionIfEven()) { if (trace) { log.tracef("Already have a concurrent bloom filter update for listenerId(%s) - skipping", org.infinispan.commons.util.Util.printArray(nearcache.getListenerId())); } return CompletableFuture.completedFuture(null); } byte[] bloomFilterBits = nearcache.calculateBloomBits(); if (trace) { log.tracef("Sending bloom filter bits(%s) update to %s for listenerId(%s)", org.infinispan.commons.util.Util.printArray(bloomFilterBits), listenerAddress, org.infinispan.commons.util.Util.printArray(nearcache.getListenerId())); } CacheOperationsFactory cacheOperationsFactory = getOperationsFactory(); UpdateBloomFilterOperation bloopOp = cacheOperationsFactory.newUpdateBloomFilterOperation(CacheOptions.DEFAULT, listenerAddress, bloomFilterBits); return incrementBloomVersionUponCompletion(bloopOp.execute()); } public SocketAddress getBloomListenerAddress() { return listenerAddress; } public void setBloomListenerAddress(SocketAddress socketAddress) { this.listenerAddress = socketAddress; } @Override public SocketAddress addNearCacheListener(Object listener, int bloomBits) { ClientListenerOperation op = getOperationsFactory().newAddNearCacheListenerOperation(listener, CacheOptions.DEFAULT, getDataFormat(), bloomBits, this); // no timeout, see below return await(op.execute()); } }
11,318
39.281139
152
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/CacheEntryMetadataImpl.java
package org.infinispan.hotrod.impl.cache; import java.time.Instant; import java.util.Objects; import java.util.Optional; import org.infinispan.api.common.CacheEntryExpiration; import org.infinispan.api.common.CacheEntryMetadata; import org.infinispan.api.common.CacheEntryVersion; /** * @since 14.0 **/ public class CacheEntryMetadataImpl implements CacheEntryMetadata { private final long creation; private final long lastAccess; private final CacheEntryVersion version; private final CacheEntryExpiration expiration; public CacheEntryMetadataImpl() { this(-1, -1, null, null); } public CacheEntryMetadataImpl(long creation, long lastAccess, CacheEntryExpiration expiration, CacheEntryVersion version) { this.creation = creation; this.lastAccess = lastAccess; this.expiration = expiration; this.version = version; } @Override public Optional<Instant> creationTime() { return creation < 0 ? Optional.empty() : Optional.of(Instant.ofEpochMilli(creation)); } @Override public Optional<Instant> lastAccessTime() { return lastAccess < 0 ? Optional.empty() : Optional.of(Instant.ofEpochMilli(lastAccess)); } @Override public CacheEntryExpiration expiration() { return expiration; } @Override public CacheEntryVersion version() { return version; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CacheEntryMetadataImpl that = (CacheEntryMetadataImpl) o; return creation == that.creation && lastAccess == that.lastAccess && Objects.equals(version, that.version) && Objects.equals(expiration, that.expiration); } @Override public int hashCode() { return Objects.hash(creation, lastAccess, version, expiration); } @Override public String toString() { return "CacheEntryMetadataImpl{" + "creation=" + creation + ", lastAccess=" + lastAccess + ", version=" + version + ", expiration=" + expiration + '}'; } }
2,132
27.824324
160
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/CacheTopologyInfo.java
package org.infinispan.hotrod.impl.cache; import java.net.SocketAddress; import java.util.Map; import java.util.Set; /** * Contains information about cache topology including servers and owned segments. * * @since 14.0 */ public interface CacheTopologyInfo { /** * @return The number of configured segments for the cache. */ Integer getNumSegments(); /** * @return Segments owned by each server. */ Map<SocketAddress, Set<Integer>> getSegmentsPerServer(); Integer getTopologyId(); }
523
19.153846
82
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/CacheTopologyInfoImpl.java
package org.infinispan.hotrod.impl.cache; import java.net.SocketAddress; import java.util.Map; import java.util.Set; /** * @since 14.0 */ public class CacheTopologyInfoImpl implements CacheTopologyInfo { private final Map<SocketAddress, Set<Integer>> segmentsByServer; private final Integer numSegments; private final Integer topologyId; public CacheTopologyInfoImpl(Map<SocketAddress, Set<Integer>> segmentsByServer, Integer numSegments, Integer topologyId) { this.segmentsByServer = segmentsByServer; this.numSegments = numSegments; this.topologyId = topologyId; } @Override public Integer getNumSegments() { return numSegments; } @Override public Integer getTopologyId() { return topologyId; } @Override public Map<SocketAddress, Set<Integer>> getSegmentsPerServer() { return segmentsByServer; } @Override public String toString() { return "CacheTopologyInfoImpl{" + "segmentsByServer=" + segmentsByServer + ", numSegments=" + numSegments + ", topologyId=" + topologyId + '}'; } }
1,142
24.4
125
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/ServerStatistics.java
package org.infinispan.hotrod.impl.cache; import java.util.Map; /** * Defines the possible list of statistics defined by the Hot Rod server. * Can be obtained through {@link RemoteCache#stats()} * * @since 14.0 */ public interface ServerStatistics { /** * Number of seconds since Hot Rod started. */ String TIME_SINCE_START = "timeSinceStart"; /** * Approximate current number of entry replicas in the cache on the server that receives the request. * * <p>Includes both entries in memory and in persistent storage.</p> */ String APPROXIMATE_ENTRIES = "approximateEntries"; /** * Approximate current number of entries for which the server that receives the request is the primary owner. * * <p>Includes both entries in memory and in persistent storage.</p> */ String APPROXIMATE_ENTRIES_UNIQUE = "approximateEntriesUnique"; /** * Number of entries stored in the cache by the server that receives the request since the cache started running. */ String STORES = "stores"; /** * Number of get operations. */ String RETRIEVALS = "retrievals"; /** * Number of get hits. */ String HITS = "hits"; /** * Number of get misses. */ String MISSES = "misses"; /** * Number of removal hits. */ String REMOVE_HITS = "removeHits"; /** * Number of removal misses. */ String REMOVE_MISSES = "removeMisses"; /** * Approximate current number of entry replicas currently in the cache cluster-wide. * * <p>Includes both entries in memory and in persistent storage.</p> */ String CLUSTER_APPROXIMATE_ENTRIES = "globalApproximateEntries"; /** * Approximate current number of unique entries in the cache cluster-wide. * * <p>Includes both entries in memory and in persistent storage. * Entries owned by multiple nodes are counted only once.</p> */ String CLUSTER_APPROXIMATE_ENTRIES_UNIQUE = "globalApproximateEntriesUnique"; Map<String, String> getStatsMap(); String getStatistic(String statsName); Integer getIntStatistic(String statsName); }
2,141
24.2
116
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/MetadataValueImpl.java
package org.infinispan.hotrod.impl.cache; /** * MetadataValueImpl. * * @since 14.0 */ public class MetadataValueImpl<V> extends VersionedValueImpl<V> implements MetadataValue<V> { private final long created; private final int lifespan; private final long lastUsed; private final int maxIdle; public MetadataValueImpl(long created, int lifespan, long lastUsed, int maxIdle, long version, V value) { super(version, value); this.created = created; this.lifespan = lifespan; this.lastUsed = lastUsed; this.maxIdle = maxIdle; } @Override public long getCreated() { return created; } @Override public int getLifespan() { return lifespan; } @Override public long getLastUsed() { return lastUsed; } @Override public int getMaxIdle() { return maxIdle; } @Override public String toString() { return "MetadataValueImpl [created=" + created + ", lifespan=" + lifespan + ", lastUsed=" + lastUsed + ", maxIdle=" + maxIdle + ", getVersion()=" + getVersion() + ", getValue()=" + getValue() + "]"; } }
1,133
21.68
166
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/MetadataValue.java
package org.infinispan.hotrod.impl.cache; /** * Besides the value, also contains a version and expiration information. Time values are server * time representations as returned by {@link org.infinispan.commons.time.TimeService#wallClockTime} * * @since 14.0 */ public interface MetadataValue<V> extends VersionedValue<V>, Metadata { }
342
27.583333
100
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/RemoteCache.java
package org.infinispan.hotrod.impl.cache; import java.net.SocketAddress; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.Flow; import jakarta.transaction.TransactionManager; import org.infinispan.api.async.AsyncCacheEntryProcessor; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryVersion; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.api.common.events.cache.CacheEntryEvent; import org.infinispan.api.common.events.cache.CacheEntryEventType; import org.infinispan.api.common.events.cache.CacheListenerOptions; import org.infinispan.api.common.process.CacheEntryProcessorResult; import org.infinispan.api.common.process.CacheProcessorOptions; import org.infinispan.api.configuration.CacheConfiguration; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.HotRodTransport; import org.infinispan.hotrod.impl.operations.CacheOperationsFactory; import org.infinispan.hotrod.impl.operations.RetryAwareCompletionStage; import org.reactivestreams.Publisher; /** * @since 14.0 **/ public interface RemoteCache<K, V> extends AutoCloseable { CompletionStage<CacheConfiguration> configuration(); HotRodTransport getHotRodTransport(); CacheOperationsFactory getOperationsFactory(); CompletionStage<V> get(K key, CacheOptions options); K keyAsObjectIfNeeded(Object key); byte[] keyToBytes(Object o); byte[] valueToBytes(Object o); CompletionStage<CacheEntry<K, V>> getEntry(K key, CacheOptions options); RetryAwareCompletionStage<CacheEntry<K, V>> getEntry(K key, CacheOptions options, SocketAddress listenerAddress); CompletionStage<CacheEntry<K, V>> putIfAbsent(K key, V value, CacheWriteOptions options); CompletionStage<Boolean> setIfAbsent(K key, V value, CacheWriteOptions options); CompletionStage<CacheEntry<K, V>> put(K key, V value, CacheWriteOptions options); CompletionStage<Void> set(K key, V value, CacheWriteOptions options); CompletionStage<Boolean> replace(K key, V value, CacheEntryVersion version, CacheWriteOptions options); CompletionStage<CacheEntry<K,V>> getOrReplaceEntry(K key, V value, CacheEntryVersion version, CacheWriteOptions options); CompletionStage<Boolean> remove(K key, CacheOptions options); CompletionStage<Boolean> remove(K key, CacheEntryVersion version, CacheOptions options); CompletionStage<CacheEntry<K, V>> getAndRemove(K key, CacheOptions options); Flow.Publisher<K> keys(CacheOptions options); Flow.Publisher<CacheEntry<K,V>> entries(CacheOptions options); CompletionStage<Void> putAll(Map<K, V> entries, CacheWriteOptions options); CompletionStage<Void> putAll(Flow.Publisher<CacheEntry<K, V>> entries, CacheWriteOptions options); Flow.Publisher<CacheEntry<K, V>> getAll(Set<K> keys, CacheOptions options); Flow.Publisher<CacheEntry<K, V>> getAll(CacheOptions options, K[] keys); Flow.Publisher<K> removeAll(Set<K> keys, CacheWriteOptions options); Flow.Publisher<K> removeAll(Flow.Publisher<K> keys, CacheWriteOptions options); Flow.Publisher<CacheEntry<K, V>> getAndRemoveAll(Set<K> keys, CacheWriteOptions options); Flow.Publisher<CacheEntry<K, V>> getAndRemoveAll(Flow.Publisher<K> keys, CacheWriteOptions options); CompletionStage<Long> estimateSize(CacheOptions options); CompletionStage<Void> clear(CacheOptions options); Flow.Publisher<CacheEntryEvent<K, V>> listen(CacheListenerOptions options, CacheEntryEventType[] types); <T> Flow.Publisher<CacheEntryProcessorResult<K, T>> process(Set<K> keys, AsyncCacheEntryProcessor<K, V, T> task, CacheOptions options); <T> Flow.Publisher<CacheEntryProcessorResult<K, T>> processAll(AsyncCacheEntryProcessor<K, V, T> processor, CacheProcessorOptions options); default CloseableIterator<CacheEntry<Object, Object>> retrieveEntries(String filterConverterFactory, Set<Integer> segments, int batchSize) { return retrieveEntries(filterConverterFactory, null, segments, batchSize); } CloseableIterator<CacheEntry<Object, Object>> retrieveEntries(String filterConverterFactory, Object[] filterConverterParams, Set<Integer> segments, int batchSize); <T, U> RemoteCache<T, U> withDataFormat(DataFormat newDataFormat); void resolveStorage(boolean objectStorage); CompletionStage<Void> updateBloomFilter(); SocketAddress addNearCacheListener(Object listener, int bloomFilterBits); String getName(); DataFormat getDataFormat(); <E> Publisher<CacheEntry<K, E>> publishEntries(String filterConverterFactory, Object[] filterConverterParams, Set<Integer> segments, int batchSize); CloseableIterator<CacheEntry<Object, Object>> retrieveEntriesByQuery(RemoteQuery query, Set<Integer> segments, int batchSize); <E> Publisher<CacheEntry<K, E>> publishEntriesByQuery(RemoteQuery query, Set<Integer> segments, int batchSize); CloseableIterator<CacheEntry<Object, Object>> retrieveEntriesWithMetadata(Set<Integer> segments, int batchSize); Publisher<CacheEntry<K, V>> publishEntriesWithMetadata(Set<Integer> segments, int batchSize); TransactionManager getTransactionManager(); boolean isTransactional(); }
5,341
39.778626
166
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/VersionedMetadataImpl.java
package org.infinispan.hotrod.impl.cache; /** * @since 14.0 */ public class VersionedMetadataImpl implements VersionedMetadata { private final long created; private final int lifespan; private final long lastUsed; private final int maxIdle; private final long version; public VersionedMetadataImpl(long created, int lifespan, long lastUsed, int maxIdle, long version) { this.created = created; this.lifespan = lifespan; this.lastUsed = lastUsed; this.maxIdle = maxIdle; this.version = version; } public long getCreated() { return created; } public int getLifespan() { return lifespan; } public long getLastUsed() { return lastUsed; } public int getMaxIdle() { return maxIdle; } public long getVersion() { return version; } }
846
19.166667
103
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/ServerStatisticsImpl.java
package org.infinispan.hotrod.impl.cache; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * @since 14.0 */ public class ServerStatisticsImpl implements ServerStatistics { private final Map<String, String> stats = new HashMap<>(); @Override public Map<String, String> getStatsMap() { return Collections.unmodifiableMap(stats); } @Override public String getStatistic(String statsName) { return stats.get(statsName); } public void addStats(String name, String value) { stats.put(name, value); } public int size() { return stats.size(); } @Override public Integer getIntStatistic(String statsName) { String value = stats.get(statsName); return value == null ? null : Integer.parseInt(value); } }
814
20.447368
63
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/Metadata.java
package org.infinispan.hotrod.impl.cache; /** * Represents metadata about an entry, such as creation and access times and expiration information. Time values are server * time representations as returned by {@link org.infinispan.commons.time.TimeService#wallClockTime} * * @since 14.0 */ public interface Metadata { /** * * @return Time when entry was created. -1 for immortal entries. */ long getCreated(); /** * * @return Lifespan of the entry in seconds. Negative values are interpreted as unlimited * lifespan. */ int getLifespan(); /** * * @return Time when entry was last used. -1 for immortal entries. */ long getLastUsed(); /** * * @return The maximum amount of time (in seconds) this key is allowed to be idle for before it * is considered as expired. */ int getMaxIdle(); }
889
23.722222
123
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/CacheEntryVersionImpl.java
package org.infinispan.hotrod.impl.cache; import java.util.Objects; import org.infinispan.api.common.CacheEntryVersion; /** * @since 14.0 **/ public class CacheEntryVersionImpl implements CacheEntryVersion { private final long version; public CacheEntryVersionImpl(long version) { this.version = version; } public long version() { return version; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CacheEntryVersionImpl that = (CacheEntryVersionImpl) o; return version == that.version; } @Override public int hashCode() { return Objects.hash(version); } @Override public String toString() { return "CacheEntryVersionImpl{" + "version=" + version + '}'; } }
863
20.073171
65
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/CacheEntryImpl.java
package org.infinispan.hotrod.impl.cache; import static org.infinispan.commons.util.Util.toStr; import java.util.Objects; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryMetadata; /** * @since 14.0 **/ public class CacheEntryImpl<K, V> implements CacheEntry<K, V> { private final K k; private final V v; private final CacheEntryMetadata metadata; public CacheEntryImpl(K k, V v, CacheEntryMetadata metadata) { this.k = k; this.v = v; this.metadata = metadata; } @Override public K key() { return k; } @Override public V value() { return v; } @Override public CacheEntryMetadata metadata() { return metadata; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CacheEntryImpl<?, ?> that = (CacheEntryImpl<?, ?>) o; return k.equals(that.k) && Objects.equals(v, that.v) && Objects.equals(metadata, that.metadata); } @Override public int hashCode() { return Objects.hash(k, v, metadata); } @Override public String toString() { return "CacheEntryImpl{" + "k=" + toStr(k) + ", v=" + toStr(v) + ", metadata=" + metadata + '}'; } }
1,347
21.098361
102
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/ClientStatistics.java
package org.infinispan.hotrod.impl.cache; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.concurrent.StripedCounters; import org.infinispan.hotrod.jmx.RemoteCacheClientStatisticsMXBean; import org.infinispan.hotrod.near.NearCacheService; public final class ClientStatistics implements RemoteCacheClientStatisticsMXBean { private final boolean enabled; private final AtomicLong startNanoseconds = new AtomicLong(0); private final AtomicLong resetNanoseconds = new AtomicLong(0); private final NearCacheService<?, ?> nearCacheService; private final TimeService timeService; private final StripedCounters<StripeB> counters = new StripedCounters<>(StripeC::new); ClientStatistics(boolean enabled, TimeService timeService, NearCacheService<?, ?> nearCacheService) { this.enabled = enabled; this.timeService = timeService; this.nearCacheService = nearCacheService; if (nearCacheService != null) nearCacheService.setInvalidationCallback(this::incrementNearCacheInvalidations); } ClientStatistics(boolean enabled, TimeService timeService) { this(enabled, timeService, null); } public boolean isEnabled() { return enabled; } @Override public long getRemoteHits() { return counters.get(StripeB.remoteCacheHitsFieldUpdater); } @Override public long getRemoteMisses() { return counters.get(StripeB.remoteCacheMissesFieldUpdater); } @Override public long getAverageRemoteReadTime() { long total = counters.get(StripeB.remoteCacheHitsFieldUpdater) + counters.get(StripeB.remoteCacheMissesFieldUpdater); if (total == 0) return 0; total = (counters.get(StripeB.remoteCacheHitsTimeFieldUpdater) + counters.get(StripeB.remoteCacheMissesTimeFieldUpdater)) / total; return TimeUnit.NANOSECONDS.toMillis(total); } @Override public long getRemoteStores() { return counters.get(StripeB.remoteCacheStoresFieldUpdater); } @Override public long getAverageRemoteStoreTime() { long total = counters.get(StripeB.remoteCacheStoresFieldUpdater); if (total == 0) return 0; total = counters.get(StripeB.remoteCacheStoresTimeFieldUpdater) / total; return TimeUnit.NANOSECONDS.toMillis(total); } @Override public long getRemoteRemoves() { return counters.get(StripeB.remoteCacheRemovesFieldUpdater); } @Override public long getAverageRemoteRemovesTime() { long total = counters.get(StripeB.remoteCacheRemovesFieldUpdater); if (total == 0) return 0; total = counters.get(StripeB.remoteCacheRemovesTimeFieldUpdater) / total; return TimeUnit.NANOSECONDS.toMillis(total); } @Override public long getNearCacheHits() { return counters.get(StripeB.nearCacheHitsFieldUpdater); } @Override public long getNearCacheMisses() { return counters.get(StripeB.nearCacheMissesFieldUpdater); } @Override public long getNearCacheInvalidations() { return counters.get(StripeB.nearCacheInvalidationsFieldUpdater); } @Override public long getNearCacheSize() { return nearCacheService != null ? nearCacheService.size() : 0; } public long time() { return timeService.time(); } public void dataRead(boolean foundValue, long startTimeNanoSeconds, int count) { long duration = timeService.timeDuration(startTimeNanoSeconds, TimeUnit.NANOSECONDS); StripeB stripe = counters.stripeForCurrentThread(); if (foundValue) { counters.add(StripeB.remoteCacheHitsTimeFieldUpdater, stripe, duration); counters.add(StripeB.remoteCacheHitsFieldUpdater, stripe, count); } else { counters.add(StripeB.remoteCacheMissesTimeFieldUpdater, stripe, duration); counters.add(StripeB.remoteCacheMissesFieldUpdater, stripe, count); } } public void dataStore(long startTimeNanoSeconds, int count) { long duration = timeService.timeDuration(startTimeNanoSeconds, TimeUnit.NANOSECONDS); StripeB stripe = counters.stripeForCurrentThread(); counters.add(StripeB.remoteCacheStoresTimeFieldUpdater, stripe, duration); counters.add(StripeB.remoteCacheStoresFieldUpdater, stripe, count); } public void dataRemove(long startTimeNanoSeconds, int count) { long duration = timeService.timeDuration(startTimeNanoSeconds, TimeUnit.NANOSECONDS); StripeB stripe = counters.stripeForCurrentThread(); counters.add(StripeB.remoteCacheRemovesTimeFieldUpdater, stripe, duration); counters.add(StripeB.remoteCacheRemovesFieldUpdater, stripe, count); } public void incrementNearCacheMisses() { counters.increment(StripeB.nearCacheMissesFieldUpdater, counters.stripeForCurrentThread()); } public void incrementNearCacheHits() { counters.increment(StripeB.nearCacheHitsFieldUpdater, counters.stripeForCurrentThread()); } public void incrementNearCacheInvalidations() { counters.increment(StripeB.nearCacheInvalidationsFieldUpdater, counters.stripeForCurrentThread()); } @Override public void resetStatistics() { counters.reset(StripeB.remoteCacheHitsFieldUpdater); counters.reset(StripeB.remoteCacheHitsTimeFieldUpdater); counters.reset(StripeB.remoteCacheMissesFieldUpdater); counters.reset(StripeB.remoteCacheMissesTimeFieldUpdater); counters.reset(StripeB.remoteCacheRemovesFieldUpdater); counters.reset(StripeB.remoteCacheRemovesTimeFieldUpdater); counters.reset(StripeB.remoteCacheStoresFieldUpdater); counters.reset(StripeB.remoteCacheStoresTimeFieldUpdater); counters.reset(StripeB.nearCacheHitsFieldUpdater); counters.reset(StripeB.nearCacheMissesFieldUpdater); counters.reset(StripeB.nearCacheInvalidationsFieldUpdater); startNanoseconds.set(timeService.time()); resetNanoseconds.set(startNanoseconds.get()); } @Override public long getTimeSinceReset() { return timeService.timeDuration(resetNanoseconds.get(), TimeUnit.SECONDS); } /** * It returns a {@link ClientStatistics} instance to be used when the statistics aren't needed. * * @return a disabled {@link ClientStatistics} instance. */ public static ClientStatistics dummyClientStatistics(TimeService timeService) { return new ClientStatistics(false, timeService); } private static class StripeA { @SuppressWarnings("unused") private long slack1, slack2, slack3, slack4, slack5, slack6, slack7, slack8; } @SuppressWarnings("VolatileLongOrDoubleField") private static class StripeB extends StripeA { static final AtomicLongFieldUpdater<StripeB> remoteCacheHitsFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheHits"); static final AtomicLongFieldUpdater<StripeB> remoteCacheHitsTimeFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheHitsTime"); static final AtomicLongFieldUpdater<StripeB> remoteCacheMissesFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheMisses"); static final AtomicLongFieldUpdater<StripeB> remoteCacheMissesTimeFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheMissesTime"); static final AtomicLongFieldUpdater<StripeB> remoteCacheRemovesFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheRemoves"); static final AtomicLongFieldUpdater<StripeB> remoteCacheRemovesTimeFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheRemovesTime"); static final AtomicLongFieldUpdater<StripeB> remoteCacheStoresFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheStores"); static final AtomicLongFieldUpdater<StripeB> remoteCacheStoresTimeFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheStoresTime"); static final AtomicLongFieldUpdater<StripeB> nearCacheHitsFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "nearCacheHits"); static final AtomicLongFieldUpdater<StripeB> nearCacheMissesFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "nearCacheMisses"); static final AtomicLongFieldUpdater<StripeB> nearCacheInvalidationsFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "nearCacheInvalidations"); private volatile long remoteCacheHits = 0; private volatile long remoteCacheHitsTime = 0; private volatile long remoteCacheMisses = 0; private volatile long remoteCacheMissesTime = 0; private volatile long remoteCacheRemoves = 0; private volatile long remoteCacheRemovesTime = 0; private volatile long remoteCacheStores = 0; private volatile long remoteCacheStoresTime = 0; private volatile long nearCacheHits = 0; private volatile long nearCacheMisses = 0; private volatile long nearCacheInvalidations = 0; } private static final class StripeC extends StripeB { @SuppressWarnings("unused") private long slack1, slack2, slack3, slack4, slack5, slack6, slack7, slack8; } }
9,438
40.951111
136
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/DelegatingRemoteCache.java
package org.infinispan.hotrod.impl.cache; import java.net.SocketAddress; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.Flow; import jakarta.transaction.TransactionManager; import org.infinispan.api.async.AsyncCacheEntryProcessor; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryVersion; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.api.common.events.cache.CacheEntryEvent; import org.infinispan.api.common.events.cache.CacheEntryEventType; import org.infinispan.api.common.events.cache.CacheListenerOptions; import org.infinispan.api.common.process.CacheEntryProcessorResult; import org.infinispan.api.common.process.CacheProcessorOptions; import org.infinispan.api.configuration.CacheConfiguration; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.HotRodTransport; import org.infinispan.hotrod.impl.operations.CacheOperationsFactory; import org.infinispan.hotrod.impl.operations.RetryAwareCompletionStage; import org.reactivestreams.Publisher; /** * Delegates all invocations to the provided underlying {@link RemoteCache} but provides extensibility to intercept when * a method is invoked. * * @param <K> key type * @param <V> value type */ public abstract class DelegatingRemoteCache<K, V> implements RemoteCache<K, V> { protected final RemoteCache<K, V> delegate; protected DelegatingRemoteCache(RemoteCache<K, V> delegate) { this.delegate = delegate; } abstract <Key, Value> RemoteCache<Key, Value> newDelegatingCache(RemoteCache<Key, Value> innerCache); @Override public CompletionStage<CacheConfiguration> configuration() { return delegate.configuration(); } @Override public HotRodTransport getHotRodTransport() { return delegate.getHotRodTransport(); } @Override public CacheOperationsFactory getOperationsFactory() { return delegate.getOperationsFactory(); } @Override public CompletionStage<V> get(K key, CacheOptions options) { return delegate.get(key, options); } @Override public CompletionStage<CacheEntry<K, V>> getEntry(K key, CacheOptions options) { return delegate.getEntry(key, options); } @Override public RetryAwareCompletionStage<CacheEntry<K, V>> getEntry(K key, CacheOptions options, SocketAddress listenerAddress) { return delegate.getEntry(key, options, listenerAddress); } @Override public CompletionStage<CacheEntry<K, V>> putIfAbsent(K key, V value, CacheWriteOptions options) { return delegate.putIfAbsent(key, value, options); } @Override public CompletionStage<Boolean> setIfAbsent(K key, V value, CacheWriteOptions options) { return delegate.setIfAbsent(key, value, options); } @Override public CompletionStage<CacheEntry<K, V>> put(K key, V value, CacheWriteOptions options) { return delegate.put(key, value, options); } @Override public CompletionStage<Void> set(K key, V value, CacheWriteOptions options) { return delegate.set(key, value, options); } @Override public CompletionStage<Boolean> replace(K key, V value, CacheEntryVersion version, CacheWriteOptions options) { return delegate.replace(key, value, version, options); } @Override public CompletionStage<CacheEntry<K, V>> getOrReplaceEntry(K key, V value, CacheEntryVersion version, CacheWriteOptions options) { return delegate.getOrReplaceEntry(key, value, version, options); } @Override public CompletionStage<Boolean> remove(K key, CacheOptions options) { return delegate.remove(key, options); } @Override public CompletionStage<Boolean> remove(K key, CacheEntryVersion version, CacheOptions options) { return delegate.remove(key, version, options); } @Override public CompletionStage<CacheEntry<K, V>> getAndRemove(K key, CacheOptions options) { return delegate.getAndRemove(key, options); } @Override public Flow.Publisher<K> keys(CacheOptions options) { return delegate.keys(options); } @Override public Flow.Publisher<CacheEntry<K, V>> entries(CacheOptions options) { return delegate.entries(options); } @Override public CompletionStage<Void> putAll(Map<K, V> entries, CacheWriteOptions options) { return delegate.putAll(entries, options); } @Override public CompletionStage<Void> putAll(Flow.Publisher<CacheEntry<K, V>> entries, CacheWriteOptions options) { return delegate.putAll(entries, options); } @Override public Flow.Publisher<CacheEntry<K, V>> getAll(Set<K> keys, CacheOptions options) { return delegate.getAll(keys, options); } @Override public Flow.Publisher<CacheEntry<K, V>> getAll(CacheOptions options, K[] keys) { return delegate.getAll(options, keys); } @Override public Flow.Publisher<K> removeAll(Set<K> keys, CacheWriteOptions options) { return delegate.removeAll(keys, options); } @Override public Flow.Publisher<K> removeAll(Flow.Publisher<K> keys, CacheWriteOptions options) { return delegate.removeAll(keys, options); } @Override public Flow.Publisher<CacheEntry<K, V>> getAndRemoveAll(Set<K> keys, CacheWriteOptions options) { return delegate.getAndRemoveAll(keys, options); } @Override public Flow.Publisher<CacheEntry<K, V>> getAndRemoveAll(Flow.Publisher<K> keys, CacheWriteOptions options) { return delegate.getAndRemoveAll(keys, options); } @Override public CompletionStage<Long> estimateSize(CacheOptions options) { return delegate.estimateSize(options); } @Override public CompletionStage<Void> clear(CacheOptions options) { return delegate.clear(options); } @Override public CloseableIterator<CacheEntry<Object, Object>> retrieveEntries(String filterConverterFactory, Set<Integer> segments, int batchSize) { return delegate.retrieveEntries(filterConverterFactory, segments, batchSize); } @Override public CloseableIterator<CacheEntry<Object, Object>> retrieveEntries(String filterConverterFactory, Object[] filterConverterParams, Set<Integer> segments, int batchSize) { return delegate.retrieveEntries(filterConverterFactory, filterConverterParams, segments, batchSize); } @Override public Flow.Publisher<CacheEntryEvent<K, V>> listen(CacheListenerOptions options, CacheEntryEventType[] types) { return delegate.listen(options, types); } @Override public <T> Flow.Publisher<CacheEntryProcessorResult<K, T>> process(Set<K> keys, AsyncCacheEntryProcessor<K, V, T> task, CacheOptions options) { return delegate.process(keys, task, options); } @Override public <T> Flow.Publisher<CacheEntryProcessorResult<K, T>> processAll(AsyncCacheEntryProcessor<K, V, T> processor, CacheProcessorOptions options) { return delegate.processAll(processor, options); } @Override public <T, U> RemoteCache<T, U> withDataFormat(DataFormat newDataFormat) { return delegate.withDataFormat(newDataFormat); } @Override public K keyAsObjectIfNeeded(Object key) { return delegate.keyAsObjectIfNeeded(key); } @Override public byte[] keyToBytes(Object o) { return delegate.keyToBytes(o); } @Override public byte[] valueToBytes(Object o) { return delegate.valueToBytes(o); } @Override public void resolveStorage(boolean objectStorage) { delegate.resolveStorage(objectStorage); } @Override public CompletionStage<Void> updateBloomFilter() { return delegate.updateBloomFilter(); } @Override public SocketAddress addNearCacheListener(Object listener, int bloomFilterBits) { return delegate.addNearCacheListener(listener, bloomFilterBits); } @Override public String getName() { return delegate.getName(); } @Override public DataFormat getDataFormat() { return delegate.getDataFormat(); } @Override public <E> Publisher<CacheEntry<K, E>> publishEntries(String filterConverterFactory, Object[] filterConverterParams, Set<Integer> segments, int batchSize) { return delegate.publishEntries(filterConverterFactory, filterConverterParams, segments, batchSize); } @Override public CloseableIterator<CacheEntry<Object, Object>> retrieveEntriesByQuery(RemoteQuery query, Set<Integer> segments, int batchSize) { return delegate.retrieveEntriesByQuery(query, segments, batchSize); } @Override public <E> Publisher<CacheEntry<K, E>> publishEntriesByQuery(RemoteQuery query, Set<Integer> segments, int batchSize) { return delegate.publishEntriesByQuery(query, segments, batchSize); } @Override public CloseableIterator<CacheEntry<Object, Object>> retrieveEntriesWithMetadata(Set<Integer> segments, int batchSize) { return delegate.retrieveEntriesWithMetadata(segments, batchSize); } @Override public Publisher<CacheEntry<K, V>> publishEntriesWithMetadata(Set<Integer> segments, int batchSize) { return delegate.publishEntriesWithMetadata(segments, batchSize); } @Override public TransactionManager getTransactionManager() { return delegate.getTransactionManager(); } @Override public boolean isTransactional() { return delegate.isTransactional(); } @Override public void close() throws Exception { delegate.close(); } }
9,592
32.07931
174
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/VersionedMetadata.java
package org.infinispan.hotrod.impl.cache; /** * VersionedMetadata * @since 14.0 */ public interface VersionedMetadata extends Versioned, Metadata { }
154
16.222222
64
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/cache/RemoteQuery.java
package org.infinispan.hotrod.impl.cache; import java.util.HashMap; import java.util.Map; import org.infinispan.api.common.CacheOptions; /** * @since 14.0 **/ public class RemoteQuery { final String query; final Map<String, Object> params = new HashMap<>(); Integer limit; Long skip; public RemoteQuery(String query, CacheOptions options) { this.query = query; } public void param(String name, Object value) { params.put(name, value); } public void limit(int limit) { this.limit = limit; } public void skip(long skip) { this.skip = skip; } public Object[] toFactoryParams() { if (params.isEmpty()) { return new Object[]{query}; } Object[] factoryParams = new Object[1 + params.size() * 2]; factoryParams[0] = query; int i = 1; for (Map.Entry<String, Object> e : params.entrySet()) { factoryParams[i++] = e.getKey(); factoryParams[i++] = e.getValue(); } return factoryParams; } }
1,030
20.93617
65
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/topology/ClusterInfo.java
package org.infinispan.hotrod.impl.topology; import java.net.InetSocketAddress; import java.util.List; import java.util.Objects; import org.infinispan.commons.util.Immutables; import org.infinispan.hotrod.configuration.ClientIntelligence; /** * Cluster definition * */ public class ClusterInfo { private final String clusterName; private final List<InetSocketAddress> servers; // Topology age provides a way to avoid concurrent cluster view changes, // affecting a cluster switch. After a cluster switch, the topology age is // increased and so any old requests that might have received topology // updates won't be allowed to apply since they refer to older views. private final int topologyAge; private final ClientIntelligence intelligence; public ClusterInfo(String clusterName, List<InetSocketAddress> servers, ClientIntelligence intelligence) { this(clusterName, servers, -1, intelligence); } private ClusterInfo(String clusterName, List<InetSocketAddress> servers, int topologyAge, ClientIntelligence intelligence) { this.clusterName = clusterName; this.servers = Immutables.immutableListCopy(servers); this.topologyAge = topologyAge; this.intelligence = Objects.requireNonNull(intelligence); } public ClusterInfo withTopologyAge(int topologyAge) { return new ClusterInfo(clusterName, servers, topologyAge, intelligence); } public String getName() { return clusterName; } public List<InetSocketAddress> getInitialServers() { return servers; } public int getTopologyAge() { return topologyAge; } public ClientIntelligence getIntelligence() { return intelligence; } @Override public String toString() { return "ClusterInfo{" + "name='" + clusterName + '\'' + ", servers=" + servers + ", age=" + topologyAge + ", intelligence=" + intelligence + '}'; } }
1,973
29.369231
127
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/topology/CacheInfo.java
package org.infinispan.hotrod.impl.topology; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.commons.marshall.WrappedBytes; import org.infinispan.commons.util.Immutables; import org.infinispan.commons.util.IntSets; import org.infinispan.hotrod.configuration.ClientIntelligence; import org.infinispan.hotrod.configuration.FailoverRequestBalancingStrategy; import org.infinispan.hotrod.impl.ClientTopology; import org.infinispan.hotrod.impl.cache.CacheTopologyInfo; import org.infinispan.hotrod.impl.cache.CacheTopologyInfoImpl; import org.infinispan.hotrod.impl.consistenthash.ConsistentHash; import org.infinispan.hotrod.impl.protocol.HotRodConstants; /** * Holds all the cluster topology information the client has for a single cache. * * <p>Each segment is mapped to a single server, even though the Hot Rod protocol and {@link ConsistentHash} * implementations allow more than one owner.</p> * * @since 14.0 */ public class CacheInfo { private final String cacheName; // The topology age at the time this topology was received private final int topologyAge; // The balancer is final, but using it still needs synchronization because it is not thread-safe private final FailoverRequestBalancingStrategy balancer; private final int numSegments; private final List<InetSocketAddress> servers; private final Map<SocketAddress, Set<Integer>> primarySegments; private final ConsistentHash consistentHash; private final AtomicReference<ClientTopology> clientTopologyRef; private final ClientTopology clientTopology; public CacheInfo(WrappedBytes cacheName, FailoverRequestBalancingStrategy balancer, int topologyAge, List<InetSocketAddress> servers, ClientIntelligence intelligence) { this.balancer = balancer; this.topologyAge = topologyAge; this.cacheName = cacheName == null || cacheName.getLength() == 0 ? "<default>" : new String(cacheName.getBytes(), HotRodConstants.HOTROD_STRING_CHARSET); this.numSegments = -1; this.clientTopology = new ClientTopology(HotRodConstants.DEFAULT_CACHE_TOPOLOGY, intelligence); this.consistentHash = null; this.servers = Immutables.immutableListCopy(servers); // Before the first topology update or after a topology-aware (non-hash) topology update this.primarySegments = null; clientTopologyRef = new AtomicReference<>(clientTopology); } public void updateBalancerServers() { // The servers list is immutable, so it doesn't matter that the balancer see it as a Collection<SocketAddress> balancer.setServers((List) servers); } public CacheInfo withNewServers(int topologyAge, int topologyId, List<InetSocketAddress> servers) { return withNewServers(topologyAge, topologyId, servers, clientTopologyRef.get().getClientIntelligence()); } public CacheInfo withNewServers(int topologyAge, int topologyId, List<InetSocketAddress> servers, ClientIntelligence intelligence) { return new CacheInfo(cacheName, balancer, topologyAge, servers, null, -1, clientTopologyRef, new ClientTopology(topologyId, intelligence)); } public CacheInfo withNewHash(int topologyAge, int topologyId, List<InetSocketAddress> servers, ConsistentHash consistentHash, int numSegments) { return new CacheInfo(cacheName, balancer, topologyAge, servers, consistentHash, numSegments, clientTopologyRef, new ClientTopology(topologyId, getIntelligence())); } private CacheInfo(String cacheName, FailoverRequestBalancingStrategy balancer, int topologyAge, List<InetSocketAddress> servers, ConsistentHash consistentHash, int numSegments, AtomicReference<ClientTopology> clientTopologyRef, ClientTopology clientTopology) { this.balancer = balancer; this.topologyAge = topologyAge; this.cacheName = cacheName; this.numSegments = numSegments; this.consistentHash = consistentHash; this.clientTopology = clientTopology; this.clientTopologyRef = clientTopologyRef; this.servers = Immutables.immutableListCopy(servers); if (numSegments > 0) { // After the servers sent a hash-aware topology update this.primarySegments = consistentHash.getPrimarySegmentsByServer(); } else { // Before the first topology update or after a topology-aware (non-hash) topology update this.primarySegments = null; } } public String getCacheName() { return cacheName; } public int getTopologyAge() { return topologyAge; } public FailoverRequestBalancingStrategy getBalancer() { return balancer; } public int getNumSegments() { return numSegments; } public int getTopologyId() { return clientTopology.getTopologyId(); } public AtomicReference<ClientTopology> getClientTopologyRef() { return clientTopologyRef; } public List<InetSocketAddress> getServers() { return servers; } public Map<SocketAddress, Set<Integer>> getPrimarySegments() { if (primarySegments == null) { return Collections.emptyMap(); } return primarySegments; } public ConsistentHash getConsistentHash() { return consistentHash; } public CacheTopologyInfo getCacheTopologyInfo() { Map<SocketAddress, Set<Integer>> segmentsByServer; if (consistentHash != null) { segmentsByServer = consistentHash.getSegmentsByServer(); } else { segmentsByServer = new HashMap<>(servers.size()); for (InetSocketAddress server : servers) { segmentsByServer.put(server, IntSets.immutableEmptySet()); } } return new CacheTopologyInfoImpl(segmentsByServer, numSegments > 0 ? numSegments : null, getTopologyId()); } private ClientIntelligence getIntelligence() { return clientTopology.getClientIntelligence(); } public void updateClientTopologyRef() { clientTopologyRef.set(clientTopology); } }
6,327
37.585366
171
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/RemoteMultimapCacheImpl.java
package org.infinispan.hotrod.impl.multimap; import java.util.Collection; import java.util.concurrent.CompletionStage; import org.infinispan.api.common.CacheEntryCollection; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.commons.marshall.AdaptiveBufferSizePredictor; import org.infinispan.commons.marshall.BufferSizePredictor; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.hotrod.exceptions.RemoteCacheManagerNotStartedException; import org.infinispan.hotrod.impl.HotRodTransport; import org.infinispan.hotrod.impl.cache.RemoteCacheImpl; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.hotrod.impl.multimap.operations.ContainsEntryMultimapOperation; import org.infinispan.hotrod.impl.multimap.operations.ContainsKeyMultimapOperation; import org.infinispan.hotrod.impl.multimap.operations.ContainsValueMultimapOperation; import org.infinispan.hotrod.impl.multimap.operations.GetKeyMultimapOperation; import org.infinispan.hotrod.impl.multimap.operations.GetKeyWithMetadataMultimapOperation; import org.infinispan.hotrod.impl.multimap.operations.MultimapOperationsFactory; import org.infinispan.hotrod.impl.multimap.operations.PutKeyValueMultimapOperation; import org.infinispan.hotrod.impl.multimap.operations.RemoveEntryMultimapOperation; import org.infinispan.hotrod.impl.multimap.operations.RemoveKeyMultimapOperation; import org.infinispan.hotrod.marshall.MarshallerUtil; import org.infinispan.hotrod.multimap.RemoteMultimapCache; /** * Remote implementation of {@link RemoteMultimapCache} * * @since 14.0 */ public class RemoteMultimapCacheImpl<K, V> implements RemoteMultimapCache<K, V> { private static final Log log = LogFactory.getLog(RemoteMultimapCacheImpl.class, Log.class); private final RemoteCacheImpl<K, Collection<V>> cache; private final HotRodTransport hotRodTransport; private MultimapOperationsFactory operationsFactory; private Marshaller marshaller; private final BufferSizePredictor keySizePredictor = new AdaptiveBufferSizePredictor(); private final BufferSizePredictor valueSizePredictor = new AdaptiveBufferSizePredictor(); private final boolean supportsDuplicates; public void init() { operationsFactory = new MultimapOperationsFactory( hotRodTransport.getChannelFactory(), cache.getName(), hotRodTransport.getConfiguration(), hotRodTransport.getCodec(), cache.getDataFormat(), cache.getClientStatistics()); this.marshaller = hotRodTransport.getMarshaller(); } public RemoteMultimapCacheImpl(HotRodTransport hotRodTransport, RemoteCacheImpl<K, Collection<V>> cache) { this(hotRodTransport, cache, false); } public RemoteMultimapCacheImpl(HotRodTransport hotRodTransport, RemoteCacheImpl<K, Collection<V>> cache, boolean supportsDuplicates) { if (log.isTraceEnabled()) { log.tracef("Creating multimap remote cache: %s", cache.getName()); } this.cache = cache; this.hotRodTransport = hotRodTransport; this.supportsDuplicates = supportsDuplicates; } @Override public CompletionStage<Void> put(K key, V value, CacheWriteOptions options) { if (log.isTraceEnabled()) { log.tracef("About to add (K,V): (%s, %s) %s", key, value, options); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); byte[] marshallValue = MarshallerUtil.obj2bytes(marshaller, value, valueSizePredictor); PutKeyValueMultimapOperation<K> op = operationsFactory.newPutKeyValueOperation(objectKey, marshallKey, marshallValue, CacheWriteOptions.DEFAULT, supportsDuplicates); return op.execute(); } @Override public CompletionStage<Collection<V>> get(K key, CacheOptions options) { if (log.isTraceEnabled()) { log.tracef("About to call get (K): (%s)", key); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); GetKeyMultimapOperation<K, V> gco = operationsFactory.newGetKeyMultimapOperation(objectKey, marshallKey, options, supportsDuplicates); return gco.execute(); } @Override public CompletionStage<CacheEntryCollection<K, V>> getWithMetadata(K key, CacheOptions options) { if (log.isTraceEnabled()) { log.tracef("About to call getWithMetadata (K): (%s)", key); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); GetKeyWithMetadataMultimapOperation<K, V> operation = operationsFactory.newGetKeyWithMetadataMultimapOperation(objectKey, marshallKey, options, supportsDuplicates); return operation.execute(); } @Override public CompletionStage<Boolean> remove(K key, CacheOptions options) { if (log.isTraceEnabled()) { log.tracef("About to remove (K): (%s)", key); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); RemoveKeyMultimapOperation<K> removeOperation = operationsFactory.newRemoveKeyOperation(objectKey, marshallKey, options, supportsDuplicates); return removeOperation.execute(); } @Override public CompletionStage<Boolean> remove(K key, V value, CacheOptions options) { if (log.isTraceEnabled()) { log.tracef("About to remove (K,V): (%s, %s)", key, value); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); byte[] marshallValue = MarshallerUtil.obj2bytes(marshaller, value, valueSizePredictor); RemoveEntryMultimapOperation<K> removeOperation = operationsFactory.newRemoveEntryOperation(objectKey, marshallKey, marshallValue, options, supportsDuplicates); return removeOperation.execute(); } @Override public CompletionStage<Boolean> containsKey(K key, CacheOptions options) { if (log.isTraceEnabled()) { log.tracef("About to call contains (K): (%s)", key); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); ContainsKeyMultimapOperation<K> containsKeyOperation = operationsFactory.newContainsKeyOperation(objectKey, marshallKey, options, supportsDuplicates); return containsKeyOperation.execute(); } @Override public CompletionStage<Boolean> containsValue(V value, CacheOptions options) { if (log.isTraceEnabled()) { log.tracef("About to call contains (V): (%s)", value); } assertRemoteCacheManagerIsStarted(); byte[] marshallValue = MarshallerUtil.obj2bytes(marshaller, value, valueSizePredictor); ContainsValueMultimapOperation containsValueOperation = operationsFactory.newContainsValueOperation(marshallValue, options, supportsDuplicates); return containsValueOperation.execute(); } @Override public CompletionStage<Boolean> containsEntry(K key, V value, CacheOptions options) { if (log.isTraceEnabled()) { log.tracef("About to call contais(K,V): (%s, %s)", key, value); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); byte[] marshallValue = MarshallerUtil.obj2bytes(marshaller, value, valueSizePredictor); ContainsEntryMultimapOperation<K> containsOperation = operationsFactory.newContainsEntryOperation(objectKey, marshallKey, marshallValue, options, supportsDuplicates); return containsOperation.execute(); } @Override public CompletionStage<Long> size(CacheOptions options) { if (log.isTraceEnabled()) { log.trace("About to call size"); } assertRemoteCacheManagerIsStarted(); return operationsFactory.newSizeOperation(supportsDuplicates).execute(); } @Override public boolean supportsDuplicates() { return supportsDuplicates; } private void assertRemoteCacheManagerIsStarted() { if (!hotRodTransport.isStarted()) { String message = "Cannot perform operations on a multimap cache associated with an unstarted RemoteMultimapCacheManager."; if (log.isInfoEnabled()) { log.unstartedRemoteCacheManager(); } throw new RemoteCacheManagerNotStartedException(message); } } private boolean isObjectStorage() { return cache.isObjectStorage(); } }
9,073
44.59799
172
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/protocol/MultimapHotRodConstants.java
package org.infinispan.hotrod.impl.multimap.protocol; /** * Multimap hotrod constants * * @since 14.0 */ public interface MultimapHotRodConstants { // requests byte GET_MULTIMAP_REQUEST = 0x67; byte GET_MULTIMAP_WITH_METADATA_REQUEST = 0x69; byte PUT_MULTIMAP_REQUEST = 0x6B; byte REMOVE_KEY_MULTIMAP_REQUEST = 0x6D; byte REMOVE_ENTRY_MULTIMAP_REQUEST = 0x6F; byte SIZE_MULTIMAP_REQUEST = 0x71; byte CONTAINS_ENTRY_REQUEST = 0x73; byte CONTAINS_KEY_MULTIMAP_REQUEST = 0x75; short CONTAINS_VALUE_MULTIMAP_REQUEST = 0x77; // responses byte GET_MULTIMAP_RESPONSE = 0x68; byte GET_MULTIMAP_WITH_METADATA_RESPONSE = 0x6A; byte PUT_MULTIMAP_RESPONSE = 0x6C; byte REMOVE_KEY_MULTIMAP_RESPONSE = 0x6E; byte REMOVE_ENTRY_MULTIMAP_RESPONSE = 0x70; byte SIZE_MULTIMAP_RESPONSE = 0x72; byte CONTAINS_ENTRY_RESPONSE = 0x74; short CONTAINS_KEY_MULTIMAP_RESPONSE = 0x76; short CONTAINS_VALUE_MULTIMAP_RESPONSE = 0x78; }
972
29.40625
53
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/operations/RemoveEntryMultimapOperation.java
package org.infinispan.hotrod.impl.multimap.operations; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.REMOVE_ENTRY_MULTIMAP_REQUEST; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.REMOVE_ENTRY_MULTIMAP_RESPONSE; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.operations.OperationContext; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import net.jcip.annotations.Immutable; /** * Implements "remove" for multimap as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @since 14.0 */ @Immutable public class RemoveEntryMultimapOperation<K> extends AbstractMultimapKeyValueOperation<K, Boolean> { public RemoveEntryMultimapOperation(OperationContext operationContext, K key, byte[] keyBytes, byte[] value, CacheOptions options, boolean supportsDuplicates) { super(operationContext, REMOVE_ENTRY_MULTIMAP_REQUEST, REMOVE_ENTRY_MULTIMAP_RESPONSE, key, keyBytes, value, options, null, supportsDuplicates); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(Boolean.FALSE); } else { complete(buf.readByte() == 1 ? Boolean.TRUE : Boolean.FALSE); } } }
1,480
40.138889
163
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/operations/GetKeyWithMetadataMultimapOperation.java
package org.infinispan.hotrod.impl.multimap.operations; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.GET_MULTIMAP_WITH_METADATA_REQUEST; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.GET_MULTIMAP_WITH_METADATA_RESPONSE; import static org.infinispan.hotrod.marshall.MarshallerUtil.bytes2obj; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import org.infinispan.api.common.CacheEntryCollection; import org.infinispan.api.common.CacheEntryExpiration; import org.infinispan.api.common.CacheEntryVersion; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.cache.CacheEntryMetadataImpl; import org.infinispan.hotrod.impl.cache.CacheEntryVersionImpl; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.hotrod.impl.multimap.metadata.CacheEntryCollectionImpl; import org.infinispan.hotrod.impl.operations.OperationContext; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import net.jcip.annotations.Immutable; /** * Implements "getWithMetadata" as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol * specification</a>. * * @since 14.0 */ @Immutable public class GetKeyWithMetadataMultimapOperation<K, V> extends AbstractMultimapKeyOperation<K, CacheEntryCollection<K, V>> { private static final Log log = LogFactory.getLog(GetKeyWithMetadataMultimapOperation.class); public GetKeyWithMetadataMultimapOperation(OperationContext operationContext, K key, byte[] keyBytes, CacheOptions options, DataFormat dataFormat, boolean supportsDuplicates) { super(operationContext, GET_MULTIMAP_WITH_METADATA_REQUEST, GET_MULTIMAP_WITH_METADATA_RESPONSE, key, keyBytes, options, dataFormat, supportsDuplicates); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(new CacheEntryCollectionImpl<>(key, Collections.emptySet())); return; } if (!HotRodConstants.isSuccess(status)) { complete(null); return; } short flags = buf.readByte(); long creation = -1; int lifespan = -1; long lastUsed = -1; int maxIdle = -1; if ((flags & INFINITE_LIFESPAN) != INFINITE_LIFESPAN) { creation = buf.readLong(); lifespan = ByteBufUtil.readVInt(buf); } if ((flags & INFINITE_MAXIDLE) != INFINITE_MAXIDLE) { lastUsed = buf.readLong(); maxIdle = ByteBufUtil.readVInt(buf); } CacheEntryExpiration expiration; if (lifespan < 0) { if (maxIdle < 0) { expiration = CacheEntryExpiration.IMMORTAL; } else { expiration = CacheEntryExpiration.withMaxIdle(Duration.ofSeconds(maxIdle)); } } else { if (maxIdle < 0) { expiration = CacheEntryExpiration.withLifespan(Duration.ofSeconds(lifespan)); } else { expiration = CacheEntryExpiration.withLifespanAndMaxIdle(Duration.ofSeconds(lifespan), Duration.ofSeconds(maxIdle)); } } CacheEntryVersion version = new CacheEntryVersionImpl(buf.readLong()); if (log.isTraceEnabled()) { log.tracef("Received version: %d", version); } int size = ByteBufUtil.readVInt(buf); Collection<V> values = new ArrayList<>(size); for (int i = 0; i < size; ++i) { V value = bytes2obj(operationContext.getChannelFactory().getMarshaller(), ByteBufUtil.readArray(buf), dataFormat().isObjectStorage(), operationContext.getConfiguration().getClassAllowList()); values.add(value); } complete(new CacheEntryCollectionImpl<>(key, values, new CacheEntryMetadataImpl(creation, lastUsed, expiration, version))); } }
4,241
43.1875
200
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/operations/RemoveKeyMultimapOperation.java
package org.infinispan.hotrod.impl.multimap.operations; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.REMOVE_KEY_MULTIMAP_REQUEST; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.REMOVE_KEY_MULTIMAP_RESPONSE; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.operations.OperationContext; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; /** * Implements "remove" for multimap cache as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot * Rod protocol specification</a>. * * @since 14.0 */ public class RemoveKeyMultimapOperation<K> extends AbstractMultimapKeyOperation<K, Boolean> { public RemoveKeyMultimapOperation(OperationContext operationContext, K key, byte[] keyBytes, CacheOptions options, boolean supportsDuplicates) { super(operationContext, REMOVE_KEY_MULTIMAP_REQUEST, REMOVE_KEY_MULTIMAP_RESPONSE, key, keyBytes, options, null, supportsDuplicates); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(Boolean.FALSE); } else { complete(buf.readByte() == 1 ? Boolean.TRUE : Boolean.FALSE); } } }
1,434
41.205882
139
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/operations/SizeMultimapOperation.java
package org.infinispan.hotrod.impl.multimap.operations; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.SIZE_MULTIMAP_REQUEST; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.SIZE_MULTIMAP_RESPONSE; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.operations.OperationContext; import org.infinispan.hotrod.impl.operations.RetryOnFailureOperation; import org.infinispan.hotrod.impl.protocol.Codec; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Implements "size" for multimap cache as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @since 14.0 */ public class SizeMultimapOperation extends RetryOnFailureOperation<Long> { private final boolean supportsDuplicates; protected SizeMultimapOperation(OperationContext operationContext, CacheOptions options, boolean supportsDuplicates) { super(operationContext, SIZE_MULTIMAP_REQUEST, SIZE_MULTIMAP_RESPONSE, options, null); this.supportsDuplicates = supportsDuplicates; } @Override protected void executeOperation(Channel channel) { sendHeaderAndRead(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(ByteBufUtil.readVLong(buf)); } @Override protected void sendHeader(Channel channel) { Codec codec = operationContext.getCodec(); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + codec.estimateSizeMultimapSupportsDuplicated()); operationContext.getCodec().writeHeader(buf, header); codec.writeMultimapSupportDuplicates(buf, supportsDuplicates); channel.writeAndFlush(buf); } }
1,927
37.56
126
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/operations/AbstractMultimapKeyOperation.java
package org.infinispan.hotrod.impl.multimap.operations; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.operations.AbstractKeyOperation; import org.infinispan.hotrod.impl.operations.OperationContext; import org.infinispan.hotrod.impl.protocol.Codec; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; public abstract class AbstractMultimapKeyOperation<K, T> extends AbstractKeyOperation<K, T> { protected final boolean supportsDuplicates; protected AbstractMultimapKeyOperation(OperationContext operationContext, short requestCode, short responseCode, K key, byte[] keyBytes, CacheOptions options, DataFormat dataFormat, boolean supportsDuplicates) { super(operationContext, requestCode, responseCode, key, keyBytes, options, dataFormat); this.supportsDuplicates = supportsDuplicates; } @Override public void executeOperation(Channel channel) { scheduleRead(channel); sendArrayOperation(channel, keyBytes); } @Override protected void sendArrayOperation(Channel channel, byte[] array) { Codec codec = operationContext.getCodec(); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + ByteBufUtil.estimateArraySize(array) + codec.estimateSizeMultimapSupportsDuplicated() ); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, array); codec.writeMultimapSupportDuplicates(buf, supportsDuplicates); channel.writeAndFlush(buf); } }
1,718
41.975
168
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/operations/ContainsKeyMultimapOperation.java
package org.infinispan.hotrod.impl.multimap.operations; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.CONTAINS_KEY_MULTIMAP_REQUEST; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.CONTAINS_KEY_MULTIMAP_RESPONSE; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.operations.OperationContext; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; /** * Implements "contains key" for multimap cache as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot * Rod protocol specification</a>. * * @since 14.0 */ public class ContainsKeyMultimapOperation<K> extends AbstractMultimapKeyOperation<K, Boolean> { public ContainsKeyMultimapOperation(OperationContext operationContext, K key, byte[] keyBytes, CacheOptions options, boolean supportsDuplicates) { super(operationContext, CONTAINS_KEY_MULTIMAP_REQUEST, CONTAINS_KEY_MULTIMAP_RESPONSE, key, keyBytes, options, null, supportsDuplicates); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(Boolean.FALSE); } else { complete(buf.readByte() == 1 ? Boolean.TRUE : Boolean.FALSE); } } }
1,454
41.794118
143
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/operations/GetKeyMultimapOperation.java
package org.infinispan.hotrod.impl.multimap.operations; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.GET_MULTIMAP_REQUEST; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.GET_MULTIMAP_RESPONSE; import static org.infinispan.hotrod.marshall.MarshallerUtil.bytes2obj; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.operations.OperationContext; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import net.jcip.annotations.Immutable; /** * Implements "get" for multimap as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @since 14.0 */ @Immutable public class GetKeyMultimapOperation<K, V> extends AbstractMultimapKeyOperation<K, Collection<V>> { private int size; private Collection<V> result; public GetKeyMultimapOperation(OperationContext operationContext, K key, byte[] keyBytes, CacheOptions options, DataFormat dataFormat, boolean supportsDuplicates) { super(operationContext, GET_MULTIMAP_REQUEST, GET_MULTIMAP_RESPONSE, key, keyBytes, options, dataFormat, supportsDuplicates); } @Override protected void reset() { super.reset(); result = null; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(Collections.emptySet()); return; } else if (result == null) { size = ByteBufUtil.readVInt(buf); result = supportsDuplicates ? new ArrayList<>(size) : new HashSet<>(size); decoder.checkpoint(); } while (result.size() < size) { V value = bytes2obj(operationContext.getChannelFactory().getMarshaller(), ByteBufUtil.readArray(buf), dataFormat().isObjectStorage(), operationContext.getConfiguration().getClassAllowList()); result.add(value); decoder.checkpoint(); } complete(result); } }
2,410
37.269841
200
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/operations/PutKeyValueMultimapOperation.java
package org.infinispan.hotrod.impl.multimap.operations; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.PUT_MULTIMAP_REQUEST; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.PUT_MULTIMAP_RESPONSE; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.exceptions.InvalidResponseException; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.operations.OperationContext; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import net.jcip.annotations.Immutable; /** * Implements "put" for multimap cache as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @since 14.0 */ @Immutable public class PutKeyValueMultimapOperation<K> extends AbstractMultimapKeyValueOperation<K, Void> { public PutKeyValueMultimapOperation(OperationContext operationContext, K key, byte[] keyBytes, byte[] value, CacheWriteOptions options, DataFormat dataFormat, boolean supportsDuplicates) { super(operationContext, PUT_MULTIMAP_REQUEST, PUT_MULTIMAP_RESPONSE, key, keyBytes, value, options, dataFormat, supportsDuplicates); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (!HotRodConstants.isSuccess(status)) { throw new InvalidResponseException("Unexpected response status: " + Integer.toHexString(status)); } complete(null); } }
1,721
42.05
138
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/operations/ContainsEntryMultimapOperation.java
package org.infinispan.hotrod.impl.multimap.operations; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.CONTAINS_ENTRY_REQUEST; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.CONTAINS_ENTRY_RESPONSE; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.operations.OperationContext; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import net.jcip.annotations.Immutable; /** * Implements "contains entry" for multimap as defined by <a * href="http://infinispan.org/docs/dev/user_guide/user_guide.html#hot_rod_protocol">Hot Rod protocol * specification</a>. * * @since 14.0 */ @Immutable public class ContainsEntryMultimapOperation<K> extends AbstractMultimapKeyValueOperation<K, Boolean> { public ContainsEntryMultimapOperation(OperationContext operationContext, K key, byte[] keyBytes, byte[] value, CacheOptions options, boolean supportsDuplicates) { super(operationContext, CONTAINS_ENTRY_REQUEST, CONTAINS_ENTRY_RESPONSE, key, keyBytes, value, options, null, supportsDuplicates); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(Boolean.FALSE); } else { complete(buf.readByte() == 1 ? Boolean.TRUE : Boolean.FALSE); } } }
1,535
39.421053
136
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/operations/AbstractMultimapKeyValueOperation.java
package org.infinispan.hotrod.impl.multimap.operations; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.api.common.CacheEntryExpiration; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.operations.AbstractKeyValueOperation; import org.infinispan.hotrod.impl.operations.OperationContext; import org.infinispan.hotrod.impl.protocol.Codec; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; public abstract class AbstractMultimapKeyValueOperation<K, T> extends AbstractKeyValueOperation<K, T> { protected final boolean supportsDuplicates; protected AbstractMultimapKeyValueOperation(OperationContext operationContext, short requestCode, short responseCode, K key, byte[] keyBytes, byte[] value, CacheOptions options, DataFormat dataFormat, boolean supportsDuplicates) { super(operationContext, requestCode, responseCode, key, keyBytes, value, options, dataFormat); this.supportsDuplicates = supportsDuplicates; } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendKeyValueOperation(channel); } protected void sendKeyValueOperation(Channel channel) { Codec codec = operationContext.getCodec(); CacheEntryExpiration.Impl expiration = (CacheEntryExpiration.Impl) ((CacheWriteOptions) options).expiration(); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + keyBytes.length + codec.estimateExpirationSize(expiration) + value.length + codec.estimateSizeMultimapSupportsDuplicated()); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, keyBytes); codec.writeExpirationParams(buf, expiration); ByteBufUtil.writeArray(buf, value); codec.writeMultimapSupportDuplicates(buf, supportsDuplicates); channel.writeAndFlush(buf); } }
2,166
47.155556
145
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/operations/ContainsValueMultimapOperation.java
package org.infinispan.hotrod.impl.multimap.operations; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.CONTAINS_VALUE_MULTIMAP_REQUEST; import static org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants.CONTAINS_VALUE_MULTIMAP_RESPONSE; import org.infinispan.api.common.CacheEntryExpiration; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.impl.operations.OperationContext; import org.infinispan.hotrod.impl.operations.RetryOnFailureOperation; import org.infinispan.hotrod.impl.protocol.Codec; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Implements "contains value" for multimap cache as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot * Rod protocol specification</a>. * * @since 14.0 */ public class ContainsValueMultimapOperation extends RetryOnFailureOperation<Boolean> { protected final byte[] value; private final boolean supportsDuplicates; protected ContainsValueMultimapOperation(OperationContext operationContext, int flags, byte[] value, CacheOptions options, boolean supportsDuplicates) { super(operationContext, CONTAINS_VALUE_MULTIMAP_REQUEST, CONTAINS_VALUE_MULTIMAP_RESPONSE, options, null); this.value = value; this.supportsDuplicates = supportsDuplicates; } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendValueOperation(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(Boolean.FALSE); } else { complete(buf.readByte() == 1 ? Boolean.TRUE : Boolean.FALSE); } } protected void sendValueOperation(Channel channel) { CacheEntryExpiration.Impl expiration = (CacheEntryExpiration.Impl) ((CacheWriteOptions) options).expiration(); Codec codec = operationContext.getCodec(); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + codec.estimateExpirationSize(expiration) + ByteBufUtil.estimateArraySize(value) + codec.estimateSizeMultimapSupportsDuplicated()); codec.writeHeader(buf, header); codec.writeExpirationParams(buf, expiration); ByteBufUtil.writeArray(buf, value); codec.writeMultimapSupportDuplicates(buf, supportsDuplicates); channel.writeAndFlush(buf); } }
2,756
41.415385
125
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/operations/MultimapOperationsFactory.java
package org.infinispan.hotrod.impl.multimap.operations; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.HotRodFlag; import org.infinispan.hotrod.configuration.HotRodConfiguration; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.cache.ClientStatistics; import org.infinispan.hotrod.impl.operations.HotRodOperation; import org.infinispan.hotrod.impl.operations.OperationContext; import org.infinispan.hotrod.impl.protocol.Codec; import org.infinispan.hotrod.impl.transport.netty.ChannelFactory; import net.jcip.annotations.Immutable; /** * Factory for {@link HotRodOperation} objects on Multimap. * * @since 14.0 */ @Immutable public class MultimapOperationsFactory { private final ThreadLocal<Integer> flagsMap = new ThreadLocal<>(); private final OperationContext operationContext; private final DataFormat dataFormat; public MultimapOperationsFactory(ChannelFactory channelFactory, String cacheName, HotRodConfiguration configuration, Codec codec, DataFormat dataFormat, ClientStatistics clientStatistics) { this.operationContext = new OperationContext(channelFactory, codec, null, configuration, clientStatistics, null, cacheName); this.dataFormat = dataFormat; } public <K, V> GetKeyMultimapOperation<K, V> newGetKeyMultimapOperation(K key, byte[] keyBytes, CacheOptions options, boolean supportsDuplicates) { return new GetKeyMultimapOperation<>(operationContext, key, keyBytes, options, dataFormat, supportsDuplicates); } public <K, V> GetKeyWithMetadataMultimapOperation<K, V> newGetKeyWithMetadataMultimapOperation(K key, byte[] keyBytes, CacheOptions options, boolean supportsDuplicates) { return new GetKeyWithMetadataMultimapOperation<>(operationContext, key, keyBytes, options, dataFormat, supportsDuplicates); } public <K> PutKeyValueMultimapOperation<K> newPutKeyValueOperation(K key, byte[] keyBytes, byte[] value, CacheWriteOptions options, boolean supportsDuplicates) { return new PutKeyValueMultimapOperation<>(operationContext, key, keyBytes, value, options, null, supportsDuplicates); } public <K> RemoveKeyMultimapOperation<K> newRemoveKeyOperation(K key, byte[] keyBytes, CacheOptions options, boolean supportsDuplicates) { return new RemoveKeyMultimapOperation<>(operationContext, key, keyBytes, options, supportsDuplicates); } public <K> RemoveEntryMultimapOperation<K> newRemoveEntryOperation(K key, byte[] keyBytes, byte[] value, CacheOptions options, boolean supportsDuplicates) { return new RemoveEntryMultimapOperation<>(operationContext, key, keyBytes, value, options, supportsDuplicates); } public <K> ContainsEntryMultimapOperation<K> newContainsEntryOperation(K key, byte[] keyBytes, byte[] value, CacheOptions options, boolean supportsDuplicates) { return new ContainsEntryMultimapOperation<>(operationContext, key, keyBytes, value, options, supportsDuplicates); } public <K> ContainsKeyMultimapOperation<K> newContainsKeyOperation(K key, byte[] keyBytes, CacheOptions options, boolean supportsDuplicates) { return new ContainsKeyMultimapOperation<>(operationContext, key, keyBytes, options, supportsDuplicates); } public ContainsValueMultimapOperation newContainsValueOperation(byte[] value, CacheOptions options, boolean supportsDuplicates) { return new ContainsValueMultimapOperation(operationContext, flags(), value, options, supportsDuplicates); } public SizeMultimapOperation newSizeOperation(boolean supportsDuplicates) { return new SizeMultimapOperation(operationContext, CacheOptions.DEFAULT, supportsDuplicates); } public int flags() { Integer threadLocalFlags = this.flagsMap.get(); this.flagsMap.remove(); int intFlags = 0; if (threadLocalFlags != null) { intFlags |= threadLocalFlags.intValue(); } return intFlags; } private int flags(long lifespan, long maxIdle) { int intFlags = flags(); if (lifespan == 0) { intFlags |= HotRodFlag.DEFAULT_LIFESPAN.getFlagInt(); } if (maxIdle == 0) { intFlags |= HotRodFlag.DEFAULT_MAXIDLE.getFlagInt(); } return intFlags; } }
4,286
47.168539
192
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/multimap/metadata/CacheEntryCollectionImpl.java
package org.infinispan.hotrod.impl.multimap.metadata; import java.util.Collection; import java.util.Objects; import org.infinispan.api.common.CacheEntryCollection; import org.infinispan.api.common.CacheEntryMetadata; import org.infinispan.hotrod.impl.cache.CacheEntryMetadataImpl; /** * The values used in this class are assumed to be in MILLISECONDS * * @since 14.0 */ public class CacheEntryCollectionImpl<K, V> implements CacheEntryCollection<K, V> { private final K key; private final Collection<V> collection; private CacheEntryMetadata metadata; public CacheEntryCollectionImpl(K key, Collection<V> collection) { this(key, collection, new CacheEntryMetadataImpl()); } public CacheEntryCollectionImpl(K key, Collection<V> collection, CacheEntryMetadata metadata) { this.key = key; this.collection = collection; this.metadata = metadata; } @Override public K key() { return key; } @Override public Collection<V> values() { return collection; } @Override public CacheEntryMetadata metadata() { return metadata; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CacheEntryCollectionImpl<?, ?> that = (CacheEntryCollectionImpl<?, ?>) o; return key.equals(that.key) && Objects.equals(collection, that.collection) && Objects.equals(metadata, that.metadata); } @Override public int hashCode() { return Objects.hash(key, collection, metadata); } @Override public String toString() { return "CacheEntryCollectionImpl{" + "key=" + key + ", collection=" + collection + ", metadata=" + metadata + '}'; } }
1,799
25.470588
124
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/protocol/ChannelInputStream.java
package org.infinispan.hotrod.impl.protocol; import java.io.IOException; import java.util.LinkedList; import org.infinispan.hotrod.impl.cache.VersionedMetadata; import org.infinispan.hotrod.impl.transport.netty.ChannelInboundHandlerDefaults; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.timeout.IdleStateEvent; public class ChannelInputStream extends AbstractVersionedInputStream implements ChannelInboundHandlerDefaults { public static final String NAME = "stream"; private final int totalLength; private final LinkedList<ByteBuf> bufs = new LinkedList<>(); private int totalReceived, totalRead; private Throwable throwable; public ChannelInputStream(VersionedMetadata versionedMetadata, Runnable afterClose, int totalLength) { super(versionedMetadata, afterClose); this.totalLength = totalLength; } @Override public synchronized int read() throws IOException { for (;;) { while (bufs.isEmpty()) { if (totalRead >= totalLength) { return -1; } try { wait(); } catch (InterruptedException e) { IOException ioException = new IOException(e); if (throwable != null) { ioException.addSuppressed(throwable); } throw ioException; } if (throwable != null) { throw new IOException(throwable); } } ByteBuf buf = bufs.peekFirst(); if (buf.isReadable()) { ++totalRead; assert totalRead <= totalLength; return buf.readUnsignedByte(); } else { buf.release(); bufs.removeFirst(); } } } @Override public synchronized int read(byte[] b, int off, int len) throws IOException { int numRead = 0; for (;;) { while (numRead == 0 && bufs.isEmpty()) { if (totalRead >= totalLength) { return -1; } try { wait(); } catch (InterruptedException e) { IOException ioException = new IOException(e); if (throwable != null) { ioException.addSuppressed(throwable); } throw ioException; } if (throwable != null) { throw new IOException(throwable); } } if (bufs.isEmpty()) { return numRead; } ByteBuf buf = bufs.peekFirst(); int readable = buf.readableBytes(); if (readable > 0) { int prevReaderIndex = buf.readerIndex(); buf.readBytes(b, off + numRead, Math.min(len - numRead, readable)); int nowRead = buf.readerIndex() - prevReaderIndex; numRead += nowRead; totalRead += nowRead; assert totalRead <= totalLength : "Now read: " + nowRead + ", read: " + totalRead + ", length" + totalLength; if (numRead >= len) { return numRead; } } else { buf.release(); bufs.removeFirst(); } } } @Override public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf) { ByteBuf buf = (ByteBuf) msg; if (totalReceived + buf.readableBytes() <= totalLength) { bufs.add(buf); totalReceived += buf.readableBytes(); if (totalReceived == totalLength) { ctx.pipeline().remove(this); } } else if (totalReceived < totalLength) { bufs.add(buf.retainedSlice(buf.readerIndex(), totalLength - totalReceived)); buf.readerIndex(buf.readerIndex() + totalLength - totalReceived); totalReceived = totalLength; ctx.pipeline().remove(this); ctx.fireChannelRead(buf); } else { ctx.fireChannelRead(buf); } notifyAll(); } else { ctx.fireChannelRead(msg); } } @Override public synchronized void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { this.throwable = cause; notifyAll(); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { // swallow the event, this channel is not idle } else { ctx.fireUserEventTriggered(evt); } } @Override public synchronized void close() throws IOException { super.close(); for (ByteBuf buf : bufs) { buf.release(); } } public boolean moveReadable(ByteBuf buf) { if (buf.isReadable()) { int numReceived = Math.min(totalLength - totalReceived, buf.readableBytes()); bufs.add(buf.readBytes(numReceived)); totalReceived += numReceived; } return totalReceived < totalLength; } }
5,095
31.253165
121
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/protocol/AbstractVersionedInputStream.java
package org.infinispan.hotrod.impl.protocol; import java.io.IOException; import java.io.InputStream; import org.infinispan.hotrod.impl.cache.VersionedMetadata; import net.jcip.annotations.NotThreadSafe; @NotThreadSafe public abstract class AbstractVersionedInputStream extends InputStream implements VersionedMetadata { protected final VersionedMetadata versionedMetadata; protected final Runnable afterClose; public AbstractVersionedInputStream(VersionedMetadata versionedMetadata, Runnable afterClose) { this.versionedMetadata = versionedMetadata; this.afterClose = afterClose; } @Override public long getVersion() { return versionedMetadata.getVersion(); } @Override public long getCreated() { return versionedMetadata.getCreated(); } @Override public int getLifespan() { return versionedMetadata.getLifespan(); } @Override public long getLastUsed() { return versionedMetadata.getLastUsed(); } @Override public int getMaxIdle() { return versionedMetadata.getMaxIdle(); } @Override public void close() throws IOException { super.close(); if (afterClose != null) { afterClose.run(); } } }
1,236
22.339623
101
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/protocol/ChannelOutputStreamListener.java
package org.infinispan.hotrod.impl.protocol; import java.io.IOException; import io.netty.channel.Channel; public interface ChannelOutputStreamListener { void onClose(Channel channel) throws IOException; void onError(Channel channel, Throwable error); }
262
22.909091
52
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/protocol/Codec40.java
package org.infinispan.hotrod.impl.protocol; import static org.infinispan.hotrod.impl.TimeUnitParam.encodeTimeUnits; import static org.infinispan.hotrod.impl.logging.Log.HOTROD; import static org.infinispan.hotrod.impl.transport.netty.ByteBufUtil.limitedHexDump; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.time.Duration; import java.util.Arrays; import java.util.BitSet; import java.util.EnumSet; import java.util.Map; import java.util.function.Function; import java.util.function.IntConsumer; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryExpiration; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.events.cache.CacheEntryEventType; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.MediaTypeIds; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IteratorMapper; import org.infinispan.counter.api.CounterState; import org.infinispan.hotrod.configuration.ClientIntelligence; import org.infinispan.hotrod.event.ClientEvent; import org.infinispan.hotrod.event.ClientListener; import org.infinispan.hotrod.event.impl.AbstractClientEvent; import org.infinispan.hotrod.event.impl.CreatedEventImpl; import org.infinispan.hotrod.event.impl.CustomEventImpl; import org.infinispan.hotrod.event.impl.ExpiredEventImpl; import org.infinispan.hotrod.event.impl.ModifiedEventImpl; import org.infinispan.hotrod.event.impl.RemovedEventImpl; import org.infinispan.hotrod.exceptions.HotRodClientException; import org.infinispan.hotrod.exceptions.RemoteIllegalLifecycleStateException; import org.infinispan.hotrod.exceptions.RemoteNodeSuspectException; import org.infinispan.hotrod.impl.ClientTopology; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.cache.RemoteCache; import org.infinispan.hotrod.impl.counter.HotRodCounterEvent; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.hotrod.impl.operations.AbstractKeyOperation; import org.infinispan.hotrod.impl.operations.CacheOperationsFactory; import org.infinispan.hotrod.impl.operations.PingResponse; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.ChannelFactory; import io.netty.buffer.ByteBuf; /** * @since 14.0 */ public class Codec40 implements Codec, HotRodConstants { private static final Log log = LogFactory.getLog(Codec.class, Log.class); public static final String EMPTY_VALUE_CONVERTER = "org.infinispan.server.hotrod.HotRodServer$ToEmptyBytesKeyValueFilterConverter"; @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { HeaderParams headerParams = writeHeader(buf, params, HotRodConstants.VERSION_40); writeDataTypes(buf, params.dataFormat); writeOtherParams(buf, params.otherParams); return headerParams; } protected void writeDataTypes(ByteBuf buf, DataFormat dataFormat) { MediaType keyType = null, valueType = null; if (dataFormat != null) { keyType = dataFormat.getKeyType(); valueType = dataFormat.getValueType(); } writeMediaType(buf, keyType); writeMediaType(buf, valueType); } private void writeMediaType(ByteBuf buf, MediaType mediaType) { if (mediaType == null) { buf.writeByte(0); } else { Short id = MediaTypeIds.getId(mediaType); if (id != null) { buf.writeByte(1); ByteBufUtil.writeVInt(buf, id); } else { buf.writeByte(2); ByteBufUtil.writeString(buf, mediaType.toString()); } Map<String, String> parameters = mediaType.getParameters(); ByteBufUtil.writeVInt(buf, parameters.size()); parameters.forEach((key, value) -> { ByteBufUtil.writeString(buf, key); ByteBufUtil.writeString(buf, value); }); } } private void writeOtherParams(ByteBuf buf, Map<String, byte[]> parameters) { if (parameters == null) { ByteBufUtil.writeVInt(buf, 0); return; } ByteBufUtil.writeVInt(buf, parameters.size()); parameters.forEach((key, value) -> { ByteBufUtil.writeString(buf, key); ByteBufUtil.writeArray(buf, value); }); } @Override public void writeClientListenerInterests(ByteBuf buf, EnumSet<CacheEntryEventType> types) { byte listenerInterests = 0; if (types.contains(CacheEntryEventType.CREATED)) listenerInterests = (byte) (listenerInterests | 0x01); if (types.contains(CacheEntryEventType.UPDATED)) listenerInterests = (byte) (listenerInterests | 0x02); if (types.contains(CacheEntryEventType.REMOVED)) listenerInterests = (byte) (listenerInterests | 0x04); if (types.contains(CacheEntryEventType.EXPIRED)) listenerInterests = (byte) (listenerInterests | 0x08); ByteBufUtil.writeVInt(buf, listenerInterests); } @Override public void writeClientListenerParams(ByteBuf buf, ClientListener clientListener, byte[][] filterFactoryParams, byte[][] converterFactoryParams) { buf.writeByte((short) (clientListener.includeCurrentState() ? 1 : 0)); writeNamedFactory(buf, clientListener.filterFactoryName(), filterFactoryParams); writeNamedFactory(buf, clientListener.converterFactoryName(), converterFactoryParams); buf.writeByte((short) (clientListener.useRawData() ? 1 : 0)); } @Override public void writeExpirationParams(ByteBuf buf, CacheEntryExpiration.Impl expiration) { byte timeUnits = encodeTimeUnits(expiration); buf.writeByte(timeUnits); Duration lifespan = expiration.rawLifespan(); if (lifespan != null && lifespan != Duration.ZERO) { ByteBufUtil.writeVLong(buf, lifespan.toSeconds()); } Duration maxIdle = expiration.rawMaxIdle(); if (maxIdle != null && lifespan != Duration.ZERO) { ByteBufUtil.writeVLong(buf, maxIdle.toSeconds()); } } @Override public void writeBloomFilter(ByteBuf buf, int bloomFilterBits) { ByteBufUtil.writeVInt(buf, bloomFilterBits); } @Override public int estimateExpirationSize(CacheEntryExpiration.Impl expiration) { int lifespanSeconds = durationToSeconds(expiration.rawLifespan()); int maxIdleSeconds = durationToSeconds(expiration.rawMaxIdle()); return 1 + (lifespanSeconds > 0 ? ByteBufUtil.estimateVLongSize(lifespanSeconds) : 0) + (maxIdleSeconds > 0 ? ByteBufUtil.estimateVLongSize(maxIdleSeconds) : 0); } private int durationToSeconds(Duration duration) { return duration == null ? 0 : (int) duration.toSeconds(); } private void writeNamedFactory(ByteBuf buf, String factoryName, byte[][] params) { ByteBufUtil.writeString(buf, factoryName); if (!factoryName.isEmpty()) { // A named factory was written, how many parameters? if (params != null) { buf.writeByte((short) params.length); for (byte[] param : params) ByteBufUtil.writeArray(buf, param); } else { buf.writeByte((short) 0); } } } protected HeaderParams writeHeader(ByteBuf buf, HeaderParams params, byte version) { ClientTopology clientTopology = params.clientTopology.get(); buf.writeByte(HotRodConstants.REQUEST_MAGIC); ByteBufUtil.writeVLong(buf, params.messageId); buf.writeByte(version); buf.writeByte(params.opCode); ByteBufUtil.writeArray(buf, params.cacheName); ByteBufUtil.writeVInt(buf, params.flags); byte clientIntel = clientTopology.getClientIntelligence().getValue(); // set the client intelligence byte sent to read the response params.clientIntelligence = clientIntel; buf.writeByte(clientIntel); int topologyId = clientTopology.getTopologyId(); ByteBufUtil.writeVInt(buf, topologyId); if (log.isTraceEnabled()) log.tracef("[%s] Wrote header for messageId=%d. Operation code: %#04x(%s). Flags: %#x. Topology id: %s", new String(params.cacheName), params.messageId, params.opCode, Names.of(params.opCode), params.flags, topologyId); return params; } @Override public int estimateHeaderSize(HeaderParams params) { return 1 + ByteBufUtil.estimateVLongSize(params.messageId) + 1 + 1 + ByteBufUtil.estimateArraySize(params.cacheName) + ByteBufUtil.estimateVIntSize(params.flags) + 1 + 1 + ByteBufUtil.estimateVIntSize(params.getClientTopology().get().getTopologyId()); } public long readMessageId(ByteBuf buf) { short magic = buf.readUnsignedByte(); if (magic != HotRodConstants.RESPONSE_MAGIC) { if (log.isTraceEnabled()) log.tracef("Socket dump: %s", limitedHexDump(buf)); throw HOTROD.invalidMagicNumber(HotRodConstants.RESPONSE_MAGIC, magic); } return ByteBufUtil.readVLong(buf); } @Override public short readOpCode(ByteBuf buf) { return buf.readUnsignedByte(); } @Override public short readHeader(ByteBuf buf, double receivedOpCode, HeaderParams params, ChannelFactory channelFactory, SocketAddress serverAddress) { // Read both the status and new topology (if present), // before deciding how to react to error situations. short status = buf.readUnsignedByte(); readNewTopologyIfPresent(buf, params, channelFactory); // Now that all headers values have been read, check the error responses. // This avoids situations where an exceptional return ends up with // the socket containing data from previous request responses. if (receivedOpCode != params.opRespCode) { if (receivedOpCode == HotRodConstants.ERROR_RESPONSE) { checkForErrorsInResponseStatus(buf, params, status, serverAddress); } throw HOTROD.invalidResponse(new String(params.cacheName), params.opRespCode, receivedOpCode); } return status; } private static CounterState decodeOldState(short encoded) { switch (encoded & 0x03) { case 0: return CounterState.VALID; case 0x01: return CounterState.LOWER_BOUND_REACHED; case 0x02: return CounterState.UPPER_BOUND_REACHED; default: throw new IllegalStateException(); } } private static CounterState decodeNewState(short encoded) { switch (encoded & 0x0C) { case 0: return CounterState.VALID; case 0x04: return CounterState.LOWER_BOUND_REACHED; case 0x08: return CounterState.UPPER_BOUND_REACHED; default: throw new IllegalStateException(); } } @Override public HotRodCounterEvent readCounterEvent(ByteBuf buf) { short status = buf.readByte(); assert status == 0; short topology = buf.readByte(); assert topology == 0; String counterName = ByteBufUtil.readString(buf); byte[] listenerId = ByteBufUtil.readArray(buf); short encodedCounterState = buf.readByte(); long oldValue = buf.readLong(); long newValue = buf.readLong(); return new HotRodCounterEvent(listenerId, counterName, oldValue, decodeOldState(encodedCounterState), newValue, decodeNewState(encodedCounterState)); } @Override public <K> CloseableIterator<K> keyIterator(RemoteCache<K, ?> remoteCache, CacheOperationsFactory cacheOperationsFactory, CacheOptions options, IntSet segments, int batchSize) { return new IteratorMapper<>(remoteCache.retrieveEntries( // Use the ToEmptyBytesKeyValueFilterConverter to remove value payload EMPTY_VALUE_CONVERTER, segments, batchSize), e -> (K) e.key()); } @Override public <K, V> CloseableIterator<CacheEntry<K, V>> entryIterator(RemoteCache<K, V> remoteCache, IntSet segments, int batchSize) { return castEntryIterator(remoteCache.retrieveEntries(null, segments, batchSize)); } protected <K, V> CloseableIterator<CacheEntry<K, V>> castEntryIterator(CloseableIterator iterator) { return iterator; } @Override public boolean isObjectStorageHinted(PingResponse pingResponse) { return pingResponse.isObjectStorage(); } @Override public AbstractClientEvent readCacheEvent(ByteBuf buf, Function<byte[], DataFormat> listenerDataFormat, short eventTypeId, ClassAllowList allowList, SocketAddress serverAddress) { short status = buf.readUnsignedByte(); buf.readUnsignedByte(); // ignore, no topology expected ClientEvent.Type eventType; switch (eventTypeId) { case CACHE_ENTRY_CREATED_EVENT_RESPONSE: eventType = ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED; break; case CACHE_ENTRY_MODIFIED_EVENT_RESPONSE: eventType = ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED; break; case CACHE_ENTRY_REMOVED_EVENT_RESPONSE: eventType = ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED; break; case CACHE_ENTRY_EXPIRED_EVENT_RESPONSE: eventType = ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED; break; case ERROR_RESPONSE: checkForErrorsInResponseStatus(buf, null, status, serverAddress); default: throw HOTROD.unknownEvent(eventTypeId); } byte[] listenerId = ByteBufUtil.readArray(buf); short isCustom = buf.readUnsignedByte(); boolean isRetried = buf.readUnsignedByte() == 1; DataFormat dataFormat = listenerDataFormat.apply(listenerId); if (isCustom == 1) { final Object eventData = dataFormat.valueToObj(ByteBufUtil.readArray(buf), allowList); return createCustomEvent(listenerId, eventData, eventType, isRetried); } else if (isCustom == 2) { // New in 2.1, dealing with raw custom events return createCustomEvent(listenerId, ByteBufUtil.readArray(buf), eventType, isRetried); // Raw data } else { switch (eventType) { case CLIENT_CACHE_ENTRY_CREATED: Object createdKey = dataFormat.keyToObj(ByteBufUtil.readArray(buf), allowList); long createdDataVersion = buf.readLong(); return createCreatedEvent(listenerId, createdKey, createdDataVersion, isRetried); case CLIENT_CACHE_ENTRY_MODIFIED: Object modifiedKey = dataFormat.keyToObj(ByteBufUtil.readArray(buf), allowList); long modifiedDataVersion = buf.readLong(); return createModifiedEvent(listenerId, modifiedKey, modifiedDataVersion, isRetried); case CLIENT_CACHE_ENTRY_REMOVED: Object removedKey = dataFormat.keyToObj(ByteBufUtil.readArray(buf), allowList); return createRemovedEvent(listenerId, removedKey, isRetried); case CLIENT_CACHE_ENTRY_EXPIRED: Object expiredKey = dataFormat.keyToObj(ByteBufUtil.readArray(buf), allowList); return createExpiredEvent(listenerId, expiredKey); default: throw HOTROD.unknownEvent(eventTypeId); } } } protected AbstractClientEvent createExpiredEvent(byte[] listenerId, final Object key) { return new ExpiredEventImpl<>(listenerId, key); } @Override public <K, V> CacheEntry<K, V> returnPossiblePrevValue(K key, ByteBuf buf, short status, DataFormat dataFormat, int flags, ClassAllowList allowList, Marshaller marshaller) { if (HotRodConstants.hasPrevious(status)) { return AbstractKeyOperation.readEntry(buf, key, dataFormat, allowList); } else { return null; } } protected AbstractClientEvent createRemovedEvent(byte[] listenerId, final Object key, final boolean isRetried) { return new RemovedEventImpl<>(listenerId, key, isRetried); } protected AbstractClientEvent createModifiedEvent(byte[] listenerId, final Object key, final long dataVersion, final boolean isRetried) { return new ModifiedEventImpl<>(listenerId, key, dataVersion, isRetried); } protected AbstractClientEvent createCreatedEvent(byte[] listenerId, final Object key, final long dataVersion, final boolean isRetried) { return new CreatedEventImpl<>(listenerId, key, dataVersion, isRetried); } protected AbstractClientEvent createCustomEvent(byte[] listenerId, final Object eventData, final ClientEvent.Type eventType, final boolean isRetried) { return new CustomEventImpl<>(listenerId, eventData, isRetried, eventType); } protected void checkForErrorsInResponseStatus(ByteBuf buf, HeaderParams params, short status, SocketAddress serverAddress) { if (log.isTraceEnabled()) log.tracef("[%s] Received operation status: %#x", new String(params.cacheName), status); String msgFromServer; try { switch (status) { case HotRodConstants.INVALID_MAGIC_OR_MESSAGE_ID_STATUS: case HotRodConstants.REQUEST_PARSING_ERROR_STATUS: case HotRodConstants.UNKNOWN_COMMAND_STATUS: case HotRodConstants.SERVER_ERROR_STATUS: case HotRodConstants.COMMAND_TIMEOUT_STATUS: case HotRodConstants.UNKNOWN_VERSION_STATUS: { // If error, the body of the message just contains a message msgFromServer = ByteBufUtil.readString(buf); if (status == HotRodConstants.COMMAND_TIMEOUT_STATUS && log.isTraceEnabled()) { log.tracef("Server-side timeout performing operation: %s", msgFromServer); } else { HOTROD.errorFromServer(msgFromServer); } throw new HotRodClientException(msgFromServer, params.messageId, status); } case HotRodConstants.ILLEGAL_LIFECYCLE_STATE: msgFromServer = ByteBufUtil.readString(buf); throw new RemoteIllegalLifecycleStateException(msgFromServer, params.messageId, status, serverAddress); case HotRodConstants.NODE_SUSPECTED: // Handle both Infinispan's and JGroups' suspicions msgFromServer = ByteBufUtil.readString(buf); if (log.isTraceEnabled()) log.tracef("[%s] A remote node was suspected while executing messageId=%d. " + "Check if retry possible. Message from server: %s", new String(params.cacheName), params.messageId, msgFromServer); throw new RemoteNodeSuspectException(msgFromServer, params.messageId, status); default: { throw new IllegalStateException(String.format("Unknown status: %#04x", status)); } } } finally { // Errors related to protocol parsing are odd, and they can sometimes // be the consequence of previous errors, so whenever these errors // occur, invalidate the underlying transport instance so that a // brand new connection is established next time around. switch (status) { case HotRodConstants.INVALID_MAGIC_OR_MESSAGE_ID_STATUS: case HotRodConstants.REQUEST_PARSING_ERROR_STATUS: case HotRodConstants.UNKNOWN_COMMAND_STATUS: case HotRodConstants.UNKNOWN_VERSION_STATUS: { // invalidation happens due to exception in operation } } } } protected void readNewTopologyIfPresent(ByteBuf buf, HeaderParams params, ChannelFactory channelFactory) { short topologyChangeByte = buf.readUnsignedByte(); if (topologyChangeByte == 1) readNewTopologyAndHash(buf, params, channelFactory); } protected void readNewTopologyAndHash(ByteBuf buf, HeaderParams params, ChannelFactory channelFactory) { int newTopologyId = ByteBufUtil.readVInt(buf); InetSocketAddress[] addresses = readTopology(buf); final short hashFunctionVersion; final SocketAddress[][] segmentOwners; if (params.clientIntelligence == ClientIntelligence.HASH_DISTRIBUTION_AWARE.getValue()) { // Only read the hash if we asked for it hashFunctionVersion = buf.readUnsignedByte(); int numSegments = ByteBufUtil.readVInt(buf); segmentOwners = new SocketAddress[numSegments][]; if (hashFunctionVersion > 0) { for (int i = 0; i < numSegments; i++) { short numOwners = buf.readUnsignedByte(); segmentOwners[i] = new SocketAddress[numOwners]; for (int j = 0; j < numOwners; j++) { int memberIndex = ByteBufUtil.readVInt(buf); segmentOwners[i][j] = addresses[memberIndex]; } } } } else { hashFunctionVersion = -1; segmentOwners = null; } channelFactory.receiveTopology(params.cacheName, params.topologyAge, newTopologyId, addresses, segmentOwners, hashFunctionVersion); } private InetSocketAddress[] readTopology(ByteBuf buf) { int clusterSize = ByteBufUtil.readVInt(buf); InetSocketAddress[] addresses = new InetSocketAddress[clusterSize]; for (int i = 0; i < clusterSize; i++) { String host = ByteBufUtil.readString(buf); int port = buf.readUnsignedShort(); addresses[i] = InetSocketAddress.createUnresolved(host, port); } return addresses; } @Override public void writeIteratorStartOperation(ByteBuf buf, IntSet segments, String filterConverterFactory, int batchSize, boolean metadata, byte[][] filterParameters) { if (segments == null) { ByteBufUtil.writeSignedVInt(buf, -1); } else { // TODO use a more compact BitSet implementation, like http://roaringbitmap.org/ BitSet bitSet = new BitSet(); segments.forEach((IntConsumer) bitSet::set); ByteBufUtil.writeOptionalArray(buf, bitSet.toByteArray()); } ByteBufUtil.writeOptionalString(buf, filterConverterFactory); if (filterConverterFactory != null) { if (filterParameters != null && filterParameters.length > 0) { buf.writeByte(filterParameters.length); Arrays.stream(filterParameters).forEach(param -> ByteBufUtil.writeArray(buf, param)); } else { buf.writeByte(0); } } ByteBufUtil.writeVInt(buf, batchSize); buf.writeByte(metadata ? 1 : 0); } @Override public int readProjectionSize(ByteBuf buf) { return ByteBufUtil.readVInt(buf); } @Override public short readMeta(ByteBuf buf) { return buf.readUnsignedByte(); } @Override public boolean allowOperationsAndEvents() { return true; } @Override public MediaType readKeyType(ByteBuf buf) { return CodecUtils.readMediaType(buf); } @Override public MediaType readValueType(ByteBuf buf) { return CodecUtils.readMediaType(buf); } @Override public int estimateSizeMultimapSupportsDuplicated() { return 1; } @Override public void writeMultimapSupportDuplicates(ByteBuf buf, boolean supportsDuplicates) { buf.writeByte(supportsDuplicates ? 1 : 0); } }
23,571
41.092857
182
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/protocol/CodecUtils.java
package org.infinispan.hotrod.impl.protocol; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.hotrod.exceptions.HotRodClientException; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.MediaTypeIds; import io.netty.buffer.ByteBuf; import io.netty.util.CharsetUtil; /** * @since 14.0 */ public final class CodecUtils { private CodecUtils() { } static boolean isGreaterThan4bytes(long value) { int narrowed = (int) value; return narrowed == value; } public static int toSeconds(long duration, TimeUnit timeUnit) { int seconds = (int) timeUnit.toSeconds(duration); long inverseDuration = timeUnit.convert(seconds, TimeUnit.SECONDS); if (duration > inverseDuration) { //Round up. seconds++; } return seconds; } static MediaType readMediaType(ByteBuf byteBuf) { byte keyMediaTypeDefinition = byteBuf.readByte(); if (keyMediaTypeDefinition == 0) return null; if (keyMediaTypeDefinition == 1) return readPredefinedMediaType(byteBuf); if (keyMediaTypeDefinition == 2) return readCustomMediaType(byteBuf); throw new HotRodClientException("Unknown MediaType definition: " + keyMediaTypeDefinition); } static MediaType readPredefinedMediaType(ByteBuf buffer) { int mediaTypeId = ByteBufUtil.readVInt(buffer); MediaType mediaType = MediaTypeIds.getMediaType((short) mediaTypeId); return mediaType.withParameters(readMediaTypeParams(buffer)); } static MediaType readCustomMediaType(ByteBuf buffer) { byte[] customMediaTypeBytes = ByteBufUtil.readArray(buffer); String strCustomMediaType = new String(customMediaTypeBytes, CharsetUtil.UTF_8); MediaType customMediaType = MediaType.fromString(strCustomMediaType); return customMediaType.withParameters(readMediaTypeParams(buffer)); } static Map<String, String> readMediaTypeParams(ByteBuf buffer) { int paramsSize = ByteBufUtil.readVInt(buffer); if (paramsSize == 0) return Collections.emptyMap(); Map<String, String> params = new HashMap<>(paramsSize); for (int i = 0; i < paramsSize; i++) { byte[] bytesParamName = ByteBufUtil.readArray(buffer); String paramName = new String(bytesParamName, CharsetUtil.UTF_8); byte[] bytesParamValue = ByteBufUtil.readArray(buffer); String paramValue = new String(bytesParamValue, CharsetUtil.UTF_8); params.put(paramName, paramValue); } return params; } }
2,702
34.565789
97
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/protocol/Codec.java
package org.infinispan.hotrod.impl.protocol; import java.net.SocketAddress; import java.util.EnumSet; import java.util.function.Function; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryExpiration; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.events.cache.CacheEntryEventType; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.IntSet; import org.infinispan.hotrod.configuration.ProtocolVersion; import org.infinispan.hotrod.event.ClientListener; import org.infinispan.hotrod.event.impl.AbstractClientEvent; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.cache.RemoteCache; import org.infinispan.hotrod.impl.counter.HotRodCounterEvent; import org.infinispan.hotrod.impl.operations.CacheOperationsFactory; import org.infinispan.hotrod.impl.operations.PingResponse; import org.infinispan.hotrod.impl.transport.netty.ChannelFactory; import io.netty.buffer.ByteBuf; /** * A Hot Rod protocol encoder/decoder. * * @since 14.0 */ public interface Codec { static Codec forProtocol(ProtocolVersion version) { switch (version) { case PROTOCOL_VERSION_40: case PROTOCOL_VERSION_AUTO: return new Codec40(); default: throw new IllegalArgumentException(version.toString()); } } int estimateHeaderSize(HeaderParams headerParams); /** * Writes a request header with the given parameters to the transport and returns an updated header parameters. */ HeaderParams writeHeader(ByteBuf buf, HeaderParams params); /** * Writes client listener parameters */ void writeClientListenerParams(ByteBuf buf, ClientListener clientListener, byte[][] filterFactoryParams, byte[][] converterFactoryParams); /** * Write lifespan/maxidle parameters. */ void writeExpirationParams(ByteBuf buf, CacheEntryExpiration.Impl expiration); void writeBloomFilter(ByteBuf buf, int bloomFilterBits); int estimateExpirationSize(CacheEntryExpiration.Impl expiration); long readMessageId(ByteBuf buf); short readOpCode(ByteBuf buf); /** * Reads a response header from the transport and returns the status of the response. */ short readHeader(ByteBuf buf, double receivedOpCode, HeaderParams params, ChannelFactory channelFactory, SocketAddress serverAddress); AbstractClientEvent readCacheEvent(ByteBuf buf, Function<byte[], DataFormat> listenerDataFormat, short eventTypeId, ClassAllowList allowList, SocketAddress serverAddress); <K, V> CacheEntry<K, V> returnPossiblePrevValue(K key, ByteBuf buf, short status, DataFormat dataFormat, int flags, ClassAllowList allowList, Marshaller marshaller); void writeClientListenerInterests(ByteBuf buf, EnumSet<CacheEntryEventType> types); /** * Reads a {@link HotRodCounterEvent} with the {@code listener-id}. */ HotRodCounterEvent readCounterEvent(ByteBuf buf); /** * @return True if we can send operations after registering a listener on given channel */ default boolean allowOperationsAndEvents() { return false; } /** * Iteration read for projection size * * @param buf * @return */ default int readProjectionSize(ByteBuf buf) { return 0; } /** * Iteration read to tell if metadata is present for entry * * @param buf * @return */ default short readMeta(ByteBuf buf) { return 0; } default void writeIteratorStartOperation(ByteBuf buf, IntSet segments, String filterConverterFactory, int batchSize, boolean metadata, byte[][] filterParameters) { throw new UnsupportedOperationException("This version doesn't support iterating upon entries!"); } /** * Creates a key iterator with the given batch size if applicable. This iterator does not support removal. * * @param remoteCache * @param cacheOperationsFactory * @param segments * @param batchSize * @param <K> * @return */ default <K> CloseableIterator<K> keyIterator(RemoteCache<K, ?> remoteCache, CacheOperationsFactory cacheOperationsFactory, CacheOptions options, IntSet segments, int batchSize) { throw new UnsupportedOperationException("This version doesn't support iterating upon keys!"); } /** * Creates an entry iterator with the given batch size if applicable. This iterator does not support removal. * * @param remoteCache * @param segments * @param batchSize * @param <K> * @param <V> * @return */ default <K, V> CloseableIterator<CacheEntry<K, V>> entryIterator(RemoteCache<K, V> remoteCache, IntSet segments, int batchSize) { throw new UnsupportedOperationException("This version doesn't support iterating upon entries!"); } /** * Reads the {@link MediaType} of the key during initial ping of the cache. */ default MediaType readKeyType(ByteBuf buf) { return MediaType.APPLICATION_UNKNOWN; } /** * Reads the {@link MediaType} of the key during initial ping of the cache. */ default MediaType readValueType(ByteBuf buf) { return MediaType.APPLICATION_UNKNOWN; } /** * Read the response code for hints of object storage in the server. */ boolean isObjectStorageHinted(PingResponse pingResponse); /** * @return size that needs to be allocated in buffer for supportsDuplicates information. */ int estimateSizeMultimapSupportsDuplicated(); /** * * @param buf, buffer which supportsDuplicates info will be written to. * @param supportsDuplicates, to see whether multimap cache supports duplicates or not. */ void writeMultimapSupportDuplicates(ByteBuf buf, boolean supportsDuplicates); }
6,150
33.172222
174
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/protocol/HotRodConstants.java
package org.infinispan.hotrod.impl.protocol; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.function.Predicate; import java.util.stream.Stream; import org.infinispan.commons.util.ReflectionUtil; import org.infinispan.hotrod.impl.multimap.protocol.MultimapHotRodConstants; /** * Defines constants defined by Hot Rod specifications. * * @since 14.0 */ public interface HotRodConstants { short REQUEST_MAGIC = 0xA0; short RESPONSE_MAGIC = 0xA1; byte VERSION_40 = 40; //requests byte ILLEGAL_OP_CODE = 0x00; byte PUT_REQUEST = 0x01; byte GET_REQUEST = 0x03; byte PUT_IF_ABSENT_REQUEST = 0x05; byte REPLACE_REQUEST = 0x07; byte REPLACE_IF_UNMODIFIED_REQUEST = 0x09; byte REMOVE_REQUEST = 0x0B; byte REMOVE_IF_UNMODIFIED_REQUEST = 0x0D; byte CONTAINS_KEY_REQUEST = 0x0F; byte GET_WITH_VERSION = 0x11; byte CLEAR_REQUEST = 0x13; byte STATS_REQUEST = 0x15; byte PING_REQUEST = 0x17; byte BULK_GET_REQUEST = 0x19; byte GET_WITH_METADATA = 0x1B; byte BULK_GET_KEYS_REQUEST = 0x1D; byte QUERY_REQUEST = 0x1F; byte AUTH_MECH_LIST_REQUEST = 0x21; byte AUTH_REQUEST = 0x23; byte ADD_CLIENT_LISTENER_REQUEST = 0x25; byte REMOVE_CLIENT_LISTENER_REQUEST = 0x27; byte SIZE_REQUEST = 0x29; byte EXEC_REQUEST = 0x2B; byte PUT_ALL_REQUEST = 0x2D; byte GET_ALL_REQUEST = 0x2F; byte ITERATION_START_REQUEST = 0x31; byte ITERATION_NEXT_REQUEST = 0x33; byte ITERATION_END_REQUEST = 0x35; byte GET_STREAM_REQUEST = 0x37; byte PUT_STREAM_REQUEST = 0x39; byte PREPARE_REQUEST = 0x3B; byte COMMIT_REQUEST = 0x3D; byte ROLLBACK_REQUEST = 0x3F; byte ADD_BLOOM_FILTER_NEAR_CACHE_LISTENER_REQUEST = 0x41; byte UPDATE_BLOOM_FILTER_REQUEST = 0x43; byte COUNTER_CREATE_REQUEST = 0x4B; byte COUNTER_GET_CONFIGURATION_REQUEST = 0x4D; byte COUNTER_IS_DEFINED_REQUEST = 0x4F; byte COUNTER_ADD_AND_GET_REQUEST = 0x52; byte COUNTER_RESET_REQUEST = 0x54; byte COUNTER_GET_REQUEST = 0x56; byte COUNTER_CAS_REQUEST = 0x58; byte COUNTER_ADD_LISTENER_REQUEST = 0x5A; byte COUNTER_REMOVE_LISTENER_REQUEST = 0x5C; byte COUNTER_REMOVE_REQUEST = 0x5E; byte COUNTER_GET_NAMES_REQUEST = 0x64; byte FORGET_TX_REQUEST = 0x79; byte FETCH_TX_RECOVERY_REQUEST = 0x7B; byte PREPARE_TX_2_REQUEST = 0x7D; byte COUNTER_GET_AND_SET_REQUEST = 0x7F; //responses byte PUT_RESPONSE = 0x02; byte GET_RESPONSE = 0x04; byte PUT_IF_ABSENT_RESPONSE = 0x06; byte REPLACE_RESPONSE = 0x08; byte REPLACE_IF_UNMODIFIED_RESPONSE = 0x0A; byte REMOVE_RESPONSE = 0x0C; byte REMOVE_IF_UNMODIFIED_RESPONSE = 0x0E; byte CONTAINS_KEY_RESPONSE = 0x10; byte GET_WITH_VERSION_RESPONSE = 0x12; byte CLEAR_RESPONSE = 0x14; byte STATS_RESPONSE = 0x16; byte PING_RESPONSE = 0x18; byte BULK_GET_RESPONSE = 0x1A; byte GET_WITH_METADATA_RESPONSE = 0x1C; byte BULK_GET_KEYS_RESPONSE = 0x1E; byte QUERY_RESPONSE = 0x20; byte AUTH_MECH_LIST_RESPONSE = 0x22; byte AUTH_RESPONSE = 0x24; byte ADD_CLIENT_LISTENER_RESPONSE = 0x26; byte REMOVE_CLIENT_LISTENER_RESPONSE = 0x28; byte SIZE_RESPONSE = 0x2A; byte EXEC_RESPONSE = 0x2C; byte PUT_ALL_RESPONSE = 0x2E; byte GET_ALL_RESPONSE = 0x30; byte ITERATION_START_RESPONSE = 0x32; byte ITERATION_NEXT_RESPONSE = 0x34; byte ITERATION_END_RESPONSE = 0x36; byte GET_STREAM_RESPONSE = 0x38; byte PUT_STREAM_RESPONSE = 0x3A; byte PREPARE_RESPONSE = 0x3C; byte COMMIT_RESPONSE = 0x3E; byte ROLLBACK_RESPONSE = 0x40; byte ADD_BLOOM_FILTER_NEAR_CACHE_LISTENER_RESPONSE = 0x42; byte UPDATE_BLOOM_FILTER_RESPONSE = 0x44; byte FORGET_TX_RESPONSE = 0x7A; byte FETCH_TX_RECOVERY_RESPONSE = 0x7C; byte PREPARE_TX_2_RESPONSE = 0x7E; byte ERROR_RESPONSE = 0x50; byte CACHE_ENTRY_CREATED_EVENT_RESPONSE = 0x60; byte CACHE_ENTRY_MODIFIED_EVENT_RESPONSE = 0x61; byte CACHE_ENTRY_REMOVED_EVENT_RESPONSE = 0x62; byte CACHE_ENTRY_EXPIRED_EVENT_RESPONSE = 0x63; byte COUNTER_CREATE_RESPONSE = 0x4C; byte COUNTER_GET_CONFIGURATION_RESPONSE = 0x4E; byte COUNTER_IS_DEFINED_RESPONSE = 0x51; byte COUNTER_ADD_AND_GET_RESPONSE = 0x53; byte COUNTER_RESET_RESPONSE = 0x55; byte COUNTER_GET_RESPONSE = 0x57; byte COUNTER_CAS_RESPONSE = 0x59; byte COUNTER_ADD_LISTENER_RESPONSE = 0x5B; byte COUNTER_REMOVE_LISTENER_RESPONSE = 0x5D; byte COUNTER_REMOVE_RESPONSE = 0x5F; byte COUNTER_GET_NAMES_RESPONSE = 0x65; byte COUNTER_EVENT_RESPONSE = 0x66; short COUNTER_GET_AND_SET_RESPONSE = 0x80; //response status byte NO_ERROR_STATUS = 0x00; byte NOT_PUT_REMOVED_REPLACED_STATUS = 0x01; int KEY_DOES_NOT_EXIST_STATUS = 0x02; int SUCCESS_WITH_PREVIOUS = 0x03; int NOT_EXECUTED_WITH_PREVIOUS = 0x04; int INVALID_ITERATION = 0x05; byte NO_ERROR_STATUS_OBJ_STORAGE = 0x06; byte SUCCESS_WITH_PREVIOUS_OBJ_STORAGE = 0x07; byte NOT_EXECUTED_WITH_PREVIOUS_OBJ_STORAGE = 0x08; int INVALID_MAGIC_OR_MESSAGE_ID_STATUS = 0x81; int REQUEST_PARSING_ERROR_STATUS = 0x84; int UNKNOWN_COMMAND_STATUS = 0x82; int UNKNOWN_VERSION_STATUS = 0x83; int SERVER_ERROR_STATUS = 0x85; int COMMAND_TIMEOUT_STATUS = 0x86; int NODE_SUSPECTED = 0x87; int ILLEGAL_LIFECYCLE_STATE = 0x88; Charset HOTROD_STRING_CHARSET = StandardCharsets.UTF_8; byte[] DEFAULT_CACHE_NAME_BYTES = new byte[]{}; byte INFINITE_LIFESPAN = 0x01; byte INFINITE_MAXIDLE = 0x02; int DEFAULT_CACHE_TOPOLOGY = -1; int SWITCH_CLUSTER_TOPOLOGY = -2; static boolean isSuccess(int status) { return status == NO_ERROR_STATUS || status == NO_ERROR_STATUS_OBJ_STORAGE || status == SUCCESS_WITH_PREVIOUS || status == SUCCESS_WITH_PREVIOUS_OBJ_STORAGE; } static boolean isNotExecuted(int status) { return status == NOT_PUT_REMOVED_REPLACED_STATUS || status == NOT_EXECUTED_WITH_PREVIOUS || status == NOT_EXECUTED_WITH_PREVIOUS_OBJ_STORAGE; } static boolean isNotExist(int status) { return status == KEY_DOES_NOT_EXIST_STATUS; } static boolean hasPrevious(int status) { return status == SUCCESS_WITH_PREVIOUS || status == SUCCESS_WITH_PREVIOUS_OBJ_STORAGE || status == NOT_EXECUTED_WITH_PREVIOUS || status == NOT_EXECUTED_WITH_PREVIOUS_OBJ_STORAGE; } static boolean isObjectStorage(short status) { return status == NO_ERROR_STATUS_OBJ_STORAGE || status == SUCCESS_WITH_PREVIOUS_OBJ_STORAGE || status == NOT_EXECUTED_WITH_PREVIOUS_OBJ_STORAGE; } static boolean isInvalidIteration(short status) { return status == INVALID_ITERATION; } final class Names { static final String[] NAMES; private Names() { } static { Predicate<Field> filterRequestsResponses = f -> f.getName().endsWith("_REQUEST") || f.getName().endsWith("_RESPONSE"); int maxId = Stream.concat(Stream.of(HotRodConstants.class.getFields()), Stream.of(MultimapHotRodConstants.class.getFields())) .filter(filterRequestsResponses) .mapToInt(f -> ReflectionUtil.getIntAccessibly(f, null)) .max().orElse(0); NAMES = new String[maxId + 1]; Stream.concat(Stream.of(HotRodConstants.class.getFields()), Stream.of(MultimapHotRodConstants.class.getFields())) .filter(filterRequestsResponses) .forEach(f -> { int id = ReflectionUtil.getIntAccessibly(f, null); assert NAMES[id] == null; NAMES[id] = f.getName(); }); for (int i = 0; i < NAMES.length; ++i) { if (NAMES[i] == null) NAMES[i] = "UNKNOWN"; } } public static String of(short opCode) { return NAMES[opCode]; } } }
7,997
33.179487
90
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/protocol/HeaderParams.java
package org.infinispan.hotrod.impl.protocol; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.hotrod.impl.ClientTopology; import org.infinispan.hotrod.impl.DataFormat; /** * Hot Rod request header parameters * * @since 14.0 */ public class HeaderParams { final short opCode; final short opRespCode; byte[] cacheName; final int flags; final byte txMarker; final AtomicReference<ClientTopology> clientTopology; final long messageId; int topologyAge; final DataFormat dataFormat; Map<String, byte[]> otherParams; // sent client intelligence: to read the response volatile byte clientIntelligence; public HeaderParams(short requestCode, short responseCode, int flags, byte txMarker, long messageId, DataFormat dataFormat, AtomicReference<ClientTopology> clientTopology) { opCode = requestCode; opRespCode = responseCode; this.flags = flags; this.txMarker = txMarker; this.messageId = messageId; this.dataFormat = dataFormat; this.clientTopology = clientTopology; } public HeaderParams cacheName(byte[] cacheName) { this.cacheName = cacheName; return this; } public long messageId() { return messageId; } public HeaderParams topologyAge(int topologyAge) { this.topologyAge = topologyAge; return this; } public int getTopologyAge() { return topologyAge; } public DataFormat dataFormat() { return dataFormat; } public byte[] cacheName() { return cacheName; } public void otherParam(String paramKey, byte[] paramValue) { if (otherParams == null) { otherParams = new HashMap<>(2); } otherParams.put(paramKey, paramValue); } public Map<String, byte[]> otherParams() { return otherParams; } public int flags() { return flags; } public AtomicReference<ClientTopology> getClientTopology() { return clientTopology; } public byte clientIntelligence() { return clientIntelligence; } public short responseCode() { return opRespCode; } }
2,174
22.641304
176
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/protocol/ChannelOutputStream.java
package org.infinispan.hotrod.impl.protocol; import java.io.IOException; import java.io.OutputStream; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelPromise; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.ImmediateEventExecutor; public class ChannelOutputStream extends OutputStream implements GenericFutureListener<Future<? super Void>> { private static final int BUFFER_SIZE = 8 * 1024; private final Channel channel; private final ChannelOutputStreamListener listener; private ByteBuf buf; public ChannelOutputStream(Channel channel, ChannelOutputStreamListener listener) { this.channel = channel; this.listener = listener; } private void alloc() { buf = channel.alloc().buffer(BUFFER_SIZE); } private ChannelPromise writePromise() { // When the write fails due to event loop closed we would not be notified // if we used the the same event loop as executor for the promise ChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE); promise.addListener(this); return promise; } @Override public void write(int b) { if (buf == null) { alloc(); } else if (!buf.isWritable()) { channel.write(vIntBuffer(buf.writerIndex()), writePromise()); channel.write(buf, writePromise()); alloc(); } buf.writeByte(b); } private ByteBuf vIntBuffer(int value) { ByteBuf buffer = channel.alloc().buffer(ByteBufUtil.estimateVIntSize(value)); ByteBufUtil.writeVInt(buffer, value); return buffer; } @Override public void write(byte[] b, int off, int len) { if (buf == null) { if (len > BUFFER_SIZE) { channel.write(vIntBuffer(len), writePromise()); channel.write(Unpooled.wrappedBuffer(b, off, len), writePromise()); } else { alloc(); buf.writeBytes(b, off, len); } return; } if (len > buf.capacity()) { channel.write(vIntBuffer(buf.writerIndex()), writePromise()); channel.write(buf, writePromise()); buf = null; channel.write(vIntBuffer(len), writePromise()); channel.write(Unpooled.wrappedBuffer(b, off, len), writePromise()); return; } else if (len > buf.writableBytes()) { int numWritten = buf.writableBytes(); buf.writeBytes(b, off, numWritten); off += numWritten; len -= numWritten; channel.write(vIntBuffer(buf.writerIndex()), writePromise()); channel.write(buf, writePromise()); alloc(); } buf.writeBytes(b, off, len); } @Override public void flush() { if (buf != null && buf.writerIndex() > 0) { channel.write(vIntBuffer(buf.writerIndex()), writePromise()); channel.writeAndFlush(buf, writePromise()); buf = null; } else { channel.flush(); } } @Override public void close() throws IOException { flush(); ByteBuf terminal = channel.alloc().buffer(1); terminal.writeByte(0); channel.writeAndFlush(terminal, writePromise()); listener.onClose(channel); } @Override public void operationComplete(Future<? super Void> future) { if (!future.isSuccess()) { listener.onError(channel, future.cause()); } } }
3,658
30.543103
110
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/consistenthash/CRC16ConsistentHashV2.java
package org.infinispan.hotrod.impl.consistenthash; import java.util.Random; import org.infinispan.commons.hash.CRC16; public class CRC16ConsistentHashV2 extends ConsistentHashV2 { public CRC16ConsistentHashV2(Random rnd) { super(rnd, CRC16.getInstance()); } }
276
20.307692
61
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/consistenthash/ConsistentHash.java
package org.infinispan.hotrod.impl.consistenthash; import java.net.SocketAddress; import java.util.Map; import java.util.Set; /** * Abstraction for the used consistent hash. * * @since 14.0 */ public interface ConsistentHash { Class<? extends ConsistentHash>[] DEFAULT = new Class[] { null, ConsistentHashV2.class, SegmentConsistentHash.class, CRC16ConsistentHashV2.class }; @Deprecated void init(Map<SocketAddress, Set<Integer>> servers2Hash, int numKeyOwners, int hashSpace); SocketAddress getServer(Object key); /** * Computes hash code of a given object, and then normalizes it to ensure a positive * value is always returned. * @param object to hash * @return a non-null, non-negative normalized hash code for a given object */ int getNormalizedHash(Object object); Map<SocketAddress, Set<Integer>> getSegmentsByServer(); default Map<SocketAddress, Set<Integer>> getPrimarySegmentsByServer() { return null; } }
1,019
25.153846
93
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/consistenthash/ConsistentHashV2.java
package org.infinispan.hotrod.impl.consistenthash; import java.net.SocketAddress; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import org.infinispan.commons.hash.Hash; import org.infinispan.commons.hash.MurmurHash3; import org.infinispan.commons.util.Util; import org.infinispan.hotrod.impl.logging.LogFactory; import org.jboss.logging.BasicLogger; /** * Version 2 of the ConsistentHash function. Uses MurmurHash3. * * @see org.infinispan.commons.hash.MurmurHash3 * @since 14.0 */ public class ConsistentHashV2 implements ConsistentHash { private static final BasicLogger log = LogFactory.getLog(ConsistentHashV2.class); private final SortedMap<Integer, SocketAddress> positions = new TreeMap<Integer, SocketAddress>(); private volatile int[] hashes; private volatile SocketAddress[] addresses; private int hashSpace; private boolean hashSpaceIsMaxInt; protected final Hash hash; private int numKeyOwners; private final Random rnd; public ConsistentHashV2(Random rnd) { this(rnd, MurmurHash3.getInstance()); } public ConsistentHashV2(Random rnd, Hash hash) { this.rnd = rnd; this.hash = hash; } @Override public void init(Map<SocketAddress, Set<Integer>> servers2Hash, int numKeyOwners, int hashSpace) { for (Map.Entry<SocketAddress, Set<Integer>> entry : servers2Hash.entrySet()) { SocketAddress addr = entry.getKey(); for (Integer hash : entry.getValue()) { SocketAddress prev = positions.put(hash, addr); if (prev != null) log.debugf("Adding hash (%d) again, this time for %s. Previously it was associated with: %s", hash, addr, prev); } } int hashWheelSize = positions.size(); log.tracef("Positions (%d entries) are: %s", hashWheelSize, positions); hashes = new int[hashWheelSize]; Iterator<Integer> it = positions.keySet().iterator(); for (int i = 0; i < hashWheelSize; i++) { hashes[i] = it.next(); } addresses = positions.values().toArray(new SocketAddress[hashWheelSize]); this.hashSpace = hashSpace; // This is true if we're talking to an instance of Infinispan 5.2 or newer. this.hashSpaceIsMaxInt = hashSpace == Integer.MAX_VALUE; this.numKeyOwners = numKeyOwners; } @Override public SocketAddress getServer(Object key) { int normalisedHashForKey; if (hashSpaceIsMaxInt) { normalisedHashForKey = getNormalizedHash(key); if (normalisedHashForKey == Integer.MAX_VALUE) normalisedHashForKey = 0; } else { normalisedHashForKey = getNormalizedHash(key) % hashSpace; } int mainOwner = getHashIndex(normalisedHashForKey); int indexToReturn = mainOwner % hashes.length; return addresses[indexToReturn]; } private int getHashIndex(int normalisedHashForKey) { int result = Arrays.binarySearch(hashes, normalisedHashForKey); if (result >= 0) {//the normalisedHashForKey has an exact match in the hashes array return result; } else { //see javadoc for Arrays.binarySearch, @return tag in particular if (result == (-hashes.length - 1)) { return 0; } else { return -result - 1; } } } private int getIndex() { return rnd.nextInt(Math.min(numKeyOwners, positions.size())); } @Override public final int getNormalizedHash(Object object) { return Util.getNormalizedHash(object, hash); } @Override public Map<SocketAddress, Set<Integer>> getSegmentsByServer() { throw new UnsupportedOperationException(); } @Override public Map<SocketAddress, Set<Integer>> getPrimarySegmentsByServer() { throw new UnsupportedOperationException(); } }
3,944
28.886364
127
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/consistenthash/ConsistentHashFactory.java
package org.infinispan.hotrod.impl.consistenthash; import org.infinispan.hotrod.configuration.HotRodConfiguration; import org.infinispan.commons.util.Util; /** * Factory for {@link org.infinispan.hotrod.impl.consistenthash.ConsistentHash} function. It will try to look * into the configuration for consistent hash definitions as follows: * consistent-hash.[version]=[fully qualified class implementing ConsistentHash] * e.g. * <code>infinispan.client.hotrod.hash_function_impl.3=org.infinispan.hotrod.impl.consistenthash.SegmentConsistentHash</code> * or if using the {@link HotRodConfiguration} API, * <code>configuration.consistentHashImpl(3, org.infinispan.hotrod.impl.consistenthash.SegmentConsistentHash.class);</code> * <p/> * * <p>The defaults are:</p> * <ol> * <li>N/A (No longer used.)</li> * <li>org.infinispan.hotrod.impl.ConsistentHashV2</li> * <li>org.infinispan.hotrod.impl.SegmentConsistentHash</li> * </ol> * * @since 14.0 */ public class ConsistentHashFactory { private HotRodConfiguration configuration; public void init(HotRodConfiguration configuration) { this.configuration = configuration; } public <T extends ConsistentHash> T newConsistentHash(int version) { Class<? extends ConsistentHash> hashFunctionClass = configuration.consistentHashImpl(version); // TODO: Why create a brand new instance via reflection everytime a new hash topology is received? Caching??? return (T) Util.getInstance(hashFunctionClass); } }
1,511
37.769231
125
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/consistenthash/SegmentConsistentHash.java
package org.infinispan.hotrod.impl.consistenthash; import java.net.SocketAddress; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.commons.hash.Hash; import org.infinispan.commons.hash.MurmurHash3; import org.infinispan.commons.util.Immutables; import org.infinispan.commons.util.Util; /** */ public final class SegmentConsistentHash implements ConsistentHash { private static final Log log = LogFactory.getLog(SegmentConsistentHash.class); private final Hash hash = MurmurHash3.getInstance(); private SocketAddress[][] segmentOwners; private int numSegments; private int segmentSize; @Override public void init(Map<SocketAddress, Set<Integer>> servers2Hash, int numKeyOwners, int hashSpace) { // No-op, parameters are not relevant for this implementation } public void init(SocketAddress[][] segmentOwners, int numSegments) { this.segmentOwners = segmentOwners; this.numSegments = numSegments; this.segmentSize = Util.getSegmentSize(numSegments); } @Override public SocketAddress getServer(Object key) { int segmentId = getSegment(key); SocketAddress server = segmentOwners[segmentId][0]; if (log.isTraceEnabled()) log.tracef("Found server %s for segment %s of key %s", server, segmentId, Util.toStr(key)); return server; } public int getSegment(Object key) { // The result must always be positive, so we make sure the dividend is positive first return getNormalizedHash(key) / segmentSize; } @Override public int getNormalizedHash(Object object) { return Util.getNormalizedHash(object, hash); } @Override public Map<SocketAddress, Set<Integer>> getSegmentsByServer() { Map<SocketAddress, Set<Integer>> map = new HashMap<>(); for (int segment = 0; segment < segmentOwners.length; segment++) { SocketAddress[] owners = segmentOwners[segment]; for (SocketAddress s : owners) { map.computeIfAbsent(s, k -> new HashSet<>()).add(segment); } } return Immutables.immutableMapWrap(map); } @Override public Map<SocketAddress, Set<Integer>> getPrimarySegmentsByServer() { Map<SocketAddress, Set<Integer>> map = new HashMap<>(); for (int segment = 0; segment < segmentOwners.length; segment++) { SocketAddress[] owners = segmentOwners[segment]; map.computeIfAbsent(owners[0], k -> new HashSet<>()).add(segment); } return Immutables.immutableMapWrap(map); } public int getNumSegments() { return numSegments; } public SocketAddress[][] getSegmentOwners() { return segmentOwners; } }
2,833
31.204545
101
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/RetryAwareCompletionStage.java
package org.infinispan.hotrod.impl.operations; import java.util.concurrent.CompletionStage; public interface RetryAwareCompletionStage<E> extends CompletionStage<E> { /** * Returns whether this operation had to be retried on another server than the first one picked. * * @return {@code true} if the operation had to be retried on another server, {@code false} if it completed without * retry or {@code null} if the operation is not yet complete. */ Boolean wasRetried(); }
501
34.857143
118
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/AddClientListenerOperation.java
package org.infinispan.hotrod.impl.operations; import java.util.EnumSet; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.events.cache.CacheEntryEventType; import org.infinispan.hotrod.event.ClientListener; import org.infinispan.hotrod.event.impl.ClientEventDispatcher; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.cache.RemoteCache; import org.infinispan.hotrod.impl.protocol.Codec; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HotRodClientDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; public class AddClientListenerOperation extends ClientListenerOperation { private final byte[][] filterFactoryParams; private final byte[][] converterFactoryParams; private final RemoteCache<?, ?> remoteCache; protected AddClientListenerOperation(OperationContext operationContext, CacheOptions options, Object listener, byte[][] filterFactoryParams, byte[][] converterFactoryParams, DataFormat dataFormat, RemoteCache<?, ?> remoteCache) { this(operationContext, options, generateListenerId(), listener, filterFactoryParams, converterFactoryParams, dataFormat, remoteCache); } private AddClientListenerOperation(OperationContext operationContext, CacheOptions options, byte[] listenerId, Object listener, byte[][] filterFactoryParams, byte[][] converterFactoryParams, DataFormat dataFormat, RemoteCache<?, ?> remoteCache) { super(operationContext, ADD_CLIENT_LISTENER_REQUEST, ADD_CLIENT_LISTENER_RESPONSE, options, listenerId, dataFormat, listener); this.filterFactoryParams = filterFactoryParams; this.converterFactoryParams = converterFactoryParams; this.remoteCache = remoteCache; } public AddClientListenerOperation copy() { return new AddClientListenerOperation(operationContext, options, listenerId, listener, filterFactoryParams, converterFactoryParams, dataFormat(), remoteCache); } @Override protected void actualExecute(Channel channel) { ClientListener clientListener = null; // FIXME channel.pipeline().get(HotRodClientDecoder.class).registerOperation(channel, this); operationContext.getListenerNotifier().addDispatcher(ClientEventDispatcher.create(this, address, () -> cleanup(channel), remoteCache)); ByteBuf buf = channel.alloc().buffer(); Codec codec = operationContext.getCodec(); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, listenerId); codec.writeClientListenerParams(buf, clientListener, filterFactoryParams, converterFactoryParams); codec.writeClientListenerInterests(buf, EnumSet.noneOf(CacheEntryEventType.class)); //FIXME channel.writeAndFlush(buf); } }
3,007
46.746032
140
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/GetStreamOperation.java
package org.infinispan.hotrod.impl.operations; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.cache.VersionedMetadataImpl; import org.infinispan.hotrod.impl.protocol.ChannelInputStream; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Streaming Get operation * * @since 14.0 */ public class GetStreamOperation<K> extends AbstractKeyOperation<K, ChannelInputStream> { private final int offset; private Channel channel; public GetStreamOperation(OperationContext operationContext, K key, byte[] keyBytes, int offset, CacheOptions options) { super(operationContext, GET_STREAM_REQUEST, GET_STREAM_RESPONSE, key, keyBytes, options, null); this.offset = offset; } @Override public void executeOperation(Channel channel) { this.channel = channel; scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(operationContext.getCodec().estimateHeaderSize(header) + ByteBufUtil.estimateArraySize(keyBytes) + ByteBufUtil.estimateVIntSize(offset)); operationContext.getCodec().writeHeader(buf, header); ByteBufUtil.writeArray(buf, keyBytes); ByteBufUtil.writeVInt(buf, offset); channel.writeAndFlush(buf); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status) || !HotRodConstants.isSuccess(status)) { statsDataRead(false); complete(null); } else { short flags = buf.readUnsignedByte(); long creation = -1; int lifespan = -1; long lastUsed = -1; int maxIdle = -1; if ((flags & INFINITE_LIFESPAN) != INFINITE_LIFESPAN) { creation = buf.readLong(); lifespan = ByteBufUtil.readVInt(buf); } if ((flags & INFINITE_MAXIDLE) != INFINITE_MAXIDLE) { lastUsed = buf.readLong(); maxIdle = ByteBufUtil.readVInt(buf); } long version = buf.readLong(); int totalLength = ByteBufUtil.readVInt(buf); VersionedMetadataImpl versionedMetadata = new VersionedMetadataImpl(creation, lifespan, lastUsed, maxIdle, version); ChannelInputStream stream = new ChannelInputStream(versionedMetadata, () -> { // ChannelInputStreams removes itself when it finishes reading all data if (channel.pipeline().get(ChannelInputStream.class) != null) { channel.pipeline().remove(ChannelInputStream.class); } }, totalLength); if (stream.moveReadable(buf)) { channel.pipeline().addBefore(HeaderDecoder.NAME, ChannelInputStream.NAME, stream); } statsDataRead(true); complete(stream); } } }
2,975
37.153846
139
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/ReplaceIfUnmodifiedOperation.java
package org.infinispan.hotrod.impl.operations; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryExpiration; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.VersionedOperationResponse; import org.infinispan.hotrod.impl.protocol.Codec; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Implement "replaceIfUnmodified" as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @since 14.0 */ public class ReplaceIfUnmodifiedOperation<K, V> extends AbstractKeyValueOperation<K, VersionedOperationResponse<CacheEntry<K, V>>> { private final long version; public ReplaceIfUnmodifiedOperation(OperationContext operationContext, K key, byte[] keyBytes, byte[] value, long version, CacheWriteOptions options, DataFormat dataFormat) { super(operationContext, REPLACE_IF_UNMODIFIED_REQUEST, REPLACE_IF_UNMODIFIED_RESPONSE, key, keyBytes, value, options, dataFormat); this.version = version; } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); Codec codec = operationContext.getCodec(); CacheEntryExpiration.Impl expiration = (CacheEntryExpiration.Impl) ((CacheWriteOptions) options).expiration(); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + ByteBufUtil.estimateArraySize(keyBytes) + codec.estimateExpirationSize(expiration) + 8 + ByteBufUtil.estimateArraySize(value)); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, keyBytes); codec.writeExpirationParams(buf, expiration); buf.writeLong(version); ByteBufUtil.writeArray(buf, value); channel.writeAndFlush(buf); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isSuccess(status)) { statsDataStore(); } complete(returnVersionedOperationResponse(buf, status)); } }
2,306
39.473684
136
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/IterationNextResponse.java
package org.infinispan.hotrod.impl.operations; import java.util.List; import org.infinispan.api.common.CacheEntry; import org.infinispan.commons.util.IntSet; /** * @since 14.0 */ public class IterationNextResponse<K, E> { private final short status; private final List<CacheEntry<K, E>> entries; private final IntSet completedSegments; private final boolean hasMore; public IterationNextResponse(short status, List<CacheEntry<K, E>> entries, IntSet completedSegments, boolean hasMore) { this.status = status; this.entries = entries; this.completedSegments = completedSegments; this.hasMore = hasMore; } public boolean hasMore() { return hasMore; } public List<CacheEntry<K, E>> getEntries() { return entries; } public short getStatus() { return status; } public IntSet getCompletedSegments() { return completedSegments; } }
925
21.585366
122
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/IterationStartResponse.java
package org.infinispan.hotrod.impl.operations; import org.infinispan.hotrod.impl.consistenthash.SegmentConsistentHash; import io.netty.channel.Channel; /** * @since 14.0 */ public class IterationStartResponse { private final byte[] iterationId; private final SegmentConsistentHash segmentConsistentHash; private final int topologyId; private final Channel channel; IterationStartResponse(byte[] iterationId, SegmentConsistentHash segmentConsistentHash, int topologyId, Channel channel) { this.iterationId = iterationId; this.segmentConsistentHash = segmentConsistentHash; this.topologyId = topologyId; this.channel = channel; } public byte[] getIterationId() { return iterationId; } public SegmentConsistentHash getSegmentConsistentHash() { return segmentConsistentHash; } public Channel getChannel() { return channel; } public int getTopologyId() { return topologyId; } }
973
23.974359
125
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/RemoveIfUnmodifiedOperation.java
package org.infinispan.hotrod.impl.operations; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.VersionedOperationResponse; import org.infinispan.hotrod.impl.protocol.Codec; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Implements "removeIfUnmodified" operation as defined by * <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol specification</a>. * * @since 14.0 */ public class RemoveIfUnmodifiedOperation<K, V> extends AbstractKeyOperation<K, VersionedOperationResponse<CacheEntry<K, V>>> { private final long version; public RemoveIfUnmodifiedOperation(OperationContext operationContext, K key, byte[] keyBytes, long version, CacheOptions options, DataFormat dataFormat) { super(operationContext, REMOVE_IF_UNMODIFIED_REQUEST, REMOVE_IF_UNMODIFIED_RESPONSE, key, keyBytes, options, dataFormat.withoutValueType()); this.version = version; } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); Codec codec = operationContext.getCodec(); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + ByteBufUtil.estimateArraySize(keyBytes) + 8); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, keyBytes); buf.writeLong(version); channel.writeAndFlush(buf); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(returnVersionedOperationResponse(buf, status)); } }
1,771
37.521739
146
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/AbstractKeyValueOperation.java
package org.infinispan.hotrod.impl.operations; import static org.infinispan.commons.util.Util.printArray; import org.infinispan.api.common.CacheEntryExpiration; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.protocol.Codec; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Base class for all operations that manipulate a key and a value. * * @since 14.0 */ public abstract class AbstractKeyValueOperation<K, T> extends AbstractKeyOperation<K, T> { protected final byte[] value; protected AbstractKeyValueOperation(OperationContext operationContext, short requestCode, short responseCode, K key, byte[] keyBytes, byte[] value, CacheOptions options, DataFormat dataFormat) { super(operationContext, requestCode, responseCode, key, keyBytes, options, dataFormat); this.value = value; } protected void sendKeyValueOperation(Channel channel) { Codec codec = operationContext.getCodec(); CacheEntryExpiration.Impl expiration = (CacheEntryExpiration.Impl) ((CacheWriteOptions) options).expiration(); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + keyBytes.length + codec.estimateExpirationSize(expiration) + value.length); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, keyBytes); codec.writeExpirationParams(buf, expiration); ByteBufUtil.writeArray(buf, value); channel.writeAndFlush(buf); } @Override protected void addParams(StringBuilder sb) { super.addParams(sb); sb.append(", value=").append(printArray(value)); } }
1,907
37.16
136
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/IterationStartOperation.java
package org.infinispan.hotrod.impl.operations; import java.net.SocketAddress; import java.util.Set; import org.infinispan.api.common.CacheOptions; import org.infinispan.commons.util.IntSet; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.consistenthash.SegmentConsistentHash; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * @since 14.0 */ public class IterationStartOperation extends RetryOnFailureOperation<IterationStartResponse> { private final String filterConverterFactory; private final byte[][] filterParameters; private final IntSet segments; private final int batchSize; private final boolean metadata; private final SocketAddress addressTarget; private Channel channel; IterationStartOperation(OperationContext operationContext, CacheOptions options, String filterConverterFactory, byte[][] filterParameters, IntSet segments, int batchSize, boolean metadata, DataFormat dataFormat, SocketAddress addressTarget) { super(operationContext, ITERATION_START_REQUEST, ITERATION_START_RESPONSE, options, dataFormat); this.filterConverterFactory = filterConverterFactory; this.filterParameters = filterParameters; this.segments = segments; this.batchSize = batchSize; this.metadata = metadata; this.addressTarget = addressTarget; } @Override protected void executeOperation(Channel channel) { this.channel = channel; scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(); operationContext.getCodec().writeHeader(buf, header); operationContext.getCodec().writeIteratorStartOperation(buf, segments, filterConverterFactory, batchSize, metadata, filterParameters); channel.writeAndFlush(buf); } @Override protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { if (addressTarget != null) { operationContext.getChannelFactory().fetchChannelAndInvoke(addressTarget, this); } else { super.fetchChannelAndInvoke(retryCount, failedServers); } } public void releaseChannel(Channel channel) { } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { SegmentConsistentHash consistentHash = (SegmentConsistentHash) operationContext.getChannelFactory().getConsistentHash(operationContext.getCacheNameBytes()); IterationStartResponse response = new IterationStartResponse(ByteBufUtil.readArray(buf), consistentHash, header.getClientTopology().get().getTopologyId(), channel); complete(response); } }
2,832
37.808219
170
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/PutAllOperation.java
package org.infinispan.hotrod.impl.operations; import java.net.SocketAddress; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.infinispan.api.common.CacheEntryExpiration; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.exceptions.InvalidResponseException; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.protocol.Codec; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Implements "putAll" as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol * specification</a>. * * @since 14.0 */ public class PutAllOperation extends StatsAffectingRetryingOperation<Void> { protected final Map<byte[], byte[]> map; public PutAllOperation(OperationContext operationContext, Map<byte[], byte[]> map, CacheWriteOptions options, DataFormat dataFormat) { super(operationContext, PUT_ALL_REQUEST, PUT_ALL_RESPONSE, options, dataFormat); this.map = map; } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); Codec codec = operationContext.getCodec(); CacheEntryExpiration.Impl expiration = (CacheEntryExpiration.Impl) ((CacheWriteOptions) options).expiration(); int bufSize = codec.estimateHeaderSize(header) + ByteBufUtil.estimateVIntSize(map.size()) + codec.estimateExpirationSize(expiration); for (Entry<byte[], byte[]> entry : map.entrySet()) { bufSize += ByteBufUtil.estimateArraySize(entry.getKey()); bufSize += ByteBufUtil.estimateArraySize(entry.getValue()); } ByteBuf buf = channel.alloc().buffer(bufSize); codec.writeHeader(buf, header); codec.writeExpirationParams(buf, expiration); ByteBufUtil.writeVInt(buf, map.size()); for (Entry<byte[], byte[]> entry : map.entrySet()) { ByteBufUtil.writeArray(buf, entry.getKey()); ByteBufUtil.writeArray(buf, entry.getValue()); } channel.writeAndFlush(buf); } @Override protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { operationContext.getChannelFactory().fetchChannelAndInvoke(map.keySet().iterator().next(), failedServers, operationContext.getCacheNameBytes(), this); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isSuccess(status)) { statsDataStore(map.size()); complete(null); return; } throw new InvalidResponseException("Unexpected response status: " + Integer.toHexString(status)); } }
2,896
37.626667
156
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/AbstractRemoveOperation.java
package org.infinispan.hotrod.impl.operations; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Implement "remove" operation as described in <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @since 14.0 */ public abstract class AbstractRemoveOperation<K, T> extends AbstractKeyOperation<K, T> { public AbstractRemoveOperation(OperationContext operationContext, K key, byte[] keyBytes, CacheOptions options, DataFormat dataFormat) { super(operationContext, REMOVE_REQUEST, REMOVE_RESPONSE, key, keyBytes, options, dataFormat); } @Override public void executeOperation(Channel channel) { scheduleRead(channel); sendArrayOperation(channel, keyBytes); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { completeNotExist(); } else { completeExisted(buf, status); } } abstract void completeNotExist(); abstract void completeExisted(ByteBuf buf, short status); }
1,342
29.522727
112
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/PrivateHotRodFlag.java
package org.infinispan.hotrod.impl.operations; public enum PrivateHotRodFlag { FORCE_RETURN_VALUE(0x0001); private final int flagInt; PrivateHotRodFlag(int flagInt) { this.flagInt = flagInt; } public int getFlagInt() { return flagInt; } }
273
16.125
46
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/IterationEndResponse.java
package org.infinispan.hotrod.impl.operations; /** * @since 14.0 */ public class IterationEndResponse { private final short status; public IterationEndResponse(short status) { this.status = status; } public short getStatus() { return status; } }
279
14.555556
46
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/SetIfAbsentOperation.java
package org.infinispan.hotrod.impl.operations; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.jboss.logging.BasicLogger; import io.netty.buffer.ByteBuf; /** * Implements "putIfAbsent" operation as described in <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @since 14.0 */ public class SetIfAbsentOperation<K> extends AbstractPutIfAbsentOperation<K, Boolean> { private static final BasicLogger log = LogFactory.getLog(SetIfAbsentOperation.class); public SetIfAbsentOperation(OperationContext operationContext, K key, byte[] keyBytes, byte[] value, CacheWriteOptions options, DataFormat dataFormat) { super(operationContext, key, keyBytes, value, options, dataFormat); } @Override void completeResponseExistent(ByteBuf buf, short status) { boolean wasSuccess = HotRodConstants.isSuccess(status); if (log.isTraceEnabled()) { log.tracef("Returning from setIfAbsent: %s", wasSuccess); } statsDataStore(); complete(wasSuccess); } @Override void completeResponseNotExistent(ByteBuf buf, short status) { completeResponseExistent(buf, status); } }
1,385
31.232558
119
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/HotRodOperation.java
package org.infinispan.hotrod.impl.operations; import static org.infinispan.hotrod.impl.logging.Log.HOTROD; import java.net.SocketAddress; import java.net.SocketTimeoutException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.infinispan.api.common.CacheEntryExpiration; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.HotRodFlag; import org.infinispan.hotrod.HotRodFlags; import org.infinispan.hotrod.exceptions.HotRodClientException; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.hotrod.impl.protocol.HeaderParams; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.hotrod.impl.transport.netty.HotRodClientDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.handler.codec.DecoderException; /** * Generic Hot Rod operation. It is aware of {@link HotRodFlag}s and it is targeted against a cache name. This base * class encapsulates the knowledge of writing and reading a header, as described in the * <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol specification</a> * * @since 14.0 */ public abstract class HotRodOperation<T> extends CompletableFuture<T> implements HotRodConstants, Runnable { private static final Log log = LogFactory.getLog(HotRodOperation.class); private static final AtomicLong MSG_ID = new AtomicLong(1); private static final byte NO_TX = 0; protected final OperationContext operationContext; protected final CacheOptions.Impl options; protected final HeaderParams header; protected volatile ScheduledFuture<?> timeoutFuture; private Channel channel; protected HotRodOperation(OperationContext operationContext, short requestCode, short responseCode, CacheOptions options, DataFormat dataFormat) { this.operationContext = operationContext; this.options = (CacheOptions.Impl) options; // TODO: we could inline all the header here this.header = new HeaderParams(requestCode, responseCode, flags(), NO_TX, MSG_ID.getAndIncrement(), dataFormat, operationContext.getClientTopology()) .cacheName(operationContext.getCacheNameBytes()) .topologyAge(operationContext.getChannelFactory().getTopologyAge()); } protected HotRodOperation(OperationContext operationContext, short requestCode, short responseCode, CacheOptions options) { this(operationContext, requestCode, responseCode, options, null); } public abstract CompletionStage<T> execute(); public HeaderParams header() { return header; } protected int flags() { int flags = HotRodFlags.toInt(options); if (options instanceof CacheWriteOptions) { CacheEntryExpiration.Impl expiration = (CacheEntryExpiration.Impl) ((CacheWriteOptions) options).expiration(); if (expiration.rawLifespan() == null) { flags |= HotRodFlag.DEFAULT_LIFESPAN.getFlagInt(); } if (expiration.rawMaxIdle() == null) { flags |= HotRodFlag.DEFAULT_MAXIDLE.getFlagInt(); } } return flags; } protected void sendHeaderAndRead(Channel channel) { scheduleRead(channel); sendHeader(channel); } protected void sendHeader(Channel channel) { ByteBuf buf = channel.alloc().buffer(operationContext.getCodec().estimateHeaderSize(header)); operationContext.getCodec().writeHeader(buf, header); channel.writeAndFlush(buf); } protected void scheduleRead(Channel channel) { channel.pipeline().get(HotRodClientDecoder.class).registerOperation(channel, this); } public void releaseChannel(Channel channel) { operationContext.getChannelFactory().releaseChannel(channel); } public void channelInactive(Channel channel) { SocketAddress address = channel.remoteAddress(); completeExceptionally(log.connectionClosed(address, address)); } public void exceptionCaught(Channel channel, Throwable cause) { while (cause instanceof DecoderException && cause.getCause() != null) { cause = cause.getCause(); } try { if (cause instanceof HotRodClientException && ((HotRodClientException) cause).isServerError()) { // don't close the channel, server just sent an error, there's nothing wrong with the channel } else { HOTROD.closingChannelAfterError(channel, cause); channel.close(); } } finally { completeExceptionally(cause); } } protected void sendArrayOperation(Channel channel, byte[] array) { // 1) write [header][array length][key] ByteBuf buf = channel.alloc().buffer(operationContext.getCodec().estimateHeaderSize(header) + ByteBufUtil.estimateArraySize(array)); operationContext.getCodec().writeHeader(buf, header); ByteBufUtil.writeArray(buf, array); channel.writeAndFlush(buf); } public abstract void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder); @Override public String toString() { byte[] cacheName = operationContext.getCacheNameBytes(); String cn = cacheName == null || cacheName.length == 0 ? "(default)" : new String(cacheName); StringBuilder sb = new StringBuilder(64); sb.append(getClass().getSimpleName()).append('{').append(cn); addParams(sb); sb.append(", flags=").append(Integer.toHexString(flags())); if (channel != null) { sb.append(", connection=").append(channel.remoteAddress()); } sb.append('}'); return sb.toString(); } protected void addParams(StringBuilder sb) { } @Override public boolean complete(T value) { cancelTimeout(); return super.complete(value); } @Override public boolean completeExceptionally(Throwable ex) { cancelTimeout(); return super.completeExceptionally(ex); } public void scheduleTimeout(Channel channel) { assert timeoutFuture == null; this.channel = channel; this.timeoutFuture = channel.eventLoop().schedule(this, operationContext.getChannelFactory().socketTimeout(), TimeUnit.MILLISECONDS); } private void cancelTimeout() { // Timeout future is not set if the operation completes before scheduling a read: // see RemoveClientListenerOperation.fetchChannelAndInvoke if (timeoutFuture != null) { timeoutFuture.cancel(false); } } @Override public void run() { exceptionCaught(channel, new SocketTimeoutException(this + " timed out after " + operationContext.getChannelFactory().socketTimeout() + " ms")); } public final DataFormat dataFormat() { return header.dataFormat(); } protected final byte[] cacheName() { return header.cacheName(); } }
7,242
37.121053
155
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/GetWithMetadataOperation.java
package org.infinispan.hotrod.impl.operations; import java.net.SocketAddress; import java.time.Duration; import java.util.Set; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryExpiration; import org.infinispan.api.common.CacheEntryVersion; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.cache.CacheEntryImpl; import org.infinispan.hotrod.impl.cache.CacheEntryMetadataImpl; import org.infinispan.hotrod.impl.cache.CacheEntryVersionImpl; import org.infinispan.hotrod.impl.logging.Log; import org.infinispan.hotrod.impl.logging.LogFactory; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Corresponds to getWithMetadata operation as described by * <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol specification</a>. * * @since 14.0 */ public class GetWithMetadataOperation<K, V> extends AbstractKeyOperation<K, CacheEntry<K, V>> implements RetryAwareCompletionStage<CacheEntry<K, V>> { private static final Log log = LogFactory.getLog(GetWithMetadataOperation.class); private final SocketAddress preferredServer; private volatile boolean retried; public GetWithMetadataOperation(OperationContext operationContext, K key, byte[] keyBytes, CacheOptions options, DataFormat dataFormat, SocketAddress preferredServer) { super(operationContext, GET_WITH_METADATA, GET_WITH_METADATA_RESPONSE, key, keyBytes, options, dataFormat); this.preferredServer = preferredServer; } public RetryAwareCompletionStage<CacheEntry<K, V>> internalExecute() { // The super.execute returns this, so the cast is safe //noinspection unchecked return (RetryAwareCompletionStage<CacheEntry<K, V>>) super.execute(); } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendArrayOperation(channel, keyBytes); } @Override protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { if (retryCount == 0 && preferredServer != null) { operationContext.getChannelFactory().fetchChannelAndInvoke(preferredServer, this); } else { retried = retryCount != 0; super.fetchChannelAndInvoke(retryCount, failedServers); } } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status) || !HotRodConstants.isSuccess(status)) { statsDataRead(false); complete(null); return; } short flags = buf.readUnsignedByte(); long creation = -1; int lifespan = -1; long lastUsed = -1; int maxIdle = -1; if ((flags & INFINITE_LIFESPAN) != INFINITE_LIFESPAN) { creation = buf.readLong(); lifespan = ByteBufUtil.readVInt(buf); } if ((flags & INFINITE_MAXIDLE) != INFINITE_MAXIDLE) { lastUsed = buf.readLong(); maxIdle = ByteBufUtil.readVInt(buf); } CacheEntryExpiration expiration; if (lifespan < 0) { if (maxIdle < 0) { expiration = CacheEntryExpiration.IMMORTAL; } else { expiration = CacheEntryExpiration.withMaxIdle(Duration.ofSeconds(maxIdle)); } } else { if (maxIdle < 0) { expiration = CacheEntryExpiration.withLifespan(Duration.ofSeconds(lifespan)); } else { expiration = CacheEntryExpiration.withLifespanAndMaxIdle(Duration.ofSeconds(lifespan), Duration.ofSeconds(maxIdle)); } } CacheEntryVersion version = new CacheEntryVersionImpl(buf.readLong()); if (log.isTraceEnabled()) { log.tracef("Received version: %s", version); } V value = dataFormat().valueToObj(ByteBufUtil.readArray(buf), operationContext.getConfiguration().getClassAllowList()); statsDataRead(true); complete(new CacheEntryImpl<>(operationKey(), value, new CacheEntryMetadataImpl(creation, lastUsed, expiration, version))); } @Override public Boolean wasRetried() { return isDone() ? retried : null; } }
4,469
38.210526
150
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/QueryOperation.java
package org.infinispan.hotrod.impl.operations; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.protocol.Codec; import org.infinispan.hotrod.impl.query.RemoteQuery; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; /** * @since 14.0 */ public final class QueryOperation extends RetryOnFailureOperation<Object> { private final RemoteQuery remoteQuery; private final QuerySerializer querySerializer; private final boolean withHitCount; public QueryOperation(OperationContext operationContext, CacheOptions options, RemoteQuery remoteQuery, DataFormat dataFormat, boolean withHitCount) { super(operationContext, QUERY_REQUEST, QUERY_RESPONSE, options, dataFormat); this.remoteQuery = remoteQuery; this.querySerializer = QuerySerializer.findByMediaType(dataFormat.getValueType()); this.withHitCount = withHitCount; } @Override protected void executeOperation(Channel channel) { // marshall and write the request byte[] requestBytes = querySerializer.serializeQueryRequest(remoteQuery, null); scheduleRead(channel); Codec codec = operationContext.getCodec(); // Here we'll rather just serialize the header + payload length than copying the requestBytes around ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + ByteBufUtil.estimateVIntSize(requestBytes.length)); codec.writeHeader(buf, header); ByteBufUtil.writeVInt(buf, requestBytes.length); channel.write(buf); channel.writeAndFlush(Unpooled.wrappedBuffer(requestBytes)); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { byte[] responseBytes = ByteBufUtil.readArray(buf); //FIXME //complete(querySerializer.readQueryResponse(channelFactory.getMarshaller(), queryRequest, responseBytes)); } }
2,128
38.425926
129
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/RemoveOperation.java
package org.infinispan.hotrod.impl.operations; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.DataFormat; import io.netty.buffer.ByteBuf; /** * Implement "remove" operation as described in <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @since 14.0 */ public class RemoveOperation<K> extends AbstractRemoveOperation<K, Boolean> { public RemoveOperation(OperationContext operationContext, K key, byte[] keyBytes, CacheOptions options, DataFormat dataFormat) { super(operationContext, key, keyBytes, options, dataFormat); } @Override void completeNotExist() { complete(Boolean.FALSE); } @Override void completeExisted(ByteBuf buf, short status) { statsDataRemove(); complete(Boolean.TRUE); } }
854
24.909091
112
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/IterationEndOperation.java
package org.infinispan.hotrod.impl.operations; import static org.infinispan.hotrod.impl.logging.Log.HOTROD; import java.util.concurrent.CompletableFuture; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * @since 14.0 */ public class IterationEndOperation extends HotRodOperation<IterationEndResponse> { private final byte[] iterationId; private final Channel channel; protected IterationEndOperation(OperationContext operationContext, CacheOptions options, byte[] iterationId, Channel channel) { super(operationContext, ITERATION_END_REQUEST, ITERATION_END_RESPONSE, options); this.iterationId = iterationId; this.channel = channel; } @Override public CompletableFuture<IterationEndResponse> execute() { if (!channel.isActive()) { throw HOTROD.channelInactive(channel.remoteAddress(), channel.remoteAddress()); } scheduleRead(channel); sendArrayOperation(channel, iterationId); releaseChannel(channel); return this; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(new IterationEndResponse(status)); } }
1,297
29.904762
130
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/UpdateBloomFilterOperation.java
package org.infinispan.hotrod.impl.operations; import java.net.SocketAddress; import java.util.concurrent.CompletableFuture; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.transport.netty.ChannelOperation; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; public class UpdateBloomFilterOperation extends HotRodOperation<Void> implements ChannelOperation { private final SocketAddress address; private final byte[] bloomBits; protected UpdateBloomFilterOperation(OperationContext operationContext, CacheOptions options, SocketAddress address, byte[] bloomBits) { super(operationContext, UPDATE_BLOOM_FILTER_REQUEST, UPDATE_BLOOM_FILTER_RESPONSE, options); this.address = address; this.bloomBits = bloomBits; } @Override public CompletableFuture<Void> execute() { try { operationContext.getChannelFactory().fetchChannelAndInvoke(address, this); } catch (Exception e) { completeExceptionally(e); } return this; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(null); } @Override public void invoke(Channel channel) { scheduleRead(channel); sendArrayOperation(channel, bloomBits); releaseChannel(channel); } @Override public void cancel(SocketAddress address, Throwable cause) { completeExceptionally(cause); } }
1,561
29.627451
99
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/ReplaceOperation.java
package org.infinispan.hotrod.impl.operations; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.protocol.HotRodConstants; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Implements "Replace" operation as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @since 14.0 */ public class ReplaceOperation<K, V> extends AbstractKeyValueOperation<K, CacheEntry<K, V>> { public ReplaceOperation(OperationContext operationContext, K key, byte[] keyBytes, byte[] value, CacheWriteOptions options, DataFormat dataFormat) { super(operationContext, REPLACE_REQUEST, REPLACE_RESPONSE, key, keyBytes, value, options, dataFormat); } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendKeyValueOperation(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isSuccess(status)) { statsDataStore(); } if (HotRodConstants.hasPrevious(status)) { statsDataRead(true); } complete(returnPossiblePrevValue(buf, status)); } }
1,380
32.682927
151
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/ParallelHotRodOperation.java
package org.infinispan.hotrod.impl.operations; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; /** * An HotRod operation that span across multiple remote nodes concurrently (like getAll / putAll). */ public abstract class ParallelHotRodOperation<T, SUBOP extends HotRodOperation<T>> extends StatsAffectingHotRodOperation<T> { protected ParallelHotRodOperation(OperationContext operationContext, CacheOptions options, DataFormat dataFormat) { super(operationContext, ILLEGAL_OP_CODE, ILLEGAL_OP_CODE, options, dataFormat); } @Override public CompletableFuture<T> execute() { List<SUBOP> operations = mapOperations(); if (operations.isEmpty()) { return CompletableFuture.completedFuture(createCollector()); } else if (operations.size() == 1) { // Only one operation to do, we stay in the caller thread return operations.get(0).execute().toCompletableFuture(); } else { // Multiple operation, submit to the thread poll return executeParallel(operations); } } private CompletableFuture<T> executeParallel(List<SUBOP> operations) { T collector = createCollector(); AtomicInteger counter = new AtomicInteger(operations.size()); for (SUBOP operation : operations) { operation.execute().whenComplete((result, throwable) -> { if (throwable != null) { completeExceptionally(throwable); } else { if (collector != null) { synchronized (collector) { combine(collector, result); } } if (counter.decrementAndGet() == 0) { complete(collector); } } }); } this.exceptionally(throwable -> { for (SUBOP operation : operations) { operation.cancel(true); } return null; }); return this; } protected abstract List<SUBOP> mapOperations(); protected abstract T createCollector(); protected abstract void combine(T collector, T result); @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { throw new UnsupportedOperationException(); } }
2,533
32.786667
125
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/SetOperation.java
package org.infinispan.hotrod.impl.operations; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.impl.DataFormat; /** * Implements "put" as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol * specification</a>. * * @since 14.0 */ public class SetOperation<K> extends AbstractPutOperation<K, Void> { public SetOperation(OperationContext operationContext, K key, byte[] keyBytes, byte[] value, CacheWriteOptions options, DataFormat dataFormat) { super(operationContext, key, keyBytes, value, options, dataFormat); } }
603
32.555556
147
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/PingResponse.java
package org.infinispan.hotrod.impl.operations; import java.util.Collections; import java.util.Set; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.hotrod.configuration.ProtocolVersion; import org.infinispan.hotrod.exceptions.HotRodClientException; import org.infinispan.hotrod.impl.protocol.HotRodConstants; public class PingResponse { public static final PingResponse EMPTY = new PingResponse(null); private final short status; private final ProtocolVersion version; private final MediaType keyMediaType; private final MediaType valueMediaType; private final Throwable error; private final Set<Short> serverOps; public PingResponse(short status, ProtocolVersion version, MediaType keyMediaType, MediaType valueMediaType, Set<Short> serverOps) { this.status = status; this.version = version; this.keyMediaType = keyMediaType; this.valueMediaType = valueMediaType; this.serverOps = serverOps; this.error = null; } PingResponse(Throwable error) { this.status = -1; this.version = ProtocolVersion.DEFAULT_PROTOCOL_VERSION; this.keyMediaType = MediaType.APPLICATION_UNKNOWN; this.valueMediaType = MediaType.APPLICATION_UNKNOWN; this.serverOps = Collections.emptySet(); this.error = error; } public short getStatus() { return status; } public boolean isSuccess() { return HotRodConstants.isSuccess(status); } public boolean isObjectStorage() { return keyMediaType != null && keyMediaType.match(MediaType.APPLICATION_OBJECT); } public boolean isFailed() { return error != null; } public boolean isCacheNotFound() { return error instanceof HotRodClientException && error.getMessage().contains("CacheNotFoundException"); } public Set<Short> getServerOps() { return serverOps; } public ProtocolVersion getVersion() { return version; } public MediaType getKeyMediaType() { return keyMediaType; } public MediaType getValueMediaType() { return valueMediaType; } }
2,134
26.727273
111
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/StatsAffectingRetryingOperation.java
package org.infinispan.hotrod.impl.operations; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.DataFormat; import io.netty.channel.Channel; /** * @since 14.0 */ public abstract class StatsAffectingRetryingOperation<T> extends RetryOnFailureOperation<T> { private long startTime; protected StatsAffectingRetryingOperation(OperationContext operationContext, short requestCode, short responseCode, CacheOptions options, DataFormat dataFormat) { super(operationContext, requestCode, responseCode, options, dataFormat); } @Override protected void scheduleRead(Channel channel) { if (operationContext.getClientStatistics().isEnabled()) { startTime = operationContext.getClientStatistics().time(); } super.scheduleRead(channel); } public void statsDataRead(boolean success) { if (operationContext.getClientStatistics().isEnabled()) { operationContext.getClientStatistics().dataRead(success, startTime, 1); } } protected void statsDataRead(boolean success, int count) { if (operationContext.getClientStatistics().isEnabled() && count > 0) { operationContext.getClientStatistics().dataRead(success, startTime, count); } } public void statsDataStore() { if (operationContext.getClientStatistics().isEnabled()) { operationContext.getClientStatistics().dataStore(startTime, 1); } } protected void statsDataStore(int count) { if (operationContext.getClientStatistics().isEnabled() && count > 0) { operationContext.getClientStatistics().dataStore(startTime, count); } } protected void statsDataRemove() { if (operationContext.getClientStatistics().isEnabled()) { operationContext.getClientStatistics().dataRemove(startTime, 1); } } }
1,851
32.071429
165
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/ExecuteOperation.java
package org.infinispan.hotrod.impl.operations; import static org.infinispan.hotrod.marshall.MarshallerUtil.bytes2obj; import java.net.SocketAddress; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.infinispan.api.common.CacheOptions; import org.infinispan.commons.util.Util; import org.infinispan.hotrod.impl.DataFormat; import org.infinispan.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * ExecuteOperation. * * @since 14.0 */ public class ExecuteOperation<T> extends RetryOnFailureOperation<T> { private final String taskName; private final Map<String, byte[]> marshalledParams; private final Object key; protected ExecuteOperation(OperationContext operationContext, CacheOptions options, String taskName, Map<String, byte[]> marshalledParams, Object key, DataFormat dataFormat) { super(operationContext, EXEC_REQUEST, EXEC_RESPONSE, options, dataFormat); this.taskName = taskName; this.marshalledParams = marshalledParams; this.key = key; } @Override protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { if (key != null) { operationContext.getChannelFactory().fetchChannelAndInvoke(key, failedServers, operationContext.getCacheNameBytes(), this); } else { operationContext.getChannelFactory().fetchChannelAndInvoke(failedServers, operationContext.getCacheNameBytes(), this); } } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(); // estimation too complex operationContext.getCodec().writeHeader(buf, header); ByteBufUtil.writeString(buf, taskName); ByteBufUtil.writeVInt(buf, marshalledParams.size()); for (Entry<String, byte[]> entry : marshalledParams.entrySet()) { ByteBufUtil.writeString(buf, entry.getKey()); ByteBufUtil.writeArray(buf, entry.getValue()); } channel.writeAndFlush(buf); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(bytes2obj(operationContext.getChannelFactory().getMarshaller(), ByteBufUtil.readArray(buf), dataFormat().isObjectStorage(), operationContext.getConfiguration().getClassAllowList())); } @Override protected void addParams(StringBuilder sb) { sb.append(", taskName=").append(taskName); sb.append(", params=["); for (Iterator<Entry<String, byte[]>> iterator = marshalledParams.entrySet().iterator(); iterator.hasNext(); ) { Entry<String, byte[]> entry = iterator.next(); String name = entry.getKey(); byte[] value = entry.getValue(); sb.append(name).append("=").append(Util.toStr(value)); if (iterator.hasNext()) { sb.append(", "); } } sb.append("]"); } }
3,042
35.22619
197
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/impl/operations/StatsAffectingHotRodOperation.java
package org.infinispan.hotrod.impl.operations; import org.infinispan.api.common.CacheOptions; import org.infinispan.hotrod.impl.DataFormat; import io.netty.channel.Channel; /** * @since 14.0 */ public abstract class StatsAffectingHotRodOperation<T> extends HotRodOperation<T> { private long startTime; protected StatsAffectingHotRodOperation(OperationContext operationContext, short requestCode, short responseCode, CacheOptions options, DataFormat dataFormat) { super(operationContext, requestCode, responseCode, options, dataFormat); } @Override protected void scheduleRead(Channel channel) { if (operationContext.getClientStatistics().isEnabled()) { startTime = operationContext.getClientStatistics().time(); } super.scheduleRead(channel); } protected void statsDataRead(boolean success) { if (operationContext.getClientStatistics().isEnabled()) { operationContext.getClientStatistics().dataRead(success, startTime, 1); } } protected void statsDataRead(boolean success, int count) { if (operationContext.getClientStatistics().isEnabled() && count > 0) { operationContext.getClientStatistics().dataRead(success, startTime, count); } } protected void statsDataStore() { if (operationContext.getClientStatistics().isEnabled()) { operationContext.getClientStatistics().dataStore(startTime, 1); } } protected void statsDataStore(int count) { if (operationContext.getClientStatistics().isEnabled() && count > 0) { operationContext.getClientStatistics().dataStore(startTime, count); } } }
1,698
32.313725
138
java