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-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/operations/ContainsEntryMultimapOperation.java
package org.infinispan.client.hotrod.impl.multimap.operations; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.CONTAINS_ENTRY_REQUEST; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.CONTAINS_ENTRY_RESPONSE; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; /** * 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>. * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ @Immutable public class ContainsEntryMultimapOperation extends AbstractMultimapKeyValueOperation<Boolean> { public ContainsEntryMultimapOperation(ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] value, ClientStatistics clientStatistics, boolean supportsDuplicates) { super(CONTAINS_ENTRY_REQUEST, CONTAINS_ENTRY_RESPONSE, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, value, -1, TimeUnit.MILLISECONDS, -1, TimeUnit.MILLISECONDS, null, clientStatistics, supportsDuplicates); } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendKeyValueOperation(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); } } }
2,274
43.607843
146
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/operations/AbstractMultimapKeyValueOperation.java
package org.infinispan.client.hotrod.impl.multimap.operations; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.exceptions.InvalidResponseException; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.AbstractKeyValueOperation; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; public abstract class AbstractMultimapKeyValueOperation<T> extends AbstractKeyValueOperation<T> { protected final boolean supportsDuplicates; protected AbstractMultimapKeyValueOperation(short requestCode, short responseCode, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, DataFormat dataFormat, ClientStatistics clientStatistics, boolean supportsDuplicates) { super(requestCode, responseCode, channelFactory.getNegotiatedCodec(), channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, value, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit, dataFormat, clientStatistics, null); this.supportsDuplicates = supportsDuplicates; } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendKeyValueOperation(channel); } @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); } @Override protected void sendKeyValueOperation(Channel channel) { ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + keyBytes.length + codec.estimateExpirationSize(lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit) + value.length + codec.estimateSizeMultimapSupportsDuplicated()); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, keyBytes); codec.writeExpirationParams(buf, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit); ByteBufUtil.writeArray(buf, value); codec.writeMultimapSupportDuplicates(buf, supportsDuplicates); channel.writeAndFlush(buf); } }
3,050
51.603448
245
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/operations/ContainsValueMultimapOperation.java
package org.infinispan.client.hotrod.impl.multimap.operations; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.CONTAINS_VALUE_MULTIMAP_REQUEST; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.CONTAINS_VALUE_MULTIMAP_RESPONSE; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.RetryOnFailureOperation; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.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>. * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public class ContainsValueMultimapOperation extends RetryOnFailureOperation<Boolean> { protected final byte[] value; private final long lifespan; private final long maxIdle; private final TimeUnit lifespanTimeUnit; private final TimeUnit maxIdleTimeUnit; private final boolean supportsDuplicates; protected ContainsValueMultimapOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, boolean supportsDuplicates) { super(CONTAINS_VALUE_MULTIMAP_REQUEST, CONTAINS_VALUE_MULTIMAP_RESPONSE, codec, channelFactory, cacheName, clientTopology, flags, cfg, null, null); this.value = value; this.lifespan = lifespan; this.maxIdle = maxIdle; this.lifespanTimeUnit = lifespanTimeUnit; this.maxIdleTimeUnit = maxIdleTimeUnit; 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) { ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + codec.estimateExpirationSize(lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit) + ByteBufUtil.estimateArraySize(value) + codec.estimateSizeMultimapSupportsDuplicated()); codec.writeHeader(buf, header); codec.writeExpirationParams(buf, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit); ByteBufUtil.writeArray(buf, value); codec.writeMultimapSupportDuplicates(buf, supportsDuplicates); channel.writeAndFlush(buf); } }
3,400
43.168831
155
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/operations/MultimapOperationsFactory.java
package org.infinispan.client.hotrod.impl.multimap.operations; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import net.jcip.annotations.Immutable; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.HotRodOperation; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; /** * Factory for {@link HotRodOperation} objects on Multimap. * * @author karesti@redhat.com * @since 9.2 */ @Immutable public class MultimapOperationsFactory { private final ThreadLocal<Integer> flagsMap = new ThreadLocal<>(); private final ChannelFactory transportFactory; private final byte[] cacheNameBytes; private final AtomicReference<ClientTopology> clientTopologyRef; private final boolean forceReturnValue; private final Configuration cfg; private final DataFormat dataFormat; private final ClientStatistics clientStatistics; public MultimapOperationsFactory(ChannelFactory channelFactory, String cacheName, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics) { this.transportFactory = channelFactory; this.cacheNameBytes = cacheName == null ? null : RemoteCacheManager.cacheNameBytes(cacheName); this.clientTopologyRef = channelFactory != null ? channelFactory.createTopologyId(cacheNameBytes) : new AtomicReference<>(new ClientTopology(-1, cfg.clientIntelligence())); this.forceReturnValue = cfg.forceReturnValues(); this.cfg = cfg; this.dataFormat = dataFormat; this.clientStatistics = clientStatistics; } public <K, V> GetKeyMultimapOperation<V> newGetKeyMultimapOperation(K key, byte[] keyBytes, boolean supportsDuplicates) { return new GetKeyMultimapOperation<>( transportFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, dataFormat, clientStatistics, supportsDuplicates); } public <K, V> GetKeyWithMetadataMultimapOperation<V> newGetKeyWithMetadataMultimapOperation(K key, byte[] keyBytes, boolean supportsDuplicates) { return new GetKeyWithMetadataMultimapOperation<>( transportFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, dataFormat, clientStatistics, supportsDuplicates); } public <K> PutKeyValueMultimapOperation newPutKeyValueOperation(K key, byte[] keyBytes, byte[] value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, boolean supportsDuplicates) { return new PutKeyValueMultimapOperation( transportFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(lifespan, maxIdle), cfg, value, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit, null, clientStatistics, supportsDuplicates); } public <K> RemoveKeyMultimapOperation newRemoveKeyOperation(K key, byte[] keyBytes, boolean supportsDuplicates) { return new RemoveKeyMultimapOperation( transportFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, clientStatistics, supportsDuplicates); } public <K> RemoveEntryMultimapOperation newRemoveEntryOperation(K key, byte[] keyBytes, byte[] value, boolean supportsDuplicates) { return new RemoveEntryMultimapOperation( transportFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, value, clientStatistics, supportsDuplicates); } public <K> ContainsEntryMultimapOperation newContainsEntryOperation(K key, byte[] keyBytes, byte[] value, boolean supportsDuplicates) { return new ContainsEntryMultimapOperation( transportFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, value, clientStatistics, supportsDuplicates); } public <K> ContainsKeyMultimapOperation newContainsKeyOperation(K key, byte[] keyBytes, boolean supportsDuplicates) { return new ContainsKeyMultimapOperation( transportFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, clientStatistics, supportsDuplicates); } public ContainsValueMultimapOperation newContainsValueOperation(byte[] value, boolean supportsDuplicates) { return new ContainsValueMultimapOperation( transportFactory.getNegotiatedCodec(), transportFactory, cacheNameBytes, clientTopologyRef, flags(), cfg, value, -1, TimeUnit.MILLISECONDS, -1, TimeUnit.MILLISECONDS, supportsDuplicates); } public SizeMultimapOperation newSizeOperation(boolean supportsDuplicates) { return new SizeMultimapOperation( transportFactory.getNegotiatedCodec(), transportFactory, cacheNameBytes, clientTopologyRef, flags(), cfg, supportsDuplicates); } public int flags() { Integer threadLocalFlags = this.flagsMap.get(); this.flagsMap.remove(); int intFlags = 0; if (threadLocalFlags != null) { intFlags |= threadLocalFlags; } if (forceReturnValue) { intFlags |= Flag.FORCE_RETURN_VALUE.getFlagInt(); } return intFlags; } private int flags(long lifespan, long maxIdle) { int intFlags = flags(); if (lifespan == 0) { intFlags |= Flag.DEFAULT_LIFESPAN.getFlagInt(); } if (maxIdle == 0) { intFlags |= Flag.DEFAULT_MAXIDLE.getFlagInt(); } return intFlags; } }
5,699
44.967742
199
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/metadata/MetadataCollectionImpl.java
package org.infinispan.client.hotrod.impl.multimap.metadata; import java.util.Collection; import org.infinispan.client.hotrod.multimap.MetadataCollection; /** * The values used in this class are assumed to be in MILLISECONDS * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public class MetadataCollectionImpl<V> implements MetadataCollection<V> { private final Collection<V> collection; private final long created; private final int lifespan; private final long lastUsed; private final int maxIdle; private final long version; public MetadataCollectionImpl(Collection<V> collection) { this.collection = collection; this.created = -1; this.lifespan = -1; this.lastUsed = -1; this.maxIdle = -1; this.version = -1; } public MetadataCollectionImpl(Collection<V> collection, long created, int lifespan, long lastUsed, int maxIdle, long version) { this.collection = collection; this.created = created; this.lifespan = lifespan; this.lastUsed = lastUsed; this.maxIdle = maxIdle; this.version = version; } @Override public Collection<V> getCollection() { return collection; } @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 long getVersion() { return version; } @Override public String toString() { StringBuilder b = new StringBuilder(); b.append("MetadataCollectionImpl{"); b.append("version="); b.append(version); b.append(", created="); b.append(created); b.append(", lastUsed="); b.append(lastUsed); b.append(", lifespan="); b.append(lifespan); b.append(", maxIdle="); b.append(maxIdle); b.append(", collection="); b.append(collection); b.append("}"); return b.toString(); } }
2,091
22.505618
130
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/ChannelInputStream.java
package org.infinispan.client.hotrod.impl.protocol; import java.io.IOException; import java.util.LinkedList; import org.infinispan.client.hotrod.VersionedMetadata; import org.infinispan.client.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,105
31.316456
121
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec26.java
package org.infinispan.client.hotrod.impl.protocol; import java.lang.annotation.Annotation; import java.util.Set; import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated; import org.infinispan.client.hotrod.annotation.ClientCacheEntryExpired; import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified; import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import io.netty.buffer.ByteBuf; /** * @since 8.2 */ public class Codec26 extends Codec25 { @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return writeHeader(buf, params, HotRodConstants.VERSION_26); } @Override public void writeClientListenerInterests(ByteBuf buf, Set<Class<? extends Annotation>> classes) { byte listenerInterests = 0; if (classes.contains(ClientCacheEntryCreated.class)) listenerInterests = (byte) (listenerInterests | 0x01); if (classes.contains(ClientCacheEntryModified.class)) listenerInterests = (byte) (listenerInterests | 0x02); if (classes.contains(ClientCacheEntryRemoved.class)) listenerInterests = (byte) (listenerInterests | 0x04); if (classes.contains(ClientCacheEntryExpired.class)) listenerInterests = (byte) (listenerInterests | 0x08); ByteBufUtil.writeVInt(buf, listenerInterests); } }
1,430
35.692308
100
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec21.java
package org.infinispan.client.hotrod.impl.protocol; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.net.SocketAddress; import java.util.function.Function; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.event.ClientEvent; import org.infinispan.client.hotrod.event.impl.AbstractClientEvent; import org.infinispan.client.hotrod.event.impl.ExpiredEventImpl; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.commons.configuration.ClassAllowList; import io.netty.buffer.ByteBuf; public class Codec21 extends Codec20 { @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return writeHeader(buf, params, HotRodConstants.VERSION_21); } @Override public void writeClientListenerParams(ByteBuf buf, ClientListener clientListener, byte[][] filterFactoryParams, byte[][] converterFactoryParams) { super.writeClientListenerParams(buf, clientListener, filterFactoryParams, converterFactoryParams); buf.writeByte((short) (clientListener.useRawData() ? 1 : 0)); } @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); } }
4,226
45.450549
182
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec23.java
package org.infinispan.client.hotrod.impl.protocol; import java.util.BitSet; import java.util.Map; import java.util.function.IntConsumer; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IteratorMapper; import io.netty.buffer.ByteBuf; /** * @author gustavonalle * @since 8.0 */ public class Codec23 extends Codec22 { @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return writeHeader(buf, params, HotRodConstants.VERSION_23); } @Override public <K> CloseableIterator<K> keyIterator(RemoteCache<K, ?> remoteCache, OperationsFactory operationsFactory, IntSet segments, int batchSize) { // Retrieve key and entry but map to key return new IteratorMapper<>(remoteCache.retrieveEntries(null, segments, batchSize), e -> (K) e.getKey()); } @Override public <K, V> CloseableIterator<Map.Entry<K, V>> entryIterator(RemoteCache<K, V> remoteCache, IntSet segments, int batchSize) { return castEntryIterator(remoteCache.retrieveEntries(null, segments, batchSize)); } protected <K, V> CloseableIterator<Map.Entry<K, V>> castEntryIterator(CloseableIterator iterator) { return iterator; } @Override public void writeIteratorStartOperation(ByteBuf buf, IntSet segments, String filterConverterFactory, int batchSize, boolean metadata, byte[][] filterParameters) { if (metadata) { throw new UnsupportedOperationException("Metadata for entry iteration not supported in this version!"); } if (segments == null) { ByteBufUtil.writeSignedVInt(buf, -1); } else { if (filterParameters != null && filterParameters.length > 0) { throw new UnsupportedOperationException("The filterParamters for entry iteration are not supported in this version!"); } // 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); ByteBufUtil.writeVInt(buf, batchSize); } }
2,486
37.261538
130
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec24.java
package org.infinispan.client.hotrod.impl.protocol; import java.util.Arrays; import java.util.BitSet; import java.util.function.IntConsumer; import org.infinispan.client.hotrod.impl.operations.PingResponse; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.commons.util.IntSet; import io.netty.buffer.ByteBuf; public class Codec24 extends Codec23 { @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return writeHeader(buf, params, HotRodConstants.VERSION_24); } @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 boolean isObjectStorageHinted(PingResponse pingResponse) { short status = pingResponse.getStatus(); return status == NO_ERROR_STATUS_OBJ_STORAGE || status == SUCCESS_WITH_PREVIOUS_OBJ_STORAGE || status == NOT_EXECUTED_WITH_PREVIOUS_OBJ_STORAGE; } }
1,992
34.589286
165
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/CodecHolder.java
package org.infinispan.client.hotrod.impl.protocol; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; /** * Holds a reference to the {@link Codec} negotiated with the server. * * @since 15.0 */ public class CodecHolder { private static final Log log = LogFactory.getLog(CodecHolder.class); private final AtomicReference<Codec> codec; public CodecHolder(Codec configuredCodec) { codec = new AtomicReference<>(configuredCodec); } public Codec getCodec() { return codec.get(); } public void setCodec(Codec newCodec) { Codec current = codec.get(); if (current.equals(newCodec)) { return; } log.debugf("Changing codec from %s to %s", current, newCodec); // if multiple PING happens in parallel, at least one will succeed // we assume all PING return the same negotiated codec. codec.compareAndSet(current, newCodec); } }
1,021
26.621622
72
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec30.java
package org.infinispan.client.hotrod.impl.protocol; import io.netty.buffer.ByteBuf; /** * @since 10.0 */ public class Codec30 extends Codec29 { @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return writeHeader(buf, params, HotRodConstants.VERSION_30); } }
306
20.928571
70
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/AbstractVersionedInputStream.java
package org.infinispan.client.hotrod.impl.protocol; import java.io.IOException; import java.io.InputStream; import org.infinispan.client.hotrod.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,239
22.396226
101
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/ChannelOutputStreamListener.java
package org.infinispan.client.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); }
269
23.545455
52
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec25.java
package org.infinispan.client.hotrod.impl.protocol; import io.netty.buffer.ByteBuf; /** * @author gustavonalle * @since 8.2 */ public class Codec25 extends Codec24 { @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return writeHeader(buf, params, HotRodConstants.VERSION_25); } @Override public short readMeta(ByteBuf buf) { return buf.readUnsignedByte(); } }
426
19.333333
70
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec40.java
package org.infinispan.client.hotrod.impl.protocol; import java.util.Map; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.impl.operations.GetWithMetadataOperation; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.marshall.Marshaller; import io.netty.buffer.ByteBuf; /** * @since 14.0 */ public class Codec40 extends Codec31 { @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return writeHeader(buf, params, HotRodConstants.VERSION_40); } @Override public Object returnPossiblePrevValue(ByteBuf buf, short status, DataFormat dataFormat, int flags, ClassAllowList allowList, Marshaller marshaller) { if (HotRodConstants.hasPrevious(status)) { MetadataValue<Object> metadataValue = GetWithMetadataOperation.readMetadataValue(buf, status, dataFormat, allowList); return metadataValue != null ? metadataValue.getValue() : null; } else { return null; } } @Override protected HeaderParams writeHeader(ByteBuf buf, HeaderParams params, byte version) { HeaderParams headerParams = super.writeHeader(buf, params, version); writeOtherParams(buf, params.otherParams()); return headerParams; } 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 int estimateSizeMultimapSupportsDuplicated() { return 1; } @Override public void writeMultimapSupportDuplicates(ByteBuf buf, boolean supportsDuplicates) { buf.writeByte(supportsDuplicates ? 1 : 0); } @Override public boolean isUnsafeForTheHandshake() { return true; } }
2,126
30.279412
152
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec28.java
package org.infinispan.client.hotrod.impl.protocol; import java.util.Map; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.MediaTypeIds; import io.netty.buffer.ByteBuf; /** * @since 9.3 */ public class Codec28 extends Codec27 { @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return this.writeHeader(buf, params, HotRodConstants.VERSION_28); } @Override protected HeaderParams writeHeader(ByteBuf buf, HeaderParams params, byte version) { HeaderParams headerParams = super.writeHeader(buf, params, version); writeDataTypes(buf, params.dataFormat); 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); }); } } @Override public boolean allowOperationsAndEvents() { return true; } }
1,950
29.015385
87
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec20.java
package org.infinispan.client.hotrod.impl.protocol; import static org.infinispan.client.hotrod.impl.Util.await; import static org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil.limitedHexDump; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.lang.annotation.Annotation; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.configuration.ClientIntelligence; import org.infinispan.client.hotrod.counter.impl.HotRodCounterEvent; import org.infinispan.client.hotrod.event.ClientEvent; import org.infinispan.client.hotrod.event.impl.AbstractClientEvent; import org.infinispan.client.hotrod.event.impl.CreatedEventImpl; import org.infinispan.client.hotrod.event.impl.CustomEventImpl; import org.infinispan.client.hotrod.event.impl.ModifiedEventImpl; import org.infinispan.client.hotrod.event.impl.RemovedEventImpl; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.exceptions.RemoteIllegalLifecycleStateException; import org.infinispan.client.hotrod.exceptions.RemoteNodeSuspectException; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.BulkGetKeysOperation; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.impl.operations.PingResponse; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.Closeables; import org.infinispan.commons.util.IntSet; import org.infinispan.counter.api.CounterState; import io.netty.buffer.ByteBuf; /** * A Hot Rod encoder/decoder for version 2.0 of the protocol. * * @author Galder Zamarreño * @since 7.0 */ public class Codec20 implements Codec, HotRodConstants { static final Log log = LogFactory.getLog(Codec.class, Log.class); public void writeClientListenerInterests(ByteBuf buf, Set<Class<? extends Annotation>> classes) { // No-op } @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return writeHeader(buf, params, HotRodConstants.VERSION_20); } @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); } @Override public void writeExpirationParams(ByteBuf buf, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit) { if (!CodecUtils.isGreaterThan4bytes(lifespan)) { HOTROD.warn("Lifespan value greater than the max supported size (Integer.MAX_VALUE), this can cause precision loss"); } if (!CodecUtils.isGreaterThan4bytes(maxIdle)) { HOTROD.warn("MaxIdle value greater than the max supported size (Integer.MAX_VALUE), this can cause precision loss"); } int lifespanSeconds = CodecUtils.toSeconds(lifespan, lifespanTimeUnit); int maxIdleSeconds = CodecUtils.toSeconds(maxIdle, maxIdleTimeUnit); ByteBufUtil.writeVInt(buf, lifespanSeconds); ByteBufUtil.writeVInt(buf, maxIdleSeconds); } @Override public void writeBloomFilter(ByteBuf buf, int bloomFilterBits) { if (bloomFilterBits > 0) { throw new UnsupportedOperationException("Bloom Filter optimization is not available for versions before 3.1"); } } @Override public int estimateExpirationSize(long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit) { int lifespanSeconds = CodecUtils.toSeconds(lifespan, lifespanTimeUnit); int maxIdleSeconds = CodecUtils.toSeconds(maxIdle, maxIdleTimeUnit); return ByteBufUtil.estimateVIntSize(lifespanSeconds) + ByteBufUtil.estimateVIntSize(maxIdleSeconds); } 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); int joinedFlags = params.flags; ByteBufUtil.writeVInt(buf, joinedFlags); 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), joinedFlags, 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, OperationsFactory operationsFactory, IntSet segments, int batchSize) { if (segments != null) { throw new UnsupportedOperationException("This version doesn't support iterating upon keys by segment!"); } BulkGetKeysOperation<K> op = operationsFactory.newBulkGetKeysOperation(0, remoteCache.getDataFormat()); Set<K> keys = await(op.execute()); return Closeables.iterator(keys.iterator()); } @Override public boolean isObjectStorageHinted(PingResponse pingResponse) { return false; } @Override public int estimateSizeMultimapSupportsDuplicated() { return 0; } @Override public void writeMultimapSupportDuplicates(ByteBuf buf, boolean supportsDuplicates) { } @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 ERROR_RESPONSE: checkForErrorsInResponseStatus(buf, null, status, serverAddress); // Fall through if we didn't throw an exception already 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 { switch (eventType) { case CLIENT_CACHE_ENTRY_CREATED: long createdDataVersion = buf.readLong(); return createCreatedEvent(listenerId, dataFormat.keyToObj(ByteBufUtil.readArray(buf), allowList), createdDataVersion, isRetried); case CLIENT_CACHE_ENTRY_MODIFIED: long modifiedDataVersion = buf.readLong(); return createModifiedEvent(listenerId, dataFormat.keyToObj(ByteBufUtil.readArray(buf), allowList), modifiedDataVersion, isRetried); case CLIENT_CACHE_ENTRY_REMOVED: return createRemovedEvent(listenerId, dataFormat.keyToObj(ByteBufUtil.readArray(buf), allowList), isRetried); default: throw HOTROD.unknownEvent(eventTypeId); } } } @Override public Object returnPossiblePrevValue(ByteBuf buf, short status, DataFormat dataFormat, int flags, ClassAllowList allowList, Marshaller marshaller) { if (HotRodConstants.hasPrevious(status)) { return dataFormat.valueToObj(ByteBufUtil.readArray(buf), 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; } }
18,639
43.486874
182
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/CodecUtils.java
package org.infinispan.client.hotrod.impl.protocol; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.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; /** * @author gustavonalle * @since 8.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,746
34.675325
97
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec.java
package org.infinispan.client.hotrod.impl.protocol; import java.lang.annotation.Annotation; import java.net.SocketAddress; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.counter.impl.HotRodCounterEvent; import org.infinispan.client.hotrod.event.impl.AbstractClientEvent; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.impl.operations.PingResponse; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; 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 io.netty.buffer.ByteBuf; /** * A Hot Rod protocol encoder/decoder. * * @author Galder Zamarreño * @since 5.1 */ public interface Codec { 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, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit); void writeBloomFilter(ByteBuf buf, int bloomFilterBits); int estimateExpirationSize(long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit); 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); Object returnPossiblePrevValue(ByteBuf buf, short status, DataFormat dataFormat, int flags, ClassAllowList allowList, Marshaller marshaller); void writeClientListenerInterests(ByteBuf buf, Set<Class<? extends Annotation>> classes); /** * 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 operationsFactory * @param segments * @param batchSize * @param <K> * @return */ default <K> CloseableIterator<K> keyIterator(RemoteCache<K, ?> remoteCache, OperationsFactory operationsFactory, 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<Map.Entry<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); /** * Returns true if the current codec uses a latest codec version, that could be unsafe for the initial handshake. * This is necessary to check interoperability between versions during the protocol negotiation. */ default boolean isUnsafeForTheHandshake() { return false; } }
5,986
33.211429
174
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/HotRodConstants.java
package org.infinispan.client.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.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants; import org.infinispan.commons.util.ReflectionUtil; /** * Defines constants defined by Hot Rod specifications. * * @author Mircea.Markus@jboss.com * @since 4.1 */ public interface HotRodConstants { short REQUEST_MAGIC = 0xA0; short RESPONSE_MAGIC = 0xA1; byte VERSION_20 = 20; byte VERSION_21 = 21; byte VERSION_22 = 22; byte VERSION_23 = 23; byte VERSION_24 = 24; byte VERSION_25 = 25; byte VERSION_26 = 26; byte VERSION_27 = 27; byte VERSION_28 = 28; byte VERSION_29 = 29; byte VERSION_30 = 30; byte VERSION_31 = 31; 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; /** * @deprecated use {@link org.infinispan.client.hotrod.configuration.ClientIntelligence#BASIC} * instead */ @Deprecated byte CLIENT_INTELLIGENCE_BASIC = 0x01; /** * @deprecated use {@link org.infinispan.client.hotrod.configuration.ClientIntelligence#TOPOLOGY_AWARE} * instead */ @Deprecated byte CLIENT_INTELLIGENCE_TOPOLOGY_AWARE = 0x02; /** * @deprecated use {@link org.infinispan.client.hotrod.configuration.ClientIntelligence#HASH_DISTRIBUTION_AWARE} * instead */ @Deprecated byte CLIENT_INTELLIGENCE_HASH_DISTRIBUTION_AWARE = 0x03; 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]; } } }
8,949
32.646617
115
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/HeaderParams.java
package org.infinispan.client.hotrod.impl.protocol; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.impl.ClientTopology; /** * Hot Rod request header parameters * * @author Galder Zamarreño * @since 5.1 */ 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 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; } }
2,011
23.839506
176
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec31.java
package org.infinispan.client.hotrod.impl.protocol; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import io.netty.buffer.ByteBuf; /** * @since 12.0 */ public class Codec31 extends Codec30 { @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return writeHeader(buf, params, HotRodConstants.VERSION_31); } @Override public void writeBloomFilter(ByteBuf buf, int bloomFilterBits) { ByteBufUtil.writeVInt(buf, bloomFilterBits); } }
515
23.571429
70
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/ChannelOutputStream.java
package org.infinispan.client.hotrod.impl.protocol; import java.io.IOException; import java.io.OutputStream; import org.infinispan.client.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,672
30.663793
110
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec29.java
package org.infinispan.client.hotrod.impl.protocol; import org.infinispan.client.hotrod.impl.operations.PingResponse; import org.infinispan.commons.dataconversion.MediaType; import io.netty.buffer.ByteBuf; /** * @since 9.4 */ public class Codec29 extends Codec28 { @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return writeHeader(buf, params, HotRodConstants.VERSION_29); } @Override public MediaType readKeyType(ByteBuf buf) { return CodecUtils.readMediaType(buf); } @Override public MediaType readValueType(ByteBuf buf) { return CodecUtils.readMediaType(buf); } @Override public boolean isObjectStorageHinted(PingResponse pingResponse) { return pingResponse.isObjectStorage(); } }
784
22.787879
70
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec27.java
package org.infinispan.client.hotrod.impl.protocol; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IteratorMapper; import io.netty.buffer.ByteBuf; /** * @since 9.2 */ public class Codec27 extends Codec26 { public static final String EMPTY_VALUE_CONVERTER = "org.infinispan.server.hotrod.HotRodServer$ToEmptyBytesKeyValueFilterConverter"; @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return writeHeader(buf, params, HotRodConstants.VERSION_27); } @Override public <K> CloseableIterator<K> keyIterator(RemoteCache<K, ?> remoteCache, OperationsFactory operationsFactory, IntSet segments, int batchSize) { return new IteratorMapper<>(remoteCache.retrieveEntries( // Use the ToEmptyBytesKeyValueFilterConverter to remove value payload EMPTY_VALUE_CONVERTER, segments, batchSize), e -> (K) e.getKey()); } }
1,113
34.935484
134
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/protocol/Codec22.java
package org.infinispan.client.hotrod.impl.protocol; import static org.infinispan.client.hotrod.impl.TimeUnitParam.encodeTimeUnits; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import io.netty.buffer.ByteBuf; public class Codec22 extends Codec21 { @Override public HeaderParams writeHeader(ByteBuf buf, HeaderParams params) { return writeHeader(buf, params, HotRodConstants.VERSION_22); } @Override public void writeExpirationParams(ByteBuf buf, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit) { byte timeUnits = encodeTimeUnits(lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit); buf.writeByte(timeUnits); if (lifespan > 0) { ByteBufUtil.writeVLong(buf, lifespan); } if (maxIdle > 0) { ByteBufUtil.writeVLong(buf, maxIdle); } } @Override public int estimateExpirationSize(long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit) { return 1 + (lifespan > 0 ? ByteBufUtil.estimateVLongSize(lifespan) : 0) + (lifespan > 0 ? ByteBufUtil.estimateVLongSize(maxIdle) : 0); } }
1,196
33.2
140
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/consistenthash/CRC16ConsistentHashV2.java
package org.infinispan.client.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()); } public CRC16ConsistentHashV2() { this(new Random()); } }
351
19.705882
61
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/consistenthash/ConsistentHash.java
package org.infinispan.client.hotrod.impl.consistenthash; import java.net.SocketAddress; import java.util.Map; import java.util.Set; /** * Abstraction for the used consistent hash. * * @author Mircea.Markus@jboss.com * @since 4.1 */ public interface ConsistentHash { @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; } }
870
24.617647
93
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/consistenthash/ConsistentHashV2.java
package org.infinispan.client.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.client.hotrod.logging.LogFactory; import org.infinispan.commons.hash.Hash; import org.infinispan.commons.hash.MurmurHash3; import org.infinispan.commons.util.Util; import org.jboss.logging.BasicLogger; /** * Version 2 of the ConsistentHash function. Uses MurmurHash3. * * @author manik * @see org.infinispan.commons.hash.MurmurHash3 * @since 5.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; } public ConsistentHashV2() { this(new Random()); } @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(); } }
4,032
28.437956
127
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/consistenthash/ConsistentHashFactory.java
package org.infinispan.client.hotrod.impl.consistenthash; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.commons.util.Util; /** * Factory for {@link org.infinispan.client.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.client.hotrod.impl.consistenthash.SegmentConsistentHash</code> * or if using the {@link Configuration} API, * <code>configuration.consistentHashImpl(3, org.infinispan.client.hotrod.impl.consistenthash.SegmentConsistentHash.class);</code> * <p/> * * <p>The defaults are:</p> * <ol> * <li>N/A (No longer used.)</li> * <li>org.infinispan.client.hotrod.impl.ConsistentHashV2</li> * <li>org.infinispan.client.hotrod.impl.SegmentConsistentHash</li> * </ol> * * @author Mircea.Markus@jboss.com * @since 4.1 */ public class ConsistentHashFactory { private Configuration configuration; public void init(Configuration 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,570
38.275
132
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/consistenthash/SegmentConsistentHash.java
package org.infinispan.client.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.client.hotrod.logging.Log; import org.infinispan.client.hotrod.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; /** * @author Galder Zamarreño */ 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,872
31.280899
101
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/RetryAwareCompletionStage.java
package org.infinispan.client.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(); }
502
37.692308
124
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/AddClientListenerOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.event.impl.ClientEventDispatcher; import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.InternalRemoteCache; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * @author Galder Zamarreño */ public class AddClientListenerOperation extends ClientListenerOperation { private final byte[][] filterFactoryParams; private final byte[][] converterFactoryParams; private final InternalRemoteCache<?, ?> remoteCache; private final TelemetryService telemetryService; protected AddClientListenerOperation(Codec codec, ChannelFactory channelFactory, String cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, ClientListenerNotifier listenerNotifier, Object listener, byte[][] filterFactoryParams, byte[][] converterFactoryParams, DataFormat dataFormat, InternalRemoteCache<?, ?> remoteCache, TelemetryService telemetryService) { this(codec, channelFactory, cacheName, clientTopology, flags, cfg, generateListenerId(), listenerNotifier, listener, filterFactoryParams, converterFactoryParams, dataFormat, remoteCache, telemetryService); } private AddClientListenerOperation(Codec codec, ChannelFactory channelFactory, String cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] listenerId, ClientListenerNotifier listenerNotifier, Object listener, byte[][] filterFactoryParams, byte[][] converterFactoryParams, DataFormat dataFormat, InternalRemoteCache<?, ?> remoteCache, TelemetryService telemetryService) { super(ADD_CLIENT_LISTENER_REQUEST, ADD_CLIENT_LISTENER_RESPONSE, codec, channelFactory, RemoteCacheManager.cacheNameBytes(cacheName), clientTopology, flags, cfg, listenerId, dataFormat, listener, cacheName, listenerNotifier, telemetryService); this.filterFactoryParams = filterFactoryParams; this.converterFactoryParams = converterFactoryParams; this.remoteCache = remoteCache; this.telemetryService = telemetryService; } public AddClientListenerOperation copy() { return new AddClientListenerOperation(codec, channelFactory, cacheNameString, header.getClientTopology(), flags(), cfg, listenerId, listenerNotifier, listener, filterFactoryParams, converterFactoryParams, dataFormat(), remoteCache, telemetryService); } @Override protected void actualExecute(Channel channel) { ClientListener clientListener = extractClientListener(); channel.pipeline().get(HeaderDecoder.class).registerOperation(channel, this); listenerNotifier.addDispatcher(ClientEventDispatcher.create(this, address, () -> cleanup(channel), remoteCache)); ByteBuf buf = channel.alloc().buffer(); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, listenerId); codec.writeClientListenerParams(buf, clientListener, filterFactoryParams, converterFactoryParams); codec.writeClientListenerInterests(buf, ClientEventDispatcher.findMethods(listener).keySet()); channel.writeAndFlush(buf); } }
4,222
52.455696
135
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/GetStreamOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.VersionedMetadataImpl; import org.infinispan.client.hotrod.impl.protocol.ChannelInputStream; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Streaming Get operation * * @author Tristan Tarrant * @since 9.0 */ @Immutable public class GetStreamOperation extends AbstractKeyOperation<ChannelInputStream> { private final int offset; private Channel channel; public GetStreamOperation(Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, int offset, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, ClientStatistics clientStatistics) { super(GET_STREAM_REQUEST, GET_STREAM_RESPONSE, codec, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, null, clientStatistics, null); this.offset = offset; } @Override public void executeOperation(Channel channel) { this.channel = channel; scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + ByteBufUtil.estimateArraySize(keyBytes) + ByteBufUtil.estimateVIntSize(offset)); codec.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); } } }
3,606
39.077778
146
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/ReplaceIfUnmodifiedOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.VersionedOperationResponse; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; 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>. * * @author Mircea.Markus@jboss.com * @since 4.1 */ public class ReplaceIfUnmodifiedOperation extends AbstractKeyValueOperation<VersionedOperationResponse> { private final long version; public ReplaceIfUnmodifiedOperation(Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, long version, DataFormat dataFormat, ClientStatistics clientStatistics, TelemetryService telemetryService) { super(REPLACE_IF_UNMODIFIED_REQUEST, REPLACE_IF_UNMODIFIED_RESPONSE, codec, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, value, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit, dataFormat, clientStatistics, telemetryService); this.version = version; } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + ByteBufUtil.estimateArraySize(keyBytes) + codec.estimateExpirationSize(lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit) + 8 + ByteBufUtil.estimateArraySize(value)); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, keyBytes); codec.writeExpirationParams(buf, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit); 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)); } }
3,060
45.378788
130
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/IterationNextResponse.java
package org.infinispan.client.hotrod.impl.operations; import java.util.List; import java.util.Map.Entry; import org.infinispan.commons.util.IntSet; /** * @author gustavonalle * @since 8.0 */ public class IterationNextResponse<K, E> { private final short status; private final List<Entry<K, E>> entries; private final IntSet completedSegments; private final boolean hasMore; public IterationNextResponse(short status, List<Entry<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<Entry<K, E>> getEntries() { return entries; } public short getStatus() { return status; } public IntSet getCompletedSegments() { return completedSegments; } }
923
21
117
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/IterationStartResponse.java
package org.infinispan.client.hotrod.impl.operations; import org.infinispan.client.hotrod.impl.consistenthash.SegmentConsistentHash; import io.netty.channel.Channel; /** * @author gustavonalle * @since 8.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; } }
1,010
24.275
125
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/RemoveIfUnmodifiedOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.VersionedOperationResponse; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Implements "removeIfUnmodified" operation as defined by * <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol specification</a>. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public class RemoveIfUnmodifiedOperation<V> extends AbstractKeyOperation<VersionedOperationResponse<V>> { private final long version; public RemoveIfUnmodifiedOperation(Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, long version, DataFormat dataFormat, ClientStatistics clientStatistics, TelemetryService telemetryService) { super(REMOVE_IF_UNMODIFIED_REQUEST, REMOVE_IF_UNMODIFIED_RESPONSE, codec, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, dataFormat.withoutValueType(), clientStatistics, telemetryService); this.version = version; } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); 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)); } }
2,492
41.254237
132
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/AbstractKeyValueOperation.java
package org.infinispan.client.hotrod.impl.operations; import static org.infinispan.commons.util.Util.printArray; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Base class for all operations that manipulate a key and a value. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public abstract class AbstractKeyValueOperation<T> extends AbstractKeyOperation<T> { protected final byte[] value; protected final long lifespan; protected final long maxIdle; protected final TimeUnit lifespanTimeUnit; protected final TimeUnit maxIdleTimeUnit; protected AbstractKeyValueOperation(short requestCode, short responseCode, Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, DataFormat dataFormat, ClientStatistics clientStatistics, TelemetryService telemetryService) { super(requestCode, responseCode, codec, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics, telemetryService); this.value = value; this.lifespan = lifespan; this.maxIdle = maxIdle; this.lifespanTimeUnit = lifespanTimeUnit; this.maxIdleTimeUnit = maxIdleTimeUnit; } protected void sendKeyValueOperation(Channel channel) { ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + keyBytes.length + codec.estimateExpirationSize(lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit) + value.length); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, keyBytes); codec.writeExpirationParams(buf, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit); ByteBufUtil.writeArray(buf, value); channel.writeAndFlush(buf); } @Override protected void addParams(StringBuilder sb) { super.addParams(sb); sb.append(", value=").append(printArray(value)); } }
2,816
39.826087
168
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/IterationStartOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.net.SocketAddress; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.consistenthash.SegmentConsistentHash; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.commons.util.IntSet; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * @author gustavonalle * @since 8.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 ChannelFactory channelFactory; private final boolean metadata; private final SocketAddress addressTarget; private Channel channel; IterationStartOperation(Codec codec, int flags, Configuration cfg, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, String filterConverterFactory, byte[][] filterParameters, IntSet segments, int batchSize, ChannelFactory channelFactory, boolean metadata, DataFormat dataFormat, SocketAddress addressTarget) { super(ITERATION_START_REQUEST, ITERATION_START_RESPONSE, codec, channelFactory, cacheName, clientTopology, flags, cfg, dataFormat, null); this.filterConverterFactory = filterConverterFactory; this.filterParameters = filterParameters; this.segments = segments; this.batchSize = batchSize; this.channelFactory = channelFactory; this.metadata = metadata; this.addressTarget = addressTarget; } @Override protected void executeOperation(Channel channel) { this.channel = channel; scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(); codec.writeHeader(buf, header); codec.writeIteratorStartOperation(buf, segments, filterConverterFactory, batchSize, metadata, filterParameters); channel.writeAndFlush(buf); } @Override protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { if (addressTarget != null) { channelFactory.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) channelFactory.getConsistentHash(cacheName()); IterationStartResponse response = new IterationStartResponse(ByteBufUtil.readArray(buf), consistentHash, header.getClientTopology().get().getTopologyId(), channel); complete(response); } }
3,257
39.222222
170
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/PutAllOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.net.SocketAddress; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.exceptions.InvalidResponseException; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Implements "putAll" as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol specification</a>. * * @author William Burns * @since 7.2 */ @Immutable public class PutAllOperation extends StatsAffectingRetryingOperation<Void> { public PutAllOperation(Codec codec, ChannelFactory channelFactory, Map<byte[], byte[]> map, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, DataFormat dataFormat, ClientStatistics clientStatistics, TelemetryService telemetryService) { super(PUT_ALL_REQUEST, PUT_ALL_RESPONSE, codec, channelFactory, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics, telemetryService); this.map = map; this.lifespan = lifespan; this.lifespanTimeUnit = lifespanTimeUnit; this.maxIdle = maxIdle; this.maxIdleTimeUnit = maxIdleTimeUnit; } protected final Map<byte[], byte[]> map; protected final long lifespan; private final TimeUnit lifespanTimeUnit; protected final long maxIdle; private final TimeUnit maxIdleTimeUnit; @Override protected void executeOperation(Channel channel) { scheduleRead(channel); int bufSize = codec.estimateHeaderSize(header) + ByteBufUtil.estimateVIntSize(map.size()) + codec.estimateExpirationSize(lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit); 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, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit); 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) { channelFactory.fetchChannelAndInvoke(map.keySet().iterator().next(), failedServers, cacheName(), 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)); } }
3,864
41.01087
130
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/IterationEndResponse.java
package org.infinispan.client.hotrod.impl.operations; /** * @author gustavonalle * @since 8.0 */ public class IterationEndResponse { private final short status; public IterationEndResponse(short status) { this.status = status; } public short getStatus() { return status; } }
309
15.315789
53
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/HotRodOperation.java
package org.infinispan.client.hotrod.impl.operations; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.net.SocketAddress; import java.net.SocketTimeoutException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HeaderParams; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.handler.codec.DecoderException; import net.jcip.annotations.Immutable; /** * Generic Hot Rod operation. It is aware of {@link org.infinispan.client.hotrod.Flag}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> * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable 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); protected final Codec codec; protected final Configuration cfg; protected final ChannelFactory channelFactory; protected final HeaderParams header; protected volatile ScheduledFuture<?> timeoutFuture; private Channel channel; private static final byte NO_TX = 0; private static final byte XA_TX = 1; protected HotRodOperation(short requestCode, short responseCode, Codec codec, int flags, Configuration cfg, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, ChannelFactory channelFactory, DataFormat dataFormat) { this.cfg = cfg; this.codec = codec; this.channelFactory = channelFactory; // TODO: we could inline all the header here this.header = new HeaderParams(requestCode, responseCode, flags, NO_TX, MSG_ID.getAndIncrement(), dataFormat, clientTopology) .cacheName(cacheName) .topologyAge(channelFactory.getTopologyAge()); } protected HotRodOperation(short requestCode, short responseCode, Codec codec, int flags, Configuration cfg, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, ChannelFactory channelFactory) { this(requestCode, responseCode, codec, flags, cfg, cacheName, clientTopology, channelFactory, null); } public abstract CompletableFuture<T> execute(); public HeaderParams header() { return header; } protected void sendHeaderAndRead(Channel channel) { scheduleRead(channel); sendHeader(channel); } protected void sendHeader(Channel channel) { ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header)); codec.writeHeader(buf, header); channel.writeAndFlush(buf); } protected void scheduleRead(Channel channel) { channel.pipeline().get(HeaderDecoder.class).registerOperation(channel, this); } public void releaseChannel(Channel channel) { channelFactory.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 (closeChannelForCause(cause)) { HOTROD.closingChannelAfterError(channel, cause); channel.close(); } } finally { completeExceptionally(cause); } } protected final boolean isServerError(Throwable t) { return t instanceof HotRodClientException && ((HotRodClientException) t).isServerError(); } protected final boolean closeChannelForCause(Throwable t) { // don't close the channel, server just sent an error, there's nothing wrong with the channel return !(isServerError(t) // The request just timed out, the channel still ok. || t instanceof SocketTimeoutException); } protected void sendArrayOperation(Channel channel, byte[] array) { // 1) write [header][array length][key] ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + ByteBufUtil.estimateArraySize(array)); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, array); channel.writeAndFlush(buf); } public abstract void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder); @Override public String toString() { 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, channelFactory.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 " + channelFactory.socketTimeout() + " ms")); } public final DataFormat dataFormat() { return header.dataFormat(); } protected final byte[] cacheName() { return header.cacheName(); } protected final int flags() { return header.flags(); } public Codec getCodec() { return codec; } }
7,273
34.832512
209
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/GetWithMetadataOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.net.SocketAddress; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.MetadataValueImpl; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.configuration.ClassAllowList; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Corresponds to getWithMetadata operation as described by * <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol specification</a>. * * @author Tristan Tarrant * @since 5.2 */ @Immutable public class GetWithMetadataOperation<V> extends AbstractKeyOperation<MetadataValue<V>> implements RetryAwareCompletionStage<MetadataValue<V>> { private static final Log log = LogFactory.getLog(GetWithMetadataOperation.class); private final SocketAddress preferredServer; private volatile boolean retried; public GetWithMetadataOperation(Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics, SocketAddress preferredServer) { super(GET_WITH_METADATA, GET_WITH_METADATA_RESPONSE, codec, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics, null); this.preferredServer = preferredServer; } public RetryAwareCompletionStage<MetadataValue<V>> internalExecute() { // The super.execute returns this, so the cast is safe //noinspection unchecked return (RetryAwareCompletionStage<MetadataValue<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) { channelFactory.fetchChannelAndInvoke(preferredServer, this); } else { retried = retryCount != 0; super.fetchChannelAndInvoke(retryCount, failedServers); } } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { MetadataValue<V> metadataValue = readMetadataValue(buf, status, dataFormat(), cfg.getClassAllowList()); statsDataRead(metadataValue != null); complete(metadataValue); } public static <V> MetadataValue<V> readMetadataValue(ByteBuf buf, short status, DataFormat dataFormat, ClassAllowList classAllowList) { if (HotRodConstants.isNotExist(status) || (!HotRodConstants.isSuccess(status) && !HotRodConstants.hasPrevious(status))) { return null; } 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(); if (log.isTraceEnabled()) { log.tracef("Received version: %d", version); } V value = dataFormat.valueToObj(ByteBufUtil.readArray(buf), classAllowList); return new MetadataValueImpl<>(creation, lifespan, lastUsed, maxIdle, version, value); } @Override public Boolean wasRetried() { return isDone() ? retried : null; } }
4,491
39.107143
144
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/QueryOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.query.RemoteQuery; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.protostream.EnumMarshaller; import org.infinispan.protostream.SerializationContext; import org.infinispan.query.remote.client.impl.QueryRequest; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; /** * @author anistor@redhat.com * @since 6.0 */ public final class QueryOperation extends RetryOnFailureOperation<Object> { private final RemoteQuery<?> remoteQuery; private final QuerySerializer querySerializer; private final boolean withHitCount; public QueryOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, RemoteQuery<?> remoteQuery, DataFormat dataFormat, boolean withHitCount) { super(QUERY_REQUEST, QUERY_RESPONSE, codec, channelFactory, cacheName, clientTopology, flags, cfg, dataFormat, null); this.remoteQuery = remoteQuery; this.querySerializer = QuerySerializer.findByMediaType(dataFormat.getValueType()); this.withHitCount = withHitCount; } @Override protected void executeOperation(Channel channel) { QueryRequest queryRequest = new QueryRequest(); queryRequest.setQueryString(remoteQuery.getQueryString()); if (remoteQuery.getStartOffset() > 0) { queryRequest.setStartOffset(remoteQuery.getStartOffset()); } if (remoteQuery.getMaxResults() >= 0) { queryRequest.setMaxResults(remoteQuery.getMaxResults()); } if (withHitCount) { if (remoteQuery.hitCountAccuracy() != null) { queryRequest.hitCountAccuracy(remoteQuery.hitCountAccuracy()); } } else { queryRequest.hitCountAccuracy(1); } queryRequest.setNamedParameters(getNamedParameters()); queryRequest.setLocal(remoteQuery.isLocal()); // marshall and write the request byte[] requestBytes = querySerializer.serializeQueryRequest(remoteQuery, queryRequest); scheduleRead(channel); // 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)); } private List<QueryRequest.NamedParameter> getNamedParameters() { Map<String, Object> namedParameters = remoteQuery.getParameters(); if (namedParameters == null || namedParameters.isEmpty()) { return null; } final SerializationContext serCtx = remoteQuery.getSerializationContext(); List<QueryRequest.NamedParameter> params = new ArrayList<>(namedParameters.size()); for (Map.Entry<String, Object> e : namedParameters.entrySet()) { Object value = e.getValue(); // only if we're using protobuf, some simple types need conversion if (serCtx != null) { // todo [anistor] not the most elegant way of doing conversion if (value instanceof Enum) { EnumMarshaller encoder = (EnumMarshaller) serCtx.getMarshaller(value.getClass()); value = encoder.encode((Enum) value); } else if (value instanceof Boolean) { value = value.toString(); } else if (value instanceof Date) { value = ((Date) value).getTime(); } else if (value instanceof Instant) { value = ((Instant) value).toEpochMilli(); } } params.add(new QueryRequest.NamedParameter(e.getKey(), value)); } return params; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { byte[] responseBytes = ByteBufUtil.readArray(buf); complete(querySerializer.readQueryResponse(channelFactory.getMarshaller(), remoteQuery, responseBytes)); } }
4,789
40.293103
134
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/RemoveOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Implement "remove" operation as described in <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public class RemoveOperation<V> extends AbstractKeyOperation<V> { public RemoveOperation(Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics, TelemetryService telemetryService) { super(REMOVE_REQUEST, REMOVE_RESPONSE, codec, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics, telemetryService); } @Override public void executeOperation(Channel channel) { scheduleRead(channel); sendArrayOperation(channel, keyBytes); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { V result = returnPossiblePrevValue(buf, status); if (HotRodConstants.isNotExist(status)) { complete(null); } else { statsDataRemove(); complete(result); // NO_ERROR_STATUS } } }
2,091
37.740741
131
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/IterationEndOperation.java
package org.infinispan.client.hotrod.impl.operations; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * @author gustavonalle * @since 8.0 */ public class IterationEndOperation extends HotRodOperation<IterationEndResponse> { private final byte[] iterationId; private final Channel channel; protected IterationEndOperation(Codec codec, int flags, Configuration cfg, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, byte[] iterationId, ChannelFactory channelFactory, Channel channel) { super(ITERATION_END_REQUEST, ITERATION_END_RESPONSE, codec, flags, cfg, cacheName, clientTopology, channelFactory); 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,781
35.367347
133
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/UpdateBloomFilterOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.net.SocketAddress; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.ChannelOperation; import org.infinispan.client.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(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, SocketAddress address, byte[] bloomBits) { super(UPDATE_BLOOM_FILTER_REQUEST, UPDATE_BLOOM_FILTER_RESPONSE, codec, flags, cfg, cacheName, clientTopology, channelFactory); this.address = address; this.bloomBits = bloomBits; } @Override public CompletableFuture<Void> execute() { try { channelFactory.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,975
34.285714
133
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/ReplaceOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Implements "Replace" operation as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public class ReplaceOperation<V> extends AbstractKeyValueOperation<V> { public ReplaceOperation(Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, DataFormat dataFormat, ClientStatistics clientStatistics, TelemetryService telemetryService) { super(REPLACE_REQUEST, REPLACE_RESPONSE, codec, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, value, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit, dataFormat, clientStatistics, telemetryService); } @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)); } }
2,320
40.446429
130
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/ParallelHotRodOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; /** * An HotRod operation that span across multiple remote nodes concurrently (like getAll / putAll). * * @author Guillaume Darmont / guillaume@dropinocean.com */ public abstract class ParallelHotRodOperation<T, SUBOP extends HotRodOperation<T>> extends StatsAffectingHotRodOperation<T> { protected final ChannelFactory channelFactory; protected ParallelHotRodOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics) { super(ILLEGAL_OP_CODE, ILLEGAL_OP_CODE, codec, flags, cfg, cacheName, clientTopology, channelFactory, dataFormat, clientStatistics); this.channelFactory = channelFactory; } @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(); } 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(); } }
3,178
35.965116
138
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/PingResponse.java
package org.infinispan.client.hotrod.impl.operations; import java.util.Collections; import java.util.Set; import java.util.TreeSet; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.commons.dataconversion.MediaType; import io.netty.buffer.ByteBuf; 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; private 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; } public static class Decoder { int decoderState = 0; final ProtocolVersion version; ProtocolVersion serverVersion; int serverOpsCount = -1; Set<Short> serverOps; MediaType keyMediaType; MediaType valueMediaType; Decoder(ProtocolVersion version) { this.version = version; } void processResponse(Codec codec, ByteBuf buf, HeaderDecoder decoder) { while (decoderState < 4) { switch (decoderState) { case 0: keyMediaType = codec.readKeyType(buf); valueMediaType = codec.readKeyType(buf); decoder.checkpoint(); if (version.compareTo(ProtocolVersion.PROTOCOL_VERSION_30) < 0) { decoderState = 4; break; } ++decoderState; case 1: serverVersion = ProtocolVersion.getBestVersion(buf.readUnsignedByte()); decoder.checkpoint(); ++decoderState; case 2: serverOpsCount = ByteBufUtil.readVInt(buf); serverOps = new TreeSet<>(); decoder.checkpoint(); ++decoderState; case 3: while (serverOps.size() < serverOpsCount) { short opCode = buf.readShort(); serverOps.add(opCode); decoder.checkpoint(); } ++decoderState; } } } PingResponse build(short status) { assert decoderState == 4 : "Invalid decoder state"; return new PingResponse(status, version.choose(serverVersion), keyMediaType, valueMediaType, serverOps); } public void reset() { decoderState = 0; } } }
4,258
30.087591
136
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/StatsAffectingRetryingOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import io.netty.channel.Channel; /** * @since 9.4 * @author Tristan Tarrant */ public abstract class StatsAffectingRetryingOperation<T> extends RetryOnFailureOperation<T> { protected ClientStatistics clientStatistics; private long startTime; protected StatsAffectingRetryingOperation(short requestCode, short responseCode, Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics, TelemetryService telemetryService) { super(requestCode, responseCode, codec, channelFactory, cacheName, clientTopology, flags, cfg, dataFormat, telemetryService); this.clientStatistics = clientStatistics; } @Override protected void scheduleRead(Channel channel) { if (clientStatistics.isEnabled()) { startTime = clientStatistics.time(); } super.scheduleRead(channel); } protected void statsDataRead(boolean success) { if (clientStatistics.isEnabled()) { clientStatistics.dataRead(success, startTime, 1); } } protected void statsDataRead(boolean success, int count) { if (clientStatistics.isEnabled() && count > 0) { clientStatistics.dataRead(success, startTime, count); } } protected void statsDataStore() { if (clientStatistics.isEnabled()) { clientStatistics.dataStore(startTime, 1); } } protected void statsDataStore(int count) { if (clientStatistics.isEnabled() && count > 0) { clientStatistics.dataStore(startTime, count); } } protected void statsDataRemove() { if (clientStatistics.isEnabled()) { clientStatistics.dataRemove(startTime, 1); } } }
2,406
34.397059
140
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/ExecuteOperation.java
package org.infinispan.client.hotrod.impl.operations; import static org.infinispan.client.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 java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.commons.util.Util; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * ExecuteOperation. * * @author Tristan Tarrant * @since 7.1 */ public class ExecuteOperation<T> extends RetryOnFailureOperation<T> { private final String taskName; private final Map<String, byte[]> marshalledParams; private final Object key; protected ExecuteOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, String taskName, Map<String, byte[]> marshalledParams, Object key, DataFormat dataFormat) { super(EXEC_REQUEST, EXEC_RESPONSE, codec, channelFactory, cacheName == null ? DEFAULT_CACHE_NAME_BYTES : cacheName, clientTopology, flags, cfg, dataFormat, null); this.taskName = taskName; this.marshalledParams = marshalledParams; this.key = key; } @Override protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { if (key != null) { channelFactory.fetchChannelAndInvoke(key, failedServers, cacheName(), this); } else { channelFactory.fetchChannelAndInvoke(failedServers, cacheName(), this); } } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(); // estimation too complex codec.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(channelFactory.getMarshaller(), ByteBufUtil.readArray(buf), dataFormat().isObjectStorage(), cfg.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,428
36.271739
143
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/StatsAffectingHotRodOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import io.netty.channel.Channel; /** * @since 9.4 * @author Tristan Tarrant */ public abstract class StatsAffectingHotRodOperation<T> extends HotRodOperation<T> { protected ClientStatistics clientStatistics; private long startTime; protected StatsAffectingHotRodOperation(short requestCode, short responseCode, Codec codec, int flags, Configuration cfg, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, ChannelFactory channelFactory, DataFormat dataFormat, ClientStatistics clientStatistics) { super(requestCode, responseCode, codec, flags, cfg, cacheName, clientTopology, channelFactory, dataFormat); this.clientStatistics = clientStatistics; } @Override protected void scheduleRead(Channel channel) { if (clientStatistics.isEnabled()) { startTime = clientStatistics.time(); } super.scheduleRead(channel); } protected void statsDataRead(boolean success) { if (clientStatistics.isEnabled()) { clientStatistics.dataRead(success, startTime, 1); } } protected void statsDataRead(boolean success, int count) { if (clientStatistics.isEnabled() && count > 0) { clientStatistics.dataRead(success, startTime, count); } } protected void statsDataStore() { if (clientStatistics.isEnabled()) { clientStatistics.dataStore(startTime, 1); } } protected void statsDataStore(int count) { if (clientStatistics.isEnabled() && count > 0) { clientStatistics.dataStore(startTime, count); } } }
2,122
33.803279
139
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/StatsOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.ServerStatistics; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.ServerStatisticsImpl; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Implements to the stats operation as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol specification</a>. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public class StatsOperation extends RetryOnFailureOperation<ServerStatistics> { private ServerStatisticsImpl result; private int numStats = -1; public StatsOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg) { super(STATS_REQUEST, STATS_RESPONSE, codec, channelFactory, cacheName, clientTopology, flags, cfg, null, null); } @Override protected void executeOperation(Channel channel) { sendHeaderAndRead(channel); } @Override protected void reset() { super.reset(); result = null; numStats = -1; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (numStats < 0) { numStats = ByteBufUtil.readVInt(buf); result = new ServerStatisticsImpl(); decoder.checkpoint(); } while (result.size() < numStats) { String statName = ByteBufUtil.readString(buf); String statValue = ByteBufUtil.readString(buf); result.addStats(statName, statValue); decoder.checkpoint(); } complete(result); } }
2,148
33.66129
143
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/GetOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Implements "get" operation as described by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol specification</a>. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public class GetOperation<V> extends AbstractKeyOperation<V> { public GetOperation(Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics) { super(GET_REQUEST, GET_RESPONSE, codec, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics, null); } @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) && HotRodConstants.isSuccess(status)) { statsDataRead(true); complete(dataFormat().valueToObj(ByteBufUtil.readArray(buf), cfg.getClassAllowList())); } else { statsDataRead(false); complete(null); } } }
2,063
38.692308
138
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/RetryOnFailureOperation.java
package org.infinispan.client.hotrod.impl.operations; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.io.IOException; import java.net.SocketAddress; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.exceptions.RemoteIllegalLifecycleStateException; import org.infinispan.client.hotrod.exceptions.RemoteNodeSuspectException; import org.infinispan.client.hotrod.exceptions.TransportException; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.ChannelOperation; import org.infinispan.client.hotrod.impl.transport.netty.ChannelRecord; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import io.netty.channel.Channel; import io.netty.handler.codec.DecoderException; import net.jcip.annotations.Immutable; /** * Base class for all the operations that need retry logic: if the operation fails due to connection problems, try with * another available connection. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public abstract class RetryOnFailureOperation<T> extends HotRodOperation<T> implements ChannelOperation { protected static final Log log = LogFactory.getLog(RetryOnFailureOperation.class, Log.class); private int retryCount = 0; private Set<SocketAddress> failedServers = null; protected RetryOnFailureOperation(short requestCode, short responseCode, Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, TelemetryService telemetryService) { super(requestCode, responseCode, codec, flags, cfg, cacheName, clientTopology, channelFactory, dataFormat); if (telemetryService != null) { telemetryService.injectSpanContext(header); } } @Override public CompletableFuture<T> execute() { assert !isDone(); try { if (log.isTraceEnabled()) { log.tracef("Requesting channel for operation %s", this); } fetchChannelAndInvoke(retryCount, failedServers); } catch (Exception e) { // if there's a bug before the operation is registered the operation wouldn't be completed completeExceptionally(e); } return this; } @Override public void invoke(Channel channel) { try { if (log.isTraceEnabled()) { log.tracef("About to start executing operation %s on %s", this, channel); } executeOperation(channel); } catch (Throwable t) { completeExceptionally(t); } finally { releaseChannel(channel); } } @Override public void cancel(SocketAddress address, Throwable cause) { cause = handleException(cause, null, address); if (cause != null) { completeExceptionally(cause); } } private void retryIfNotDone() { if (isDone()) { if (log.isTraceEnabled()) { log.tracef("Not retrying as done (exceptionally=%s), retryCount=%d", this.isCompletedExceptionally(), retryCount); } } else { reset(); fetchChannelAndInvoke(retryCount, failedServers); } } // hook for stateful operations protected void reset() { // The exception may happen when we try to fetch the channel; at this time the operation // is not registered yet and timeoutFuture is null if (timeoutFuture != null) { timeoutFuture.cancel(false); timeoutFuture = null; } // Update the topology age in case the retry is connecting to a new cluster header.topologyAge(channelFactory.getTopologyAge()); } private Set<SocketAddress> addFailedServer(SocketAddress address) { if (failedServers == null) { failedServers = new HashSet<>(); } if (log.isTraceEnabled()) log.tracef("Add %s to failed servers", address); failedServers.add(address); return failedServers; } @Override public void channelInactive(Channel channel) { if (isDone()) { return; } SocketAddress address = ChannelRecord.of(channel).getUnresolvedAddress(); addFailedServer(address); logAndRetryOrFail(HOTROD.connectionClosed(address, address)); } @Override public void exceptionCaught(Channel channel, Throwable cause) { SocketAddress address = channel == null ? null : ChannelRecord.of(channel).getUnresolvedAddress(); cause = handleException(cause, channel, address); if (cause != null) { // ctx.close() triggers channelInactive; we want to complete this to signal that no retries are expected try { completeExceptionally(cause); } finally { if (channel != null) { HOTROD.closingChannelAfterError(channel, cause); channel.close(); } } } } protected Throwable handleException(Throwable cause, Channel channel, SocketAddress address) { while (cause instanceof DecoderException && cause.getCause() != null) { cause = cause.getCause(); } if (cause instanceof RemoteIllegalLifecycleStateException || cause instanceof IOException || cause instanceof TransportException) { if (Thread.interrupted()) { // Don't invalidate the transport if our thread was interrupted completeExceptionally(new InterruptedException()); return null; } if (address != null) { addFailedServer(address); } if (channel != null && closeChannelForCause(cause)) { // We need to remove decoder even if we're about to close the channel // because otherwise we would be notified through channelInactive and we would retry (again). HeaderDecoder headerDecoder = (HeaderDecoder) channel.pipeline().get(HeaderDecoder.NAME); if (headerDecoder != null) { channel.pipeline().remove(HeaderDecoder.NAME); } HOTROD.closingChannelAfterError(channel, cause); channel.close(); if (headerDecoder != null) { headerDecoder.failoverClientListeners(); } } logAndRetryOrFail(cause); return null; } else if (cause instanceof RemoteNodeSuspectException) { // TODO Clients should never receive a RemoteNodeSuspectException, see ISPN-11636 logAndRetryOrFail(cause); return null; } else if (isServerError(cause)) { // fail the operation (don't retry) but don't close the channel completeExceptionally(cause); return null; } else { return cause; } } protected void logAndRetryOrFail(Throwable e) { if (retryCount < channelFactory.getMaxRetries()) { if (log.isTraceEnabled()) { log.tracef(e, "Exception encountered in %s. Retry %d out of %d", this, retryCount, channelFactory.getMaxRetries()); } retryCount++; channelFactory.incrementRetryCount(); retryIfNotDone(); } else { HOTROD.exceptionAndNoRetriesLeft(retryCount, channelFactory.getMaxRetries(), e); completeExceptionally(e); } } protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { channelFactory.fetchChannelAndInvoke(failedServers, cacheName(), this); } /** * Perform the operation-specific request/response I/O on the specified channel. * If an error occurs during I/O, this class will detect it and retry the operation with a different channel by invoking the executeOperation method again. * @param channel the channel to use for I/O */ protected abstract void executeOperation(Channel channel); }
8,456
37.266968
158
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/ClientListenerOperation.java
package org.infinispan.client.hotrod.impl.operations; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.ChannelRecord; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import org.infinispan.commons.util.ReflectionUtil; import org.infinispan.commons.util.Util; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; public abstract class ClientListenerOperation extends RetryOnFailureOperation<SocketAddress> { public final byte[] listenerId; public final Object listener; protected final String cacheNameString; protected final ClientListenerNotifier listenerNotifier; // Holds which address we are currently executing the operation on protected SocketAddress address; protected ClientListenerOperation(short requestCode, short responseCode, Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] listenerId, DataFormat dataFormat, Object listener, String cacheNameString, ClientListenerNotifier listenerNotifier, TelemetryService telemetryService) { super(requestCode, responseCode, codec, channelFactory, cacheName, clientTopology, flags, cfg, dataFormat, telemetryService); this.listenerId = listenerId; this.listener = listener; this.cacheNameString = cacheNameString; this.listenerNotifier = listenerNotifier; } protected static byte[] generateListenerId() { ThreadLocalRandom random = ThreadLocalRandom.current(); byte[] listenerId = new byte[16]; ByteBuffer bb = ByteBuffer.wrap(listenerId); bb.putLong(random.nextLong()); bb.putLong(random.nextLong()); return listenerId; } protected ClientListener extractClientListener() { ClientListener l = ReflectionUtil.getAnnotation(listener.getClass(), ClientListener.class); if (l == null) throw HOTROD.missingClientListenerAnnotation(listener.getClass().getName()); return l; } public String getCacheName() { return cacheNameString; } @Override protected final void executeOperation(Channel channel) { // Note: since the HeaderDecoder now supports decoding both operations and events we don't have to // wait until all operations complete; the server will deliver responses and we'll just handle them regardless // of the order if (!channel.isActive()) { channelInactive(channel); return; } this.address = ChannelRecord.of(channel).getUnresolvedAddress(); actualExecute(channel); } protected abstract void actualExecute(Channel channel); protected void cleanup(Channel channel) { channel.eventLoop().execute(() -> { if (!codec.allowOperationsAndEvents()) { if (channel.isOpen()) { channelFactory.releaseChannel(channel); } } HeaderDecoder decoder = channel.pipeline().get(HeaderDecoder.class); if (decoder != null) { decoder.removeListener(listenerId); } }); } @Override public void releaseChannel(Channel channel) { if (codec.allowOperationsAndEvents()) { super.releaseChannel(channel); } } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isSuccess(status)) { decoder.addListener(listenerId); listenerNotifier.startClientListener(listenerId); } else { // this releases the channel listenerNotifier.removeClientListener(listenerId); throw HOTROD.failedToAddListener(listener, status); } complete(address); } @Override public boolean completeExceptionally(Throwable ex) { if (!isDone()) { listenerNotifier.removeClientListener(listenerId); } return super.completeExceptionally(ex); } public void postponeTimeout(Channel channel) { assert !isDone(); timeoutFuture.cancel(false); timeoutFuture = null; scheduleTimeout(channel); } @Override protected void addParams(StringBuilder sb) { sb.append("listenerId=").append(Util.printArray(listenerId)); } abstract public ClientListenerOperation copy(); }
5,181
36.280576
132
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/AbstractKeyOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.net.SocketAddress; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.VersionedOperationResponse; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import org.infinispan.commons.util.Util; import io.netty.buffer.ByteBuf; import net.jcip.annotations.Immutable; /** * Basic class for all hot rod operations that manipulate a key. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public abstract class AbstractKeyOperation<T> extends StatsAffectingRetryingOperation<T> { protected final Object key; protected final byte[] keyBytes; protected AbstractKeyOperation(short requestCode, short responseCode, Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics, TelemetryService telemetryService) { super(requestCode, responseCode, codec, channelFactory, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics, telemetryService); this.key = key; this.keyBytes = keyBytes; } @Override protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { if (retryCount == 0) { channelFactory.fetchChannelAndInvoke(key == null ? keyBytes : key, failedServers, cacheName(), this); } else { channelFactory.fetchChannelAndInvoke(failedServers, cacheName(), this); } } protected T returnPossiblePrevValue(ByteBuf buf, short status) { return (T) codec.returnPossiblePrevValue(buf, status, dataFormat(), flags(), cfg.getClassAllowList(), channelFactory.getMarshaller()); } protected VersionedOperationResponse returnVersionedOperationResponse(ByteBuf buf, short status) { VersionedOperationResponse.RspCode code; if (HotRodConstants.isSuccess(status)) { code = VersionedOperationResponse.RspCode.SUCCESS; } else if (HotRodConstants.isNotExecuted(status)) { code = VersionedOperationResponse.RspCode.MODIFIED_KEY; } else if (HotRodConstants.isNotExist(status)) { code = VersionedOperationResponse.RspCode.NO_SUCH_KEY; } else { throw new IllegalStateException("Unknown response status: " + Integer.toHexString(status)); } Object prevValue = returnPossiblePrevValue(buf, status); return new VersionedOperationResponse(prevValue, code); } @Override protected void addParams(StringBuilder sb) { sb.append(", key=").append(key == null ? Util.printArray(keyBytes) : key); } }
3,267
42.573333
140
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/PingOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.net.SocketAddress; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.exceptions.InvalidResponseException; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.ChannelOperation; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.handler.codec.DecoderException; import net.jcip.annotations.Immutable; /** * Corresponds to the "ping" operation as defined in <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public class PingOperation extends NeutralVersionHotRodOperation<PingResponse> implements ChannelOperation { private static final Log log = LogFactory.getLog(PingOperation.class); private final boolean releaseChannel; private final PingResponse.Decoder responseBuilder; public PingOperation(Codec codec, AtomicReference<ClientTopology> clientTopology, Configuration cfg, byte[] cacheName, ChannelFactory channelFactory, boolean releaseChannel) { this(PING_REQUEST, PING_RESPONSE, codec, clientTopology, cfg, cacheName, channelFactory, releaseChannel); } protected PingOperation(short requestCode, short responseCode, Codec codec, AtomicReference<ClientTopology> clientTopology, Configuration cfg, byte[] cacheName, ChannelFactory channelFactory, boolean releaseChannel) { super(requestCode, responseCode, codec, 0, cfg, cacheName, clientTopology, channelFactory); this.releaseChannel = releaseChannel; this.responseBuilder = new PingResponse.Decoder(cfg.version()); } @Override public void invoke(Channel channel) { sendHeaderAndRead(channel); if (releaseChannel) { releaseChannel(channel); } } @Override public void cancel(SocketAddress address, Throwable cause) { completeExceptionally(cause); } @Override public CompletableFuture<PingResponse> execute() { throw new UnsupportedOperationException("Cannot execute directly"); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { responseBuilder.processResponse(codec, buf, decoder); if (HotRodConstants.isSuccess(status)) { PingResponse pingResponse = responseBuilder.build(status); if (pingResponse.getVersion() != null && cfg.version() == ProtocolVersion.PROTOCOL_VERSION_AUTO) { channelFactory.setNegotiatedCodec(pingResponse.getVersion().getCodec()); } complete(pingResponse); } else { String hexStatus = Integer.toHexString(status); if (log.isTraceEnabled()) log.tracef("Unknown response status: %s", hexStatus); throw new InvalidResponseException("Unexpected response status: " + hexStatus); } } @Override public void exceptionCaught(Channel channel, Throwable cause) { while (cause instanceof DecoderException && cause.getCause() != null) { cause = cause.getCause(); } PingResponse pingResponse = new PingResponse(cause); if (pingResponse.isCacheNotFound()) { complete(pingResponse); } else { super.exceptionCaught(channel, cause); } } }
3,931
38.717172
178
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/AdminOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; /** * AdminOperation. A special type of {@link ExecuteOperation} which returns the result of an admin operation which is always * represented as a JSON object. The actual parsing and interpretation of the result is up to the caller. * * @author Tristan Tarrant * @since 9.3 */ public class AdminOperation extends ExecuteOperation<String> { AdminOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, String taskName, Map<String, byte[]> marshalledParams) { super(codec, channelFactory, cacheName, clientTopology, flags, cfg, taskName, marshalledParams, null, null); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { byte[] bytes = ByteBufUtil.readArray(buf); complete(new String(bytes, StandardCharsets.UTF_8)); } }
1,492
42.911765
214
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/PutOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.exceptions.InvalidResponseException; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Implements "put" as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol specification</a>. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public class PutOperation<V> extends AbstractKeyValueOperation<V> { public PutOperation(Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, DataFormat dataFormat, ClientStatistics clientStatistics, TelemetryService telemetryService) { super(PUT_REQUEST, PUT_RESPONSE, codec, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, value, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit, dataFormat, clientStatistics, telemetryService); } @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)); } else { throw new InvalidResponseException("Unexpected response status: " + Integer.toHexString(status)); } } }
2,490
41.220339
127
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/PutStreamOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.io.IOException; import java.io.OutputStream; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.exceptions.InvalidResponseException; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.ChannelOutputStream; import org.infinispan.client.hotrod.impl.protocol.ChannelOutputStreamListener; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Streaming put operation * * @author Tristan Tarrant * @since 9.0 */ @Immutable public class PutStreamOperation extends AbstractKeyOperation<OutputStream> implements ChannelOutputStreamListener { static final long VERSION_PUT = 0; static final long VERSION_PUT_IF_ABSENT = -1; private final long version; private final long lifespan; private final long maxIdle; private final TimeUnit lifespanTimeUnit; private final TimeUnit maxIdleTimeUnit; private final CompletableFuture<Void> closeFuture = new CompletableFuture<>(); public PutStreamOperation(Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, long version, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, ClientStatistics clientStatistics, TelemetryService telemetryService) { super(PUT_STREAM_REQUEST, PUT_STREAM_RESPONSE, codec, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, null, clientStatistics, telemetryService); this.version = version; this.lifespan = lifespan; this.maxIdle = maxIdle; this.lifespanTimeUnit = lifespanTimeUnit; this.maxIdleTimeUnit = maxIdleTimeUnit; } @Override public void executeOperation(Channel channel) { scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + ByteBufUtil.estimateArraySize(keyBytes) + codec.estimateExpirationSize(lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit) + 8); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, keyBytes); codec.writeExpirationParams(buf, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit); buf.writeLong(version); channel.writeAndFlush(buf); complete(new ChannelOutputStream(channel, this)); } @Override public void releaseChannel(Channel channel) { } @Override public boolean completeExceptionally(Throwable ex) { closeFuture.completeExceptionally(ex); return super.completeExceptionally(ex); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isSuccess(status) || HotRodConstants.isNotExecuted(status) && (version != VERSION_PUT)) { if (HotRodConstants.isSuccess(status)) { statsDataStore(); } closeFuture.complete(null); } else { closeFuture.completeExceptionally(new InvalidResponseException("Unexpected response status: " + Integer.toHexString(status))); } } @Override public void onError(Channel channel, Throwable error) { completeExceptionally(error); } @Override public void onClose(Channel channel) throws IOException { try { closeFuture.join(); } catch (CompletionException e) { throw new IOException(e.getCause()); } finally { // When the channel is closed during the operation it's already released; don't do that again if (channel.isActive()) { channelFactory.releaseChannel(channel); } } } }
4,540
38.486957
135
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/QuerySerializer.java
package org.infinispan.client.hotrod.impl.operations; import static java.nio.charset.StandardCharsets.UTF_8; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.commons.dataconversion.MediaType.MATCH_ALL; import java.io.IOException; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.impl.query.RemoteQuery; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.protostream.SerializationContext; import org.infinispan.query.remote.client.impl.BaseQueryResponse; import org.infinispan.query.remote.client.impl.JsonClientQueryResponse; import org.infinispan.query.remote.client.impl.QueryRequest; import org.infinispan.query.remote.client.impl.QueryResponse; /** * @since 9.4 */ enum QuerySerializer { JSON(APPLICATION_JSON) { @Override byte[] serializeQueryRequest(RemoteQuery<?> remoteQuery, QueryRequest queryRequest) { Json object = Json.make(queryRequest); return object.toString().getBytes(UTF_8); } @Override JsonClientQueryResponse readQueryResponse(Marshaller marshaller, RemoteQuery<?> remoteQuery, byte[] bytesResponse) { Json response = Json.read(new String(bytesResponse, UTF_8)); return new JsonClientQueryResponse(response); } }, DEFAULT(MATCH_ALL) { @Override byte[] serializeQueryRequest(RemoteQuery<?> remoteQuery, QueryRequest queryRequest) { final SerializationContext serCtx = remoteQuery.getSerializationContext(); Marshaller marshaller; if (serCtx != null) { try { return ProtobufUtil.toByteArray(serCtx, queryRequest); } catch (IOException e) { throw new HotRodClientException(e); } } else { marshaller = remoteQuery.getCache().getRemoteCacheContainer().getMarshaller(); try { return marshaller.objectToByteBuffer(queryRequest); } catch (IOException e) { throw new HotRodClientException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new HotRodClientException(e); } } } @Override QueryResponse readQueryResponse(Marshaller marshaller, RemoteQuery<?> remoteQuery, byte[] bytesResponse) { SerializationContext serCtx = remoteQuery.getSerializationContext(); if (serCtx != null) { try { return ProtobufUtil.fromByteArray(serCtx, bytesResponse, QueryResponse.class); } catch (IOException e) { throw new HotRodClientException(e); } } else { try { return (QueryResponse) marshaller.objectFromByteBuffer(bytesResponse); } catch (IOException | ClassNotFoundException e) { throw new HotRodClientException(e); } } } }; private final MediaType mediaType; QuerySerializer(MediaType mediaType) { this.mediaType = mediaType; } @Override public String toString() { return mediaType.getTypeSubtype(); } static QuerySerializer findByMediaType(MediaType mediaType) { return mediaType != null && mediaType.match(APPLICATION_JSON) ? JSON : DEFAULT; } abstract byte[] serializeQueryRequest(RemoteQuery<?> remoteQuery, QueryRequest queryRequest); abstract BaseQueryResponse<?> readQueryResponse(Marshaller marshaller, RemoteQuery<?> remoteQuery, byte[] bytesResponse); }
3,783
36.098039
124
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/AddBloomNearCacheClientListenerOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.event.impl.ClientEventDispatcher; import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.InternalRemoteCache; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * @author Galder Zamarreño */ public class AddBloomNearCacheClientListenerOperation extends ClientListenerOperation { private final int bloomFilterBits; private final InternalRemoteCache<?, ?> remoteCache; protected AddBloomNearCacheClientListenerOperation(Codec codec, ChannelFactory channelFactory, String cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, ClientListenerNotifier listenerNotifier, Object listener, DataFormat dataFormat, int bloomFilterBits, InternalRemoteCache<?, ?> remoteCache) { this(codec, channelFactory, cacheName, clientTopology, flags, cfg, generateListenerId(), listenerNotifier, listener, dataFormat, bloomFilterBits, remoteCache); } private AddBloomNearCacheClientListenerOperation(Codec codec, ChannelFactory channelFactory, String cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] listenerId, ClientListenerNotifier listenerNotifier, Object listener, DataFormat dataFormat, int bloomFilterBits, InternalRemoteCache<?, ?> remoteCache) { super(ADD_BLOOM_FILTER_NEAR_CACHE_LISTENER_REQUEST, ADD_BLOOM_FILTER_NEAR_CACHE_LISTENER_RESPONSE, codec, channelFactory, RemoteCacheManager.cacheNameBytes(cacheName), clientTopology, flags, cfg, listenerId, dataFormat, listener, cacheName, listenerNotifier, null); this.bloomFilterBits = bloomFilterBits; this.remoteCache = remoteCache; } public AddBloomNearCacheClientListenerOperation copy() { return new AddBloomNearCacheClientListenerOperation(codec, channelFactory, cacheNameString, header.getClientTopology(), flags(), cfg, listenerId, listenerNotifier, listener, dataFormat(), bloomFilterBits, remoteCache); } @Override protected void actualExecute(Channel channel) { channel.pipeline().get(HeaderDecoder.class).registerOperation(channel, this); listenerNotifier.addDispatcher(ClientEventDispatcher.create(this, address, () -> cleanup(channel), remoteCache)); ByteBuf buf = channel.alloc().buffer(); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, listenerId); codec.writeBloomFilter(buf, bloomFilterBits); channel.writeAndFlush(buf); } }
3,615
49.929577
149
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/RemoveClientListenerOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.net.SocketAddress; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.ChannelOperation; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Remove client listener operation. In order to avoid issues with concurrent * event consumption, removing client listener operation is sent in a separate * connection to the one used for event consumption, but it must go to the * same node where the listener has been added. * * @author Galder Zamarreño */ public class RemoveClientListenerOperation extends HotRodOperation<Void> implements ChannelOperation { private final ClientListenerNotifier listenerNotifier; private final Object listener; private byte[] listenerId; protected RemoveClientListenerOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, ClientListenerNotifier listenerNotifier, Object listener) { super(REMOVE_CLIENT_LISTENER_REQUEST, REMOVE_CLIENT_LISTENER_RESPONSE, codec, flags, cfg, cacheName, clientTopology, channelFactory); this.listenerNotifier = listenerNotifier; this.listener = listener; } protected void fetchChannelAndInvoke() { listenerId = listenerNotifier.findListenerId(listener); if (listenerId != null) { SocketAddress address = listenerNotifier.findAddress(listenerId); channelFactory.fetchChannelAndInvoke(address, this); } else { complete(null); } } @Override public void invoke(Channel channel) { scheduleRead(channel); sendArrayOperation(channel, listenerId); releaseChannel(channel); } @Override public void cancel(SocketAddress address, Throwable cause) { completeExceptionally(cause); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isSuccess(status) || HotRodConstants.isNotExecuted(status)) { listenerNotifier.removeClientListener(listenerId); } complete(null); } @Override public CompletableFuture<Void> execute() { try { fetchChannelAndInvoke(); } catch (Exception e) { completeExceptionally(e); } return this; } }
3,032
35.987805
139
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/AuthOperation.java
package org.infinispan.client.hotrod.impl.operations; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Performs a step in the challenge/response authentication operation * * @author Tristan Tarrant * @since 7.0 */ @Immutable public class AuthOperation extends NeutralVersionHotRodOperation<byte[]> { private final Channel channel; private final String saslMechanism; private final byte[] response; public AuthOperation(Codec codec, AtomicReference<ClientTopology> clientTopology, Configuration cfg, Channel channel, ChannelFactory channelFactory, String saslMechanism, byte[] response) { super(AUTH_REQUEST, AUTH_RESPONSE, codec, 0, cfg, DEFAULT_CACHE_NAME_BYTES, clientTopology, channelFactory); this.channel = channel; this.saslMechanism = saslMechanism; this.response = response; } @Override public CompletableFuture<byte[]> execute() { if (!channel.isActive()) { throw HOTROD.channelInactive(channel.remoteAddress(), channel.remoteAddress()); } byte[] saslMechBytes = saslMechanism.getBytes(HOTROD_STRING_CHARSET); scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + ByteBufUtil.estimateArraySize(saslMechBytes) + ByteBufUtil.estimateArraySize(response)); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, saslMechBytes); ByteBufUtil.writeArray(buf, response); channel.writeAndFlush(buf); return this; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { boolean complete = buf.readUnsignedByte() > 0; byte[] challenge = ByteBufUtil.readArray(buf); complete(complete ? null : challenge); } }
2,404
34.367647
120
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/SizeOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; public class SizeOperation extends RetryOnFailureOperation<Integer> { protected SizeOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, TelemetryService telemetryService) { super(SIZE_REQUEST, SIZE_RESPONSE, codec, channelFactory, cacheName, clientTopology, flags, cfg, null, telemetryService); } @Override protected void executeOperation(Channel channel) { sendHeaderAndRead(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(ByteBufUtil.readVInt(buf)); } }
1,353
38.823529
127
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/FaultTolerantPingOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.net.SocketAddress; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.exceptions.InvalidResponseException; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.handler.codec.DecoderException; /** * A fault tolerant ping operation that can survive to node failures. * * @author Galder Zamarreño * @since 5.2 */ public class FaultTolerantPingOperation extends RetryOnFailureOperation<PingResponse> { private final PingResponse.Decoder responseBuilder; protected FaultTolerantPingOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg) { super(PING_REQUEST, PING_RESPONSE, codec, channelFactory, cacheName, clientTopology, flags, cfg, null, null); this.responseBuilder = new PingResponse.Decoder(cfg.version()); } @Override protected void executeOperation(Channel channel) { sendHeaderAndRead(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { responseBuilder.processResponse(codec, buf, decoder); if (HotRodConstants.isSuccess(status)) { PingResponse pingResponse = responseBuilder.build(status); if (pingResponse.getVersion() != null && cfg.version() == ProtocolVersion.PROTOCOL_VERSION_AUTO) { channelFactory.setNegotiatedCodec(pingResponse.getVersion().getCodec()); } complete(pingResponse); } else { String hexStatus = Integer.toHexString(status); if (log.isTraceEnabled()) log.tracef("Unknown response status: %s", hexStatus); throw new InvalidResponseException("Unexpected response status: " + hexStatus); } } @Override protected Throwable handleException(Throwable cause, Channel channel, SocketAddress address) { while (cause instanceof DecoderException && cause.getCause() != null) { cause = cause.getCause(); } PingResponse pingResponse = new PingResponse(cause); if (pingResponse.isCacheNotFound()) { complete(pingResponse); return null; } return super.handleException(cause, channel, address); } @Override protected void reset() { super.reset(); responseBuilder.reset(); } }
2,949
36.820513
116
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/PutIfAbsentOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import org.jboss.logging.BasicLogger; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Implements "putIfAbsent" operation as described in <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public class PutIfAbsentOperation<V> extends AbstractKeyValueOperation<V> { private static final BasicLogger log = LogFactory.getLog(PutIfAbsentOperation.class); public PutIfAbsentOperation(Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit, DataFormat dataFormat, ClientStatistics clientStatistics, TelemetryService telemetryService) { super(PUT_IF_ABSENT_REQUEST, PUT_IF_ABSENT_RESPONSE, codec, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, value, lifespan, lifespanTimeUnit, maxIdleTime, maxIdleTimeUnit, dataFormat, clientStatistics, telemetryService); } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendKeyValueOperation(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExecuted(status)) { V prevValue = returnPossiblePrevValue(buf, status); if (HotRodConstants.hasPrevious(status)) { statsDataRead(true); } if (log.isTraceEnabled()) { log.tracef("Returning from putIfAbsent: %s", prevValue); } complete(prevValue); } else { statsDataStore(); complete(null); } } }
2,761
40.848485
142
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/BulkGetKeysOperation.java
package org.infinispan.client.hotrod.impl.operations; import static org.infinispan.client.hotrod.marshall.MarshallerUtil.bytes2obj; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Reads all keys. Similar to <a href="http://community.jboss.org/wiki/HotRodBulkGet-Design">BulkGet</a>, but without the entry values. * * @author <a href="mailto:rtsang@redhat.com">Ray Tsang</a> * @since 5.2 */ public class BulkGetKeysOperation<K> extends StatsAffectingRetryingOperation<Set<K>> { private final int scope; private final Set<K> result = new HashSet<>(); public BulkGetKeysOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, int scope, DataFormat dataFormat, ClientStatistics clientStatistics) { super(BULK_GET_KEYS_REQUEST, BULK_GET_KEYS_RESPONSE, codec, channelFactory, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics, null); this.scope = scope; } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + ByteBufUtil.estimateVIntSize(scope)); codec.writeHeader(buf, header); ByteBufUtil.writeVInt(buf, scope); channel.writeAndFlush(buf); } @Override protected void reset() { super.reset(); result.clear(); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { while (buf.readUnsignedByte() == 1) { //there's more! result.add(bytes2obj(channelFactory.getMarshaller(), ByteBufUtil.readArray(buf), dataFormat().isObjectStorage(), cfg.getClassAllowList())); decoder.checkpoint(); } complete(result); } }
2,462
37.484375
179
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/ContainsKeyOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Implements "containsKey" operation as described in <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol specification</a>. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public class ContainsKeyOperation extends AbstractKeyOperation<Boolean> { public ContainsKeyOperation(Codec codec, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics) { super(CONTAINS_KEY_REQUEST, CONTAINS_KEY_RESPONSE, codec, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics, null); } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendArrayOperation(channel, keyBytes); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(!HotRodConstants.isNotExist(status) && HotRodConstants.isSuccess(status)); } }
1,855
40.244444
146
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/GetAllParallelOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.net.SocketAddress; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; /** * @author Guillaume Darmont / guillaume@dropinocean.com */ public class GetAllParallelOperation<K, V> extends ParallelHotRodOperation<Map<K, V>, GetAllOperation<K, V>> { private final Set<byte[]> keys; protected GetAllParallelOperation(Codec codec, ChannelFactory channelFactory, Set<byte[]> keys, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics) { super(codec, channelFactory, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics); this.keys = keys; } @Override protected List<GetAllOperation<K, V>> mapOperations() { Map<SocketAddress, Set<byte[]>> splittedKeys = new HashMap<>(); for (byte[] key : keys) { SocketAddress socketAddress = channelFactory.getHashAwareServer(key, cacheName()); Set<byte[]> keys = splittedKeys.computeIfAbsent(socketAddress, k -> new HashSet<>()); keys.add(key); } return splittedKeys.values().stream().map( keysSubset -> new GetAllOperation<K, V>(codec, channelFactory, keysSubset, cacheName(), header.getClientTopology(), flags(), cfg, dataFormat(), clientStatistics)).collect(Collectors.toList()); } @Override protected Map<K, V> createCollector() { return new HashMap<>(); } @Override protected void combine(Map<K, V> collector, Map<K, V> result) { collector.putAll(result); } }
2,150
36.736842
157
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/IterationNextOperation.java
package org.infinispan.client.hotrod.impl.operations; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.MetadataValueImpl; import org.infinispan.client.hotrod.impl.iteration.KeyTracker; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * @author gustavonalle * @since 8.0 */ public class IterationNextOperation<K, E> extends HotRodOperation<IterationNextResponse<K, E>> { private final byte[] iterationId; private final Channel channel; private final KeyTracker segmentKeyTracker; private byte[] finishedSegments; private int entriesSize = -1; private List<Entry<K, E>> entries; private int projectionsSize; private int untrackedEntries; protected IterationNextOperation(Codec codec, int flags, Configuration cfg, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, byte[] iterationId, Channel channel, ChannelFactory channelFactory, KeyTracker segmentKeyTracker, DataFormat dataFormat) { super(ITERATION_NEXT_REQUEST, ITERATION_NEXT_RESPONSE, codec, flags, cfg, cacheName, clientTopology, channelFactory, dataFormat); this.iterationId = iterationId; this.channel = channel; this.segmentKeyTracker = segmentKeyTracker; } @Override public CompletableFuture<IterationNextResponse<K, E>> execute() { if (!channel.isActive()) { throw HOTROD.channelInactive(channel.remoteAddress(), channel.remoteAddress()); } scheduleRead(channel); sendArrayOperation(channel, iterationId); return this; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (entriesSize < 0) { finishedSegments = ByteBufUtil.readArray(buf); entriesSize = ByteBufUtil.readVInt(buf); if (entriesSize == 0) { IntSet finishedSegmentSet = IntSets.from(finishedSegments); segmentKeyTracker.segmentsFinished(finishedSegmentSet); complete(new IterationNextResponse<>(status, Collections.emptyList(), finishedSegmentSet, false)); return; } entries = new ArrayList<>(entriesSize); projectionsSize = -1; decoder.checkpoint(); } if (projectionsSize < 0) { projectionsSize = codec.readProjectionSize(buf); decoder.checkpoint(); } while (entries.size() + untrackedEntries < entriesSize) { short meta = codec.readMeta(buf); long creation = -1; int lifespan = -1; long lastUsed = -1; int maxIdle = -1; long version = 0; if (meta == 1) { short flags = buf.readUnsignedByte(); 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); } version = buf.readLong(); } byte[] key = ByteBufUtil.readArray(buf); E value; if (projectionsSize > 1) { Object[] projections = new Object[projectionsSize]; for (int j = 0; j < projectionsSize; j++) { projections[j] = unmarshallValue(ByteBufUtil.readArray(buf)); } value = (E) projections; } else { value = unmarshallValue(ByteBufUtil.readArray(buf)); } if (meta == 1) { value = (E) new MetadataValueImpl<>(creation, lifespan, lastUsed, maxIdle, version, value); } if (segmentKeyTracker.track(key, status, cfg.getClassAllowList())) { K unmarshallKey = dataFormat().keyToObj(key, cfg.getClassAllowList()); entries.add(new SimpleEntry<>(unmarshallKey, value)); } else { untrackedEntries++; } decoder.checkpoint(); } IntSet finishedSegmentSet = IntSets.from(finishedSegments); segmentKeyTracker.segmentsFinished(finishedSegmentSet); if (HotRodConstants.isInvalidIteration(status)) { throw HOTROD.errorRetrievingNext(new String(iterationId, HOTROD_STRING_CHARSET)); } complete(new IterationNextResponse<>(status, entries, finishedSegmentSet, entriesSize > 0)); } private <M> M unmarshallValue(byte[] bytes) { return dataFormat().valueToObj(bytes, cfg.getClassAllowList()); } }
5,490
38.221429
135
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/NeutralVersionHotRodOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import net.jcip.annotations.Immutable; /** * An extension of {@link HotRodOperation} for backwards compatibility after introducing HR 4.0. We override the * <code>codec</code> with a pinned version, all operations are executed in the same way. * * @param <T> */ @Immutable public abstract class NeutralVersionHotRodOperation<T> extends HotRodOperation<T> { protected NeutralVersionHotRodOperation(short requestCode, short responseCode, Codec codec, int flags, Configuration cfg, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, ChannelFactory channelFactory) { super(requestCode, responseCode, chooseCodec(codec), flags, cfg, cacheName, clientTopology, channelFactory); } private static Codec chooseCodec(Codec codec) { return codec.isUnsafeForTheHandshake() ? ProtocolVersion.SAFE_HANDSHAKE_PROTOCOL_VERSION.getCodec() : codec; } }
1,339
42.225806
141
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/PutAllParallelOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.net.SocketAddress; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; /** * @author Guillaume Darmont / guillaume@dropinocean.com */ public class PutAllParallelOperation extends ParallelHotRodOperation<Void, PutAllOperation> { protected final Map<byte[], byte[]> map; protected final long lifespan; private final TimeUnit lifespanTimeUnit; protected final long maxIdle; private final TimeUnit maxIdleTimeUnit; private final TelemetryService telemetryService; public PutAllParallelOperation(Codec codec, ChannelFactory channelFactory, Map<byte[], byte[]> map, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, DataFormat dataFormat, ClientStatistics clientStatistics, TelemetryService telemetryService) { super(codec, channelFactory, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics); this.map = map; this.lifespan = lifespan; this.lifespanTimeUnit = lifespanTimeUnit; this.maxIdle = maxIdle; this.maxIdleTimeUnit = maxIdleTimeUnit; this.telemetryService = telemetryService; } @Override protected List<PutAllOperation> mapOperations() { Map<SocketAddress, Map<byte[], byte[]>> splittedMaps = new HashMap<>(); for (Map.Entry<byte[], byte[]> entry : map.entrySet()) { SocketAddress socketAddress = channelFactory.getHashAwareServer(entry.getKey(), cacheName()); Map<byte[], byte[]> keyValueMap = splittedMaps.computeIfAbsent(socketAddress, k -> new HashMap<>()); keyValueMap.put(entry.getKey(), entry.getValue()); } return splittedMaps.values().stream().map( mapSubset -> new PutAllOperation(codec, channelFactory, mapSubset, cacheName(), header.getClientTopology(), flags(), cfg, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit, dataFormat(), clientStatistics, telemetryService)).collect(Collectors.toList()); } @Override protected Void createCollector() { return null; } @Override protected void combine(Void collector, Void result) { // Nothing to do } }
2,975
40.333333
128
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/GetAllOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.net.SocketAddress; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Implements "getAll" as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol specification</a>. * * @author William Burns * @since 7.2 */ @Immutable public class GetAllOperation<K, V> extends StatsAffectingRetryingOperation<Map<K, V>> { private Map<K, V> result; private int size = -1; public GetAllOperation(Codec codec, ChannelFactory channelFactory, Set<byte[]> keys, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics) { super(GET_ALL_REQUEST, GET_ALL_RESPONSE, codec, channelFactory, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics, null); this.keys = keys; } protected final Set<byte[]> keys; @Override protected void executeOperation(Channel channel) { scheduleRead(channel); int bufSize = codec.estimateHeaderSize(header) + ByteBufUtil.estimateVIntSize(keys.size()); for (byte[] key : keys) { bufSize += ByteBufUtil.estimateArraySize(key); } ByteBuf buf = channel.alloc().buffer(bufSize); codec.writeHeader(buf, header); ByteBufUtil.writeVInt(buf, keys.size()); for (byte[] key : keys) { ByteBufUtil.writeArray(buf, key); } channel.writeAndFlush(buf); } @Override protected void reset() { super.reset(); result = null; size = -1; } @Override protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { channelFactory.fetchChannelAndInvoke(keys.iterator().next(), failedServers, cacheName(), this); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (size < 0) { size = ByteBufUtil.readVInt(buf); result = new HashMap<>(size); decoder.checkpoint(); } while (result.size() < size) { K key = dataFormat().keyToObj(ByteBufUtil.readArray(buf), cfg.getClassAllowList()); V value = dataFormat().valueToObj(ByteBufUtil.readArray(buf), cfg.getClassAllowList()); result.put(key, value); decoder.checkpoint(); } statsDataRead(true, size); statsDataRead(false, keys.size() - size); complete(result); } }
3,196
33.75
130
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/OperationsFactory.java
package org.infinispan.client.hotrod.impl.operations; import java.net.SocketAddress; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.CacheTopologyInfo; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.InternalRemoteCache; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash; import org.infinispan.client.hotrod.impl.iteration.KeyTracker; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.query.RemoteQuery; import org.infinispan.client.hotrod.impl.transaction.entry.Modification; import org.infinispan.client.hotrod.impl.transaction.operations.PrepareTransactionOperation; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import org.infinispan.commons.util.IntSet; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Factory for {@link org.infinispan.client.hotrod.impl.operations.HotRodOperation} objects. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public class OperationsFactory implements HotRodConstants { private static final Log log = LogFactory.getLog(OperationsFactory.class, Log.class); private final ThreadLocal<Integer> flagsMap = new ThreadLocal<>(); private final ChannelFactory channelFactory; private final byte[] cacheNameBytes; private final AtomicReference<ClientTopology> clientTopologyRef; private final boolean forceReturnValue; private final ClientListenerNotifier listenerNotifier; private final String cacheName; private final Configuration cfg; private final ClientStatistics clientStatistics; private final TelemetryService telemetryService; public OperationsFactory(ChannelFactory channelFactory, String cacheName, boolean forceReturnValue, ClientListenerNotifier listenerNotifier, Configuration cfg, ClientStatistics clientStatistics) { this.channelFactory = channelFactory; this.cacheNameBytes = cacheName == null ? DEFAULT_CACHE_NAME_BYTES : RemoteCacheManager.cacheNameBytes(cacheName); this.cacheName = cacheName; clientTopologyRef = channelFactory != null ? channelFactory.createTopologyId(cacheNameBytes) : new AtomicReference<>(new ClientTopology(-1, cfg.clientIntelligence())); this.forceReturnValue = forceReturnValue; this.listenerNotifier = listenerNotifier; this.cfg = cfg; this.clientStatistics = clientStatistics; TelemetryService telemetryService = null; try { if (cfg.tracingPropagationEnabled()) { telemetryService = TelemetryService.create(); log.openTelemetryPropagationEnabled(); } else { log.openTelemetryPropagationDisabled(); } } catch (Throwable e) { // missing dependency => no context to propagate to the server log.noOpenTelemetryAPI(e); } this.telemetryService = telemetryService; } public OperationsFactory(ChannelFactory channelFactory, ClientListenerNotifier listenerNotifier, Configuration cfg) { this(channelFactory, null, false, listenerNotifier, cfg, null); } public ClientListenerNotifier getListenerNotifier() { return listenerNotifier; } public String getCacheName() { return cacheName; } public ChannelFactory getChannelFactory() { return channelFactory; } public Codec getCodec() { return channelFactory.getNegotiatedCodec(); } public <V> GetOperation<V> newGetKeyOperation(Object key, byte[] keyBytes, DataFormat dataFormat) { return new GetOperation<>( getCodec(), channelFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, dataFormat, clientStatistics); } public <K, V> GetAllParallelOperation<K, V> newGetAllOperation(Set<byte[]> keys, DataFormat dataFormat) { return new GetAllParallelOperation<>(getCodec(), channelFactory, keys, cacheNameBytes, clientTopologyRef, flags(), cfg, dataFormat, clientStatistics); } public <V> RemoveOperation<V> newRemoveOperation(Object key, byte[] keyBytes, DataFormat dataFormat) { return new RemoveOperation<>( getCodec(), channelFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, dataFormat, clientStatistics, telemetryService); } public <V> RemoveIfUnmodifiedOperation<V> newRemoveIfUnmodifiedOperation(Object key, byte[] keyBytes, long version, DataFormat dataFormat) { return new RemoveIfUnmodifiedOperation<>( getCodec(), channelFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, version, dataFormat, clientStatistics, telemetryService); } public ReplaceIfUnmodifiedOperation newReplaceIfUnmodifiedOperation(Object key, byte[] keyBytes, byte[] value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, long version, DataFormat dataFormat) { return new ReplaceIfUnmodifiedOperation( getCodec(), channelFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(lifespan, maxIdle), cfg, value, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit, version, dataFormat, clientStatistics, telemetryService); } public <V> GetWithMetadataOperation<V> newGetWithMetadataOperation(Object key, byte[] keyBytes, DataFormat dataFormat) { return newGetWithMetadataOperation(key, keyBytes, dataFormat, null); } public <V> GetWithMetadataOperation<V> newGetWithMetadataOperation(Object key, byte[] keyBytes, DataFormat dataFormat, SocketAddress listenerServer) { return new GetWithMetadataOperation<>( getCodec(), channelFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, dataFormat, clientStatistics, listenerServer); } public StatsOperation newStatsOperation() { return new StatsOperation( getCodec(), channelFactory, cacheNameBytes, clientTopologyRef, flags(), cfg); } public <V> PutOperation<V> newPutKeyValueOperation(Object key, byte[] keyBytes, byte[] value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, DataFormat dataFormat) { return new PutOperation<>( getCodec(), channelFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(lifespan, maxIdle), cfg, value, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit, dataFormat, clientStatistics, telemetryService); } public PutAllParallelOperation newPutAllOperation(Map<byte[], byte[]> map, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, DataFormat dataFormat) { return new PutAllParallelOperation( getCodec(), channelFactory, map, cacheNameBytes, clientTopologyRef, flags(lifespan, maxIdle), cfg, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit, dataFormat, clientStatistics, telemetryService); } public <V> PutIfAbsentOperation<V> newPutIfAbsentOperation(Object key, byte[] keyBytes, byte[] value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit, DataFormat dataFormat) { return new PutIfAbsentOperation<>( getCodec(), channelFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(lifespan, maxIdleTime), cfg, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit, dataFormat, clientStatistics, telemetryService); } public <V> ReplaceOperation<V> newReplaceOperation(Object key, byte[] keyBytes, byte[] values, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, DataFormat dataFormat) { return new ReplaceOperation<>( getCodec(), channelFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(lifespan, maxIdle), cfg, values, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit, dataFormat, clientStatistics, telemetryService); } public ContainsKeyOperation newContainsKeyOperation(Object key, byte[] keyBytes, DataFormat dataFormat) { return new ContainsKeyOperation( getCodec(), channelFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, dataFormat, clientStatistics); } public ClearOperation newClearOperation() { return new ClearOperation( getCodec(), channelFactory, cacheNameBytes, clientTopologyRef, flags(), cfg, telemetryService); } public <K> BulkGetKeysOperation<K> newBulkGetKeysOperation(int scope, DataFormat dataFormat) { return new BulkGetKeysOperation<>( getCodec(), channelFactory, cacheNameBytes, clientTopologyRef, flags(), cfg, scope, dataFormat, clientStatistics); } public AddClientListenerOperation newAddClientListenerOperation(Object listener, DataFormat dataFormat) { return new AddClientListenerOperation(getCodec(), channelFactory, cacheName, clientTopologyRef, flags(), cfg, listenerNotifier, listener, null, null, dataFormat, null, telemetryService); } public AddClientListenerOperation newAddClientListenerOperation( Object listener, byte[][] filterFactoryParams, byte[][] converterFactoryParams, DataFormat dataFormat) { return new AddClientListenerOperation(getCodec(), channelFactory, cacheName, clientTopologyRef, flags(), cfg, listenerNotifier, listener, filterFactoryParams, converterFactoryParams, dataFormat, null, telemetryService); } public RemoveClientListenerOperation newRemoveClientListenerOperation(Object listener) { return new RemoveClientListenerOperation(getCodec(), channelFactory, cacheNameBytes, clientTopologyRef, flags(), cfg, listenerNotifier, listener); } public AddBloomNearCacheClientListenerOperation newAddNearCacheListenerOperation(Object listener, DataFormat dataFormat, int bloomFilterBits, InternalRemoteCache<?, ?> remoteCache) { return new AddBloomNearCacheClientListenerOperation(getCodec(), channelFactory, cacheName, clientTopologyRef, flags(), cfg, listenerNotifier, listener, dataFormat, bloomFilterBits, remoteCache); } public UpdateBloomFilterOperation newUpdateBloomFilterOperation(SocketAddress address, byte[] bloomBytes) { return new UpdateBloomFilterOperation(getCodec(), channelFactory, cacheNameBytes, clientTopologyRef, flags(), cfg, address, bloomBytes); } /** * Construct a ping request directed to a particular node. * * @return a ping operation for a particular node * @param releaseChannel */ public PingOperation newPingOperation(boolean releaseChannel) { return new PingOperation(getCodec(), clientTopologyRef, cfg, cacheNameBytes, channelFactory, releaseChannel); } /** * Construct a fault tolerant ping request. This operation should be capable * to deal with nodes being down, so it will find the first node successful * node to respond to the ping. * * @return a ping operation for the cluster */ public FaultTolerantPingOperation newFaultTolerantPingOperation() { return new FaultTolerantPingOperation( getCodec(), channelFactory, cacheNameBytes, clientTopologyRef, flags(), cfg); } public QueryOperation newQueryOperation(RemoteQuery<?> remoteQuery, DataFormat dataFormat, boolean withHitCount) { return new QueryOperation(getCodec(), channelFactory, cacheNameBytes, clientTopologyRef, flags(), cfg, remoteQuery, dataFormat, withHitCount); } public SizeOperation newSizeOperation() { return new SizeOperation(getCodec(), channelFactory, cacheNameBytes, clientTopologyRef, flags(), cfg, telemetryService); } public <T> ExecuteOperation<T> newExecuteOperation(String taskName, Map<String, byte[]> marshalledParams, Object key, DataFormat dataFormat) { return new ExecuteOperation<>(getCodec(), channelFactory, cacheNameBytes, clientTopologyRef, flags(), cfg, taskName, marshalledParams, key, dataFormat); } public AdminOperation newAdminOperation(String taskName, Map<String, byte[]> marshalledParams) { return new AdminOperation(getCodec(), channelFactory, cacheNameBytes, clientTopologyRef, flags(), cfg, taskName, marshalledParams); } private int flags(long lifespan, long maxIdle) { int intFlags = flags(); if (lifespan == 0) { intFlags |= Flag.DEFAULT_LIFESPAN.getFlagInt(); } if (maxIdle == 0) { intFlags |= Flag.DEFAULT_MAXIDLE.getFlagInt(); } return intFlags; } public int flags() { Integer threadLocalFlags = this.flagsMap.get(); this.flagsMap.remove(); int intFlags = 0; if (threadLocalFlags != null) { intFlags |= threadLocalFlags; } if (forceReturnValue) { intFlags |= Flag.FORCE_RETURN_VALUE.getFlagInt(); } return intFlags; } public void setFlags(Flag[] flags) { int intFlags = 0; for (Flag flag : flags) intFlags |= flag.getFlagInt(); this.flagsMap.set(intFlags); } public void setFlags(int intFlags) { this.flagsMap.set(intFlags); } public boolean hasFlag(Flag flag) { Integer threadLocalFlags = this.flagsMap.get(); return threadLocalFlags != null && (threadLocalFlags & flag.getFlagInt()) != 0; } public CacheTopologyInfo getCacheTopologyInfo() { return channelFactory.getCacheTopologyInfo(cacheNameBytes); } /** * Returns a map containing for each address all of its primarily owned segments. If the primary segments are not * known an empty map will be returned instead * @return map containing addresses and their primary segments */ public Map<SocketAddress, Set<Integer>> getPrimarySegmentsByAddress() { return channelFactory.getPrimarySegmentsByAddress(cacheNameBytes); } public ConsistentHash getConsistentHash() { return channelFactory.getConsistentHash(cacheNameBytes); } public int getTopologyId() { return clientTopologyRef.get().getTopologyId(); } public IterationStartOperation newIterationStartOperation(String filterConverterFactory, byte[][] filterParameters, IntSet segments, int batchSize, boolean metadata, DataFormat dataFormat, SocketAddress targetAddress) { return new IterationStartOperation(getCodec(), flags(), cfg, cacheNameBytes, clientTopologyRef, filterConverterFactory, filterParameters, segments, batchSize, channelFactory, metadata, dataFormat, targetAddress); } public IterationEndOperation newIterationEndOperation(byte[] iterationId, Channel channel) { return new IterationEndOperation(getCodec(), flags(), cfg, cacheNameBytes, clientTopologyRef, iterationId, channelFactory, channel); } public <K, E> IterationNextOperation<K, E> newIterationNextOperation(byte[] iterationId, Channel channel, KeyTracker segmentKeyTracker, DataFormat dataFormat) { return new IterationNextOperation<>(getCodec(), flags(), cfg, cacheNameBytes, clientTopologyRef, iterationId, channel, channelFactory, segmentKeyTracker, dataFormat); } public <K> GetStreamOperation newGetStreamOperation(K key, byte[] keyBytes, int offset) { return new GetStreamOperation(getCodec(), channelFactory, key, keyBytes, offset, cacheNameBytes, clientTopologyRef, flags(), cfg, clientStatistics); } public <K> PutStreamOperation newPutStreamOperation(K key, byte[] keyBytes, long version, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { return new PutStreamOperation(getCodec(), channelFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, version, lifespan, lifespanUnit, maxIdle, maxIdleUnit, clientStatistics, telemetryService); } public <K> PutStreamOperation newPutStreamOperation(K key, byte[] keyBytes, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { return new PutStreamOperation(getCodec(), channelFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, PutStreamOperation.VERSION_PUT, lifespan, lifespanUnit, maxIdle, maxIdleUnit, clientStatistics, telemetryService); } public <K> PutStreamOperation newPutIfAbsentStreamOperation(K key, byte[] keyBytes, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { return new PutStreamOperation(getCodec(), channelFactory, key, keyBytes, cacheNameBytes, clientTopologyRef, flags(), cfg, PutStreamOperation.VERSION_PUT_IF_ABSENT, lifespan, lifespanUnit, maxIdle, maxIdleUnit, clientStatistics, telemetryService); } public AuthMechListOperation newAuthMechListOperation(Channel channel) { return new AuthMechListOperation(getCodec(), clientTopologyRef, cfg, channel, channelFactory); } public AuthOperation newAuthOperation(Channel channel, String saslMechanism, byte[] response) { return new AuthOperation(getCodec(), clientTopologyRef, cfg, channel, channelFactory, saslMechanism, response); } public PrepareTransactionOperation newPrepareTransactionOperation(Xid xid, boolean onePhaseCommit, List<Modification> modifications, boolean recoverable, long timeoutMs) { return new PrepareTransactionOperation(getCodec(), channelFactory, cacheNameBytes, clientTopologyRef, cfg, xid, onePhaseCommit, modifications, recoverable, timeoutMs); } }
18,832
47.916883
252
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/ClearOperation.java
package org.infinispan.client.hotrod.impl.operations; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.telemetry.impl.TelemetryService; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; /** * Corresponds to clear operation as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol specification</a>. * * @author Mircea.Markus@jboss.com * @since 4.1 */ @Immutable public class ClearOperation extends RetryOnFailureOperation<Void> { public ClearOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, TelemetryService telemetryService) { super(CLEAR_REQUEST, CLEAR_RESPONSE, codec, channelFactory, cacheName, clientTopology, flags, cfg, null, telemetryService); } @Override protected void executeOperation(Channel channel) { sendHeaderAndRead(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(null); } }
1,507
35.780488
140
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/operations/AuthMechListOperation.java
package org.infinispan.client.hotrod.impl.operations; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Obtains a list of SASL authentication mechanisms supported by the server * * @author Tristan Tarrant * @since 7.0 */ public class AuthMechListOperation extends NeutralVersionHotRodOperation<List<String>> { private final Channel channel; private int mechCount = -1; private List<String> result; public AuthMechListOperation(Codec codec, AtomicReference<ClientTopology> clientTopology, Configuration cfg, Channel channel, ChannelFactory channelFactory) { super(AUTH_MECH_LIST_REQUEST, AUTH_MECH_LIST_RESPONSE, codec, 0, cfg, DEFAULT_CACHE_NAME_BYTES, clientTopology, channelFactory); this.channel = channel; } @Override public CompletableFuture<List<String>> execute() { if (!channel.isActive()) { throw HOTROD.channelInactive(channel.remoteAddress(), channel.remoteAddress()); } scheduleRead(channel); sendHeader(channel); return this; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (mechCount < 0) { mechCount = ByteBufUtil.readVInt(buf); result = new ArrayList<>(mechCount); decoder.checkpoint(); } while (result.size() < mechCount) { result.add(ByteBufUtil.readString(buf)); decoder.checkpoint(); } complete(result); } }
2,074
33.583333
161
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/query/RemoteQueryBuilder.java
package org.infinispan.client.hotrod.impl.query; import org.infinispan.client.hotrod.impl.InternalRemoteCache; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.protostream.SerializationContext; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.impl.BaseQueryBuilder; import org.infinispan.query.dsl.impl.QueryStringCreator; /** * @author anistor@redhat.com * @since 6.0 */ final class RemoteQueryBuilder extends BaseQueryBuilder { private static final Log log = LogFactory.getLog(RemoteQueryBuilder.class); private final InternalRemoteCache<?, ?> cache; private final SerializationContext serializationContext; RemoteQueryBuilder(RemoteQueryFactory queryFactory, InternalRemoteCache<?, ?> cache, SerializationContext serializationContext, String rootType) { super(queryFactory, rootType); this.cache = cache; this.serializationContext = serializationContext; } @Override public <T> Query<T> build() { QueryStringCreator generator = serializationContext != null ? new RemoteQueryStringCreator(serializationContext) : new QueryStringCreator(); String queryString = accept(generator); if (log.isTraceEnabled()) { log.tracef("Query string : %s", queryString); } // QueryBuilder is deprecated and will not support local mode return new RemoteQuery<>(queryFactory, cache, serializationContext, queryString, generator.getNamedParameters(), getProjectionPaths(), startOffset, maxResults, false); } }
1,599
39
173
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/query/RemoteQueryStringCreator.java
package org.infinispan.client.hotrod.impl.query; import java.time.Instant; import java.util.Date; import org.infinispan.protostream.EnumMarshaller; import org.infinispan.protostream.SerializationContext; import org.infinispan.query.dsl.impl.QueryStringCreator; /** * @author anistor@redhat.com * @since 6.0 */ final class RemoteQueryStringCreator extends QueryStringCreator { private final SerializationContext serializationContext; RemoteQueryStringCreator(SerializationContext serializationContext) { this.serializationContext = serializationContext; } //TODO [anistor] these are only used for remote query with Lucene engine @Override protected <E extends Enum<E>> String renderEnum(E argument) { EnumMarshaller<E> encoder = (EnumMarshaller<E>) serializationContext.getMarshaller(argument.getClass()); return String.valueOf(encoder.encode(argument)); } @Override protected String renderDate(Date argument) { return Long.toString(argument.getTime()); } @Override protected String renderInstant(Instant argument) { return Long.toString(argument.toEpochMilli()); } }
1,148
27.725
110
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/query/RemoteQueryFactory.java
package org.infinispan.client.hotrod.impl.query; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.impl.InternalRemoteCache; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.protostream.SerializationContext; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryBuilder; import org.infinispan.query.dsl.impl.BaseQueryFactory; import org.infinispan.query.remote.client.impl.MarshallerRegistration; import org.infinispan.query.remote.client.impl.QueryRequest; /** * @author anistor@redhat.com * @since 6.0 */ public final class RemoteQueryFactory extends BaseQueryFactory { private final InternalRemoteCache<?, ?> cache; private final SerializationContext serializationContext; public RemoteQueryFactory(InternalRemoteCache<?, ?> cache) { this.cache = cache; Marshaller marshaller = cache.getRemoteCacheContainer().getMarshaller(); // we may or may not use Protobuf if (marshaller instanceof ProtoStreamMarshaller) { serializationContext = ((ProtoStreamMarshaller) marshaller).getSerializationContext(); try { if (!serializationContext.canMarshall(QueryRequest.class)) { MarshallerRegistration.init(serializationContext); } } catch (Exception e) { throw new HotRodClientException("Failed to initialise the Protobuf serialization context", e); } } else { serializationContext = null; } } @Override public <T> Query<T> create(String queryString) { return new RemoteQuery<>(this, cache, serializationContext, queryString); } @Override public QueryBuilder from(Class<?> entityType) { String typeName = serializationContext != null ? serializationContext.getMarshaller(entityType).getTypeName() : entityType.getName(); return new RemoteQueryBuilder(this, cache, serializationContext, typeName); } @Override public QueryBuilder from(String entityType) { if (serializationContext != null) { // just check that the type name is valid serializationContext.getMarshaller(entityType); } return new RemoteQueryBuilder(this, cache, serializationContext, entityType); } }
2,367
37.193548
106
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/query/RemoteQuery.java
package org.infinispan.client.hotrod.impl.query; import static org.infinispan.client.hotrod.impl.Util.await; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.impl.InternalRemoteCache; import org.infinispan.client.hotrod.impl.operations.QueryOperation; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.Closeables; import org.infinispan.protostream.SerializationContext; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.dsl.TotalHitCount; import org.infinispan.query.dsl.impl.BaseQuery; import org.infinispan.query.remote.client.impl.BaseQueryResponse; /** * @author anistor@redhat.com * @since 6.0 */ public final class RemoteQuery<T> extends BaseQuery<T> { private static final Log log = LogFactory.getLog(RemoteQuery.class); private final InternalRemoteCache<?, ?> cache; private final SerializationContext serializationContext; RemoteQuery(QueryFactory queryFactory, InternalRemoteCache<?, ?> cache, SerializationContext serializationContext, String queryString) { super(queryFactory, queryString); this.cache = cache; this.serializationContext = serializationContext; } RemoteQuery(QueryFactory queryFactory, InternalRemoteCache<?, ?> cache, SerializationContext serializationContext, String queryString, Map<String, Object> namedParameters, String[] projection, long startOffset, int maxResults, boolean local) { super(queryFactory, queryString, namedParameters, projection, startOffset, maxResults, local); this.cache = cache; this.serializationContext = serializationContext; } @Override public void resetQuery() { } @Override public List<T> list() { BaseQueryResponse<T> response = executeRemotely(false); try { return response.extractResults(serializationContext); } catch (IOException e) { throw new HotRodClientException(e); } } @Override public QueryResult<T> execute() { BaseQueryResponse<T> response = executeRemotely(true); return new QueryResult<>() { @Override public TotalHitCount count() { return new TotalHitCount(response.hitCount(), response.hitCountExact()); } @Override public List<T> list() { try { return response.extractResults(serializationContext); } catch (IOException e) { throw new HotRodClientException(e); } } }; } @Override public int executeStatement() { BaseQueryResponse<?> response = executeRemotely(false); return response.hitCount(); } @Override public CloseableIterator<T> iterator() { if (maxResults == -1 && startOffset == 0) { log.warnPerfRemoteIterationWithoutPagination(queryString); } return Closeables.iterator(list().iterator()); } @Override public int getResultSize() { BaseQueryResponse<?> response = executeRemotely(true); return response.hitCount(); } private BaseQueryResponse<T> executeRemotely(boolean withHitCount) { validateNamedParameters(); QueryOperation op = cache.getOperationsFactory().newQueryOperation(this, cache.getDataFormat(), withHitCount); return (BaseQueryResponse<T>) (timeout != -1 ? await(op.execute(), TimeUnit.NANOSECONDS.toMillis(timeout)) : await(op.execute())); } /** * Get the protobuf SerializationContext or {@code null} if we are not using protobuf. */ public SerializationContext getSerializationContext() { return serializationContext; } public RemoteCache<?, ?> getCache() { return cache; } @Override public String toString() { return "RemoteQuery{" + "queryString=" + queryString + ", namedParameters=" + namedParameters + ", startOffset=" + startOffset + ", maxResults=" + maxResults + ", timeout=" + timeout + '}'; } }
4,406
32.135338
143
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/tcp/RoundRobinBalancingStrategy.java
package org.infinispan.client.hotrod.impl.transport.tcp; import java.net.SocketAddress; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; /** * Round-robin implementation for {@link org.infinispan.client.hotrod.FailoverRequestBalancingStrategy}. * * @author Mircea.Markus@jboss.com * @since 4.1 */ public class RoundRobinBalancingStrategy implements FailoverRequestBalancingStrategy { private static final Log log = LogFactory.getLog(RoundRobinBalancingStrategy.class); private int index; private SocketAddress[] servers; @Override public void setServers(Collection<SocketAddress> servers) { this.servers = servers.toArray(new SocketAddress[servers.size()]); // Always start with a random server after a topology update index = ThreadLocalRandom.current().nextInt(this.servers.length); if (log.isTraceEnabled()) { log.tracef("New server list is: " + Arrays.toString(this.servers)); } } /** * @param failedServers Servers that should not be returned (if any other are available) */ @Override public SocketAddress nextServer(Set<SocketAddress> failedServers) { for (int i = 0;; ++i) { SocketAddress server = getServerByIndex(index++); // don't allow index to overflow and have a negative value if (index >= servers.length) index = 0; if (failedServers == null || !failedServers.contains(server) || i >= failedServers.size()) { if (log.isTraceEnabled()) { if (failedServers == null) log.tracef("Found server %s", server); else log.tracef("Found server %s, with failed servers %s", server, failedServers.toString()); } return server; } } } private SocketAddress getServerByIndex(int pos) { return servers[pos]; } public SocketAddress[] getServers() { return servers; } }
2,204
30.956522
106
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/IOURingNativeTransport.java
package org.infinispan.client.hotrod.impl.transport.netty; import java.util.concurrent.ExecutorService; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.SocketChannel; import io.netty.incubator.channel.uring.IOUringDatagramChannel; import io.netty.incubator.channel.uring.IOUringEventLoopGroup; import io.netty.incubator.channel.uring.IOUringSocketChannel; /** * @since 14.0 **/ public class IOURingNativeTransport { public static Class<? extends SocketChannel> socketChannelClass() { return IOUringSocketChannel.class; } public static EventLoopGroup createEventLoopGroup(int maxExecutors, ExecutorService executorService) { return new IOUringEventLoopGroup(maxExecutors, executorService); } public static Class<? extends DatagramChannel> datagramChannelClass() { return IOUringDatagramChannel.class; } }
919
30.724138
105
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/ChannelInboundHandlerDefaults.java
package org.infinispan.client.hotrod.impl.transport.netty; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandler; /** * This is effectively the same as {@link io.netty.channel.ChannelInboundHandlerAdapter} but allows * to be inherited in a class with another superclass. */ public interface ChannelInboundHandlerDefaults extends ChannelInboundHandler { @Override default void channelRegistered(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelRegistered(); } @Override default void channelUnregistered(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelUnregistered(); } @Override default void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelActive(); } @Override default void channelInactive(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelInactive(); } @Override default void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.fireChannelRead(msg); } @Override default void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelReadComplete(); } @Override default void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { ctx.fireUserEventTriggered(evt); } @Override default void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelWritabilityChanged(); } @Override default void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.fireExceptionCaught(cause); } @Override default void handlerAdded(ChannelHandlerContext ctx) throws Exception { // noop } @Override default void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // noop } }
1,872
27.378788
99
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/HeaderDecoder.java
package org.infinispan.client.hotrod.impl.transport.netty; import static org.infinispan.client.hotrod.impl.protocol.HotRodConstants.CACHE_ENTRY_CREATED_EVENT_RESPONSE; import static org.infinispan.client.hotrod.impl.protocol.HotRodConstants.CACHE_ENTRY_EXPIRED_EVENT_RESPONSE; import static org.infinispan.client.hotrod.impl.protocol.HotRodConstants.CACHE_ENTRY_MODIFIED_EVENT_RESPONSE; import static org.infinispan.client.hotrod.impl.protocol.HotRodConstants.CACHE_ENTRY_REMOVED_EVENT_RESPONSE; import static org.infinispan.client.hotrod.impl.protocol.HotRodConstants.COUNTER_EVENT_RESPONSE; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.counter.impl.HotRodCounterEvent; import org.infinispan.client.hotrod.event.impl.AbstractClientEvent; import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.client.hotrod.exceptions.TransportException; import org.infinispan.client.hotrod.impl.operations.AddClientListenerOperation; import org.infinispan.client.hotrod.impl.operations.HotRodOperation; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.util.Util; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.timeout.IdleStateEvent; import io.netty.util.Signal; public class HeaderDecoder extends HintedReplayingDecoder<HeaderDecoder.State> { private static final Log log = LogFactory.getLog(HeaderDecoder.class); // used for HeaderOrEventDecoder, too, as the function is similar public static final String NAME = "header-decoder"; private final ChannelFactory channelFactory; private final Configuration configuration; private final ClientListenerNotifier listenerNotifier; // operations may be registered in any thread, and are removed in event loop thread private final ConcurrentMap<Long, HotRodOperation<?>> incomplete = new ConcurrentHashMap<>(); private final List<byte[]> listeners = new ArrayList<>(); private volatile boolean closing; private HotRodOperation<?> operation; private short status; private short receivedOpCode; public HeaderDecoder(ChannelFactory channelFactory, Configuration configuration, ClientListenerNotifier listenerNotifier) { super(State.READ_MESSAGE_ID); this.channelFactory = channelFactory; this.configuration = configuration; this.listenerNotifier = listenerNotifier; } @Override public boolean isSharable() { return false; } public void registerOperation(Channel channel, HotRodOperation<?> operation) { if (log.isTraceEnabled()) { log.tracef("Registering operation %s(%08X) with id %d on %s", operation, System.identityHashCode(operation), operation.header().messageId(), channel); } if (closing) { throw HOTROD.noMoreOperationsAllowed(); } HotRodOperation<?> prev = incomplete.put(operation.header().messageId(), operation); assert prev == null : "Already registered: " + prev + ", new: " + operation; operation.scheduleTimeout(channel); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { Codec codec = operation == null ? channelFactory.getNegotiatedCodec() : operation.getCodec(); try { switch (state()) { case READ_MESSAGE_ID: long messageId = codec.readMessageId(in); receivedOpCode = codec.readOpCode(in); switch (receivedOpCode) { case CACHE_ENTRY_CREATED_EVENT_RESPONSE: case CACHE_ENTRY_MODIFIED_EVENT_RESPONSE: case CACHE_ENTRY_REMOVED_EVENT_RESPONSE: case CACHE_ENTRY_EXPIRED_EVENT_RESPONSE: if (codec.allowOperationsAndEvents()) { operation = messageId == 0 ? null : incomplete.get(messageId); } else { operation = null; messageId = 0; } // The operation may be null even if the messageId was set: the server does not really wait // until all events are sent, only until these are queued. In such case the operation may // complete earlier. if (operation != null && !(operation instanceof AddClientListenerOperation)) { throw HOTROD.operationIsNotAddClientListener(messageId, operation.toString()); } else if (log.isTraceEnabled()) { log.tracef("Received event for request %d", messageId, operation); } checkpoint(State.READ_CACHE_EVENT); // the loop in HintedReplayingDecoder will call decode again return; case COUNTER_EVENT_RESPONSE: checkpoint(State.READ_COUNTER_EVENT); // the loop in HintedReplayingDecoder will call decode again return; } if (messageId == 0) { // let's read the header even at this stage; it should throw an error and the other throw statement // won't be reached codec.readHeader(in, receivedOpCode, null, channelFactory, ctx.channel().remoteAddress()); throw new IllegalStateException("Should be never reached"); } // we can remove the operation at this point since we'll read no more in this state operation = incomplete.remove(messageId); if (operation == null) { throw HOTROD.unknownMessageId(messageId); } if (log.isTraceEnabled()) { log.tracef("Received response for request %d, %s", messageId, operation); } checkpoint(State.READ_HEADER); // fall through case READ_HEADER: if (log.isTraceEnabled()) { log.tracef("Decoding header for message %s", HotRodConstants.Names.of(receivedOpCode)); } status = codec.readHeader(in, receivedOpCode, operation.header(), channelFactory, ctx.channel().remoteAddress()); checkpoint(State.READ_PAYLOAD); // fall through case READ_PAYLOAD: if (log.isTraceEnabled()) { log.tracef("Decoding payload for message %s", HotRodConstants.Names.of(receivedOpCode)); } operation.acceptResponse(in, status, this); checkpoint(State.READ_MESSAGE_ID); break; case READ_CACHE_EVENT: if (log.isTraceEnabled()) { log.tracef("Decoding cache event %s", HotRodConstants.Names.of(receivedOpCode)); } AbstractClientEvent cacheEvent; try { cacheEvent = codec.readCacheEvent(in, listenerNotifier::getCacheDataFormat, receivedOpCode, configuration.getClassAllowList(), ctx.channel().remoteAddress()); } catch (Signal signal) { throw signal; } catch (Throwable t) { log.unableToReadEventFromServer(t, ctx.channel().remoteAddress()); throw t; } if (operation != null) { ((AddClientListenerOperation) operation).postponeTimeout(ctx.channel()); } invokeEvent(cacheEvent.getListenerId(), cacheEvent); checkpoint(State.READ_MESSAGE_ID); break; case READ_COUNTER_EVENT: if (log.isTraceEnabled()) { log.tracef("Decoding counter event %s", HotRodConstants.Names.of(receivedOpCode)); } HotRodCounterEvent counterEvent; try { counterEvent = codec.readCounterEvent(in); } catch (Signal signal) { throw signal; } catch (Throwable t) { HOTROD.unableToReadEventFromServer(t, ctx.channel().remoteAddress()); throw t; } invokeEvent(counterEvent.getListenerId(), counterEvent); checkpoint(State.READ_MESSAGE_ID); break; } } catch (Exception e) { // If this is server error make sure to restart the state of decoder checkpoint(State.READ_MESSAGE_ID); throw e; } } private void invokeEvent(byte[] listenerId, Object cacheEvent) { try { listenerNotifier.invokeEvent(listenerId, cacheEvent); } catch (Exception e) { HOTROD.unexpectedErrorConsumingEvent(cacheEvent, e); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (operation != null) { operation.exceptionCaught(ctx.channel(), cause); } else { TransportException transportException = log.errorFromUnknownOperation(ctx.channel(), cause, ctx.channel().remoteAddress()); for (HotRodOperation<?> op : incomplete.values()) { try { op.exceptionCaught(ctx.channel(), transportException); } catch (Throwable t) { HOTROD.errorf(t, "Failed to complete %s", op); } } if (log.isTraceEnabled()) { log.tracef(cause, "Requesting %s close due to exception", ctx.channel()); } ctx.close(); } } @Override public void channelInactive(ChannelHandlerContext ctx) { for (HotRodOperation<?> op : incomplete.values()) { try { op.channelInactive(ctx.channel()); } catch (Throwable t) { HOTROD.errorf(t, "Failed to complete %s", op); } } failoverClientListeners(); } public void failoverClientListeners() { for (byte[] listenerId : listeners) { listenerNotifier.failoverClientListener(listenerId); } } public CompletableFuture<Void> allCompleteFuture() { return CompletableFuture.allOf(incomplete.values().toArray(new CompletableFuture[0])); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof ChannelPoolCloseEvent) { closing = true; allCompleteFuture().whenComplete((nil, throwable) -> ctx.channel().close()); } else if (evt instanceof IdleStateEvent) { // If we have incomplete operations this channel is not idle! if (!incomplete.isEmpty()) { return; } } ctx.fireUserEventTriggered(evt); } /** * {@inheritDoc} * * Checkpoint is exposed for implementations of {@link HotRodOperation} */ @Override public void checkpoint() { super.checkpoint(); } public int registeredOperations() { return incomplete.size(); } public void addListener(byte[] listenerId) { if (log.isTraceEnabled()) { log.tracef("Decoder %08X adding listener %s", hashCode(), Util.printArray(listenerId)); } listeners.add(listenerId); } // must be called from event loop thread! public void removeListener(byte[] listenerId) { boolean removed = listeners.removeIf(id -> Arrays.equals(id, listenerId)); if (log.isTraceEnabled()) { log.tracef("Decoder %08X removed? %s listener %s", hashCode(), Boolean.toString(removed), Util.printArray(listenerId)); } } enum State { READ_MESSAGE_ID, READ_HEADER, READ_PAYLOAD, READ_CACHE_EVENT, READ_COUNTER_EVENT, } }
12,275
41.773519
132
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/InitialPingHandler.java
package org.infinispan.client.hotrod.impl.transport.netty; import org.infinispan.client.hotrod.impl.operations.PingOperation; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; public class InitialPingHandler extends ActivationHandler { private static final Log log = LogFactory.getLog(InitialPingHandler.class); static final String NAME = "initial-ping-handler"; private final PingOperation ping; public InitialPingHandler(PingOperation ping) { this.ping = ping; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); if (log.isTraceEnabled()) { log.tracef("Activating channel %s", channel); } ChannelRecord channelRecord = ChannelRecord.of(channel); ping.invoke(channel); ping.whenComplete((result, throwable) -> { if (log.isTraceEnabled()) { log.tracef("Initial ping completed with result %s/%s", result, throwable); } if (throwable != null) { channelRecord.completeExceptionally(throwable); } else { channelRecord.complete(channel); } }); ctx.pipeline().remove(this); } }
1,347
31.095238
86
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/IdleStateHandlerProvider.java
package org.infinispan.client.hotrod.impl.transport.netty; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.timeout.IdleStateEvent; @Sharable public class IdleStateHandlerProvider extends ChannelInboundHandlerAdapter { private final int minIdle; private final ChannelPool channelPool; private final static Log log = LogFactory.getLog(IdleStateHandlerProvider.class); static final String NAME = "idle-state-handler-provider"; public IdleStateHandlerProvider(int minIdle, ChannelPool channelPool) { this.minIdle = minIdle; this.channelPool = channelPool; } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof IdleStateEvent) { if (channelPool.getIdle() > minIdle && ChannelRecord.of(ctx.channel()).isIdle()) { log.debugf("Closing idle channel %s", ctx.channel()); ctx.close(); } } else { ctx.fireUserEventTriggered(evt); } } }
1,218
32.861111
91
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/ChannelPoolCloseEvent.java
package org.infinispan.client.hotrod.impl.transport.netty; public class ChannelPoolCloseEvent { public static final ChannelPoolCloseEvent INSTANCE = new ChannelPoolCloseEvent(); private ChannelPoolCloseEvent() {} }
223
27
84
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/ChannelOutboundHandlerDefaults.java
package org.infinispan.client.hotrod.impl.transport.netty; import java.net.SocketAddress; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandler; import io.netty.channel.ChannelPromise; /** * This is effectively the same as {@link io.netty.channel.ChannelOutboundHandlerAdapter} but allows * to be inherited in a class with another superclass. */ public interface ChannelOutboundHandlerDefaults extends ChannelOutboundHandler { @Override default void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception { ctx.bind(localAddress, promise); } @Override default void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception { ctx.connect(remoteAddress, localAddress, promise); } @Override default void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { ctx.disconnect(promise); } @Override default void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { ctx.close(promise); } @Override default void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { ctx.deregister(promise); } @Override default void read(ChannelHandlerContext ctx) throws Exception { ctx.read(); } @Override default void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { ctx.write(msg, promise); } @Override default void flush(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override default void handlerAdded(ChannelHandlerContext ctx) throws Exception { // noop } @Override default void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // noop } @Override default void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.fireExceptionCaught(cause); } }
2,043
28.623188
150
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/HintedReplayingDecoder.java
package org.infinispan.client.hotrod.impl.transport.netty; import java.util.Collections; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.DecoderException; import io.netty.util.Signal; /** * Copy-paste of {@link io.netty.handler.codec.ReplayingDecoder} which is hinted to not attempt decoding unless enough * bytes are read. * * The decoder does not expect pass different message up the pipeline, this is a terminal read operation. */ public abstract class HintedReplayingDecoder<S> extends ByteToMessageDecoder { static final Signal REPLAY = Signal.valueOf(HintedReplayingDecoder.class.getName() + ".REPLAY"); // We don't expect decode() to use the out param private static final List<Object> NO_WRITE_LIST = Collections.emptyList(); private final HintingByteBuf replayable = new HintingByteBuf(this); private S state; private int checkpoint = -1; private int requiredReadableBytes = 0; /** * Creates a new instance with no initial state (i.e: {@code null}). */ protected HintedReplayingDecoder() { this(null); } /** * Creates a new instance with the specified initial state. */ protected HintedReplayingDecoder(S initialState) { state = initialState; } /** * Stores the internal cumulative buffer's reader position. */ protected void checkpoint() { checkpoint = internalBuffer().readerIndex(); } /** * Stores the internal cumulative buffer's reader position and updates * the current decoder state. */ protected void checkpoint(S state) { checkpoint(); state(state); } /** * Returns the current state of this decoder. * @return the current state of this decoder */ protected S state() { return state; } /** * Sets the current state of this decoder. * @return the old state of this decoder */ protected S state(S newState) { S oldState = state; state = newState; return oldState; } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { replayable.terminate(); super.channelInactive(ctx); } @Override protected void callDecode(ChannelHandlerContext ctx, ByteBuf in, List<Object> xxx) { if (in.readableBytes() < requiredReadableBytes) { // noop, wait for further reads return; } replayable.setCumulation(in); try { while (in.isReadable() && !ctx.isRemoved() && ctx.channel().isActive()) { checkpoint = in.readerIndex(); try { decode(ctx, replayable, NO_WRITE_LIST); requiredReadableBytes = 0; // TODO: unset cumulation } catch (Signal replay) { replay.expect(REPLAY); // Check if this handler was removed before continuing the loop. // If it was removed, it is not safe to continue to operate on the buffer. // // See https://github.com/netty/netty/issues/1664 if (ctx.isRemoved()) { break; } // Return to the checkpoint (or oldPosition) and retry. int checkpoint = this.checkpoint; if (checkpoint >= 0) { in.readerIndex(checkpoint); } else { // Called by cleanup() - no need to maintain the readerIndex // anymore because the buffer has been released already. } break; } catch (Throwable t) { requiredReadableBytes = 0; throw t; } } } catch (DecoderException e) { throw e; } catch (Throwable cause) { throw new DecoderException(cause); } } void requireWriterIndex(int index) { // TODO: setCumulator to composite if the number of bytes is too high requiredReadableBytes = index - checkpoint; } }
4,116
29.723881
118
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/AuthHandler.java
package org.infinispan.client.hotrod.impl.transport.netty; import static io.netty.util.internal.EmptyArrays.EMPTY_BYTES; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.function.Function; import javax.security.auth.Subject; import javax.security.sasl.Sasl; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslException; import org.infinispan.client.hotrod.configuration.AuthenticationConfiguration; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; class AuthHandler extends ActivationHandler { private static final Log log = LogFactory.getLog(AuthHandler.class); private static final String AUTH_INT = "auth-int"; private static final String AUTH_CONF = "auth-conf"; static final String NAME = "auth-handler"; private final AuthenticationConfiguration authentication; private final SaslClient saslClient; private final OperationsFactory operationsFactory; AuthHandler(AuthenticationConfiguration authentication, SaslClient saslClient, OperationsFactory operationsFactory) { this.authentication = authentication; this.saslClient = saslClient; this.operationsFactory = operationsFactory; } @Override public void channelActive(ChannelHandlerContext ctx) { Channel channel = ctx.channel(); operationsFactory.newAuthMechListOperation(channel).execute().thenCompose(serverMechs -> { if (!serverMechs.contains(authentication.saslMechanism())) { throw HOTROD.unsupportedMech(authentication.saslMechanism(), serverMechs); } if (log.isTraceEnabled()) { log.tracef("Authenticating using mech: %s", authentication.saslMechanism()); } byte response[]; if (saslClient.hasInitialResponse()) { try { response = evaluateChallenge(saslClient, EMPTY_BYTES, authentication.clientSubject()); } catch (SaslException e) { throw new CompletionException(e); } } else { response = EMPTY_BYTES; } return operationsFactory.newAuthOperation(channel, authentication.saslMechanism(), response).execute(); }).thenCompose(new ChallengeEvaluator(channel, saslClient)).thenRun(() -> { String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP); if (qop != null && (qop.equalsIgnoreCase(AUTH_INT) || qop.equalsIgnoreCase(AUTH_CONF))) { channel.pipeline().addFirst( new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4), new SaslDecoderEncoder(saslClient)); } else { try { saslClient.dispose(); } catch (SaslException e) { channel.pipeline().fireExceptionCaught(e); } } channel.pipeline().remove(this); channel.pipeline().fireUserEventTriggered(ActivationHandler.ACTIVATION_EVENT); }).exceptionally(throwable -> { while (throwable instanceof CompletionException && throwable.getCause() != null) { throwable = throwable.getCause(); } channel.pipeline().fireExceptionCaught(throwable); return null; }); } private byte[] evaluateChallenge(final SaslClient saslClient, final byte[] challenge, Subject clientSubject) throws SaslException { if(clientSubject != null) { try { return Subject.doAs(clientSubject, (PrivilegedExceptionAction<byte[]>) () -> saslClient.evaluateChallenge(challenge)); } catch (PrivilegedActionException e) { Throwable cause = e.getCause(); if (cause instanceof SaslException) { throw (SaslException)cause; } else { throw new RuntimeException(cause); } } } else { return saslClient.evaluateChallenge(challenge); } } private class ChallengeEvaluator implements Function<byte[], CompletableFuture<byte[]>> { private final Channel channel; private final SaslClient saslClient; private ChallengeEvaluator(Channel channel, SaslClient saslClient) { this.channel = channel; this.saslClient = saslClient; } @Override public CompletableFuture<byte[]> apply(byte[] challenge) { if (!saslClient.isComplete() && challenge != null) { byte[] response; try { response = evaluateChallenge(saslClient, challenge, authentication.clientSubject()); } catch (SaslException e) { throw new CompletionException(e); } if (response != null) { return operationsFactory.newAuthOperation(channel, authentication.saslMechanism(), response) .execute().thenCompose(this); } } return CompletableFuture.completedFuture(null); } } }
5,425
38.897059
134
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/SslHandshakeExceptionHandler.java
package org.infinispan.client.hotrod.impl.transport.netty; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.ssl.SslHandshakeCompletionEvent; @Sharable public class SslHandshakeExceptionHandler extends ChannelInboundHandlerAdapter { public static final SslHandshakeExceptionHandler INSTANCE = new SslHandshakeExceptionHandler(); @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { if (evt != SslHandshakeCompletionEvent.SUCCESS) { SslHandshakeCompletionEvent sslEvent = (SslHandshakeCompletionEvent) evt; ctx.fireExceptionCaught(sslEvent.cause()); } ctx.pipeline().remove(this); } else { ctx.fireUserEventTriggered(evt); } } }
941
36.68
98
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/HintingByteBuf.java
package org.infinispan.client.hotrod.impl.transport.netty; import static org.infinispan.client.hotrod.impl.transport.netty.HintedReplayingDecoder.REPLAY; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import java.nio.charset.Charset; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.SwappedByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.ByteProcessor; import io.netty.util.internal.StringUtil; /** * Copy-paste of {@link io.netty.handler.codec.ReplayingDecoderByteBuf} which hints {@link HintedReplayingDecoder} * to not try decoding until requested bytes are received. */ public class HintingByteBuf extends ByteBuf { private final HintedReplayingDecoder<?> decoder; private ByteBuf buffer; private boolean terminated; private SwappedByteBuf swapped; HintingByteBuf(HintedReplayingDecoder<?> decoder) { this.decoder = decoder; } void setCumulation(ByteBuf buffer) { this.buffer = buffer; } void terminate() { terminated = true; } @Override public int capacity() { if (terminated) { return buffer.capacity(); } else { return Integer.MAX_VALUE; } } @Override public ByteBuf capacity(int newCapacity) { throw reject(); } @Override public int maxCapacity() { return capacity(); } @Override public ByteBufAllocator alloc() { return buffer.alloc(); } @Override public boolean isReadOnly() { return false; } @SuppressWarnings("deprecation") @Override public ByteBuf asReadOnly() { return Unpooled.unmodifiableBuffer(this); } @Override public boolean isDirect() { return buffer.isDirect(); } @Override public boolean hasArray() { return false; } @Override public byte[] array() { throw new UnsupportedOperationException(); } @Override public int arrayOffset() { throw new UnsupportedOperationException(); } @Override public boolean hasMemoryAddress() { return false; } @Override public long memoryAddress() { throw new UnsupportedOperationException(); } @Override public ByteBuf clear() { throw reject(); } @Override public boolean equals(Object obj) { return this == obj; } @Override public int compareTo(ByteBuf buffer) { throw reject(); } @Override public ByteBuf copy() { throw reject(); } @Override public ByteBuf copy(int index, int length) { checkIndex(index, length); return buffer.copy(index, length); } @Override public ByteBuf discardReadBytes() { throw reject(); } @Override public ByteBuf ensureWritable(int writableBytes) { throw reject(); } @Override public int ensureWritable(int minWritableBytes, boolean force) { throw reject(); } @Override public ByteBuf duplicate() { throw reject(); } @Override public ByteBuf retainedDuplicate() { throw reject(); } @Override public boolean getBoolean(int index) { checkIndex(index, 1); return buffer.getBoolean(index); } @Override public byte getByte(int index) { checkIndex(index, 1); return buffer.getByte(index); } @Override public short getUnsignedByte(int index) { checkIndex(index, 1); return buffer.getUnsignedByte(index); } @Override public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { checkIndex(index, length); buffer.getBytes(index, dst, dstIndex, length); return this; } @Override public ByteBuf getBytes(int index, byte[] dst) { checkIndex(index, dst.length); buffer.getBytes(index, dst); return this; } @Override public ByteBuf getBytes(int index, ByteBuffer dst) { throw reject(); } @Override public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { checkIndex(index, length); buffer.getBytes(index, dst, dstIndex, length); return this; } @Override public ByteBuf getBytes(int index, ByteBuf dst, int length) { throw reject(); } @Override public ByteBuf getBytes(int index, ByteBuf dst) { throw reject(); } @Override public int getBytes(int index, GatheringByteChannel out, int length) { throw reject(); } @Override public int getBytes(int index, FileChannel out, long position, int length) { throw reject(); } @Override public ByteBuf getBytes(int index, OutputStream out, int length) { throw reject(); } @Override public int getInt(int index) { checkIndex(index, 4); return buffer.getInt(index); } @Override public int getIntLE(int index) { checkIndex(index, 4); return buffer.getIntLE(index); } @Override public long getUnsignedInt(int index) { checkIndex(index, 4); return buffer.getUnsignedInt(index); } @Override public long getUnsignedIntLE(int index) { checkIndex(index, 4); return buffer.getUnsignedIntLE(index); } @Override public long getLong(int index) { checkIndex(index, 8); return buffer.getLong(index); } @Override public long getLongLE(int index) { checkIndex(index, 8); return buffer.getLongLE(index); } @Override public int getMedium(int index) { checkIndex(index, 3); return buffer.getMedium(index); } @Override public int getMediumLE(int index) { checkIndex(index, 3); return buffer.getMediumLE(index); } @Override public int getUnsignedMedium(int index) { checkIndex(index, 3); return buffer.getUnsignedMedium(index); } @Override public int getUnsignedMediumLE(int index) { checkIndex(index, 3); return buffer.getUnsignedMediumLE(index); } @Override public short getShort(int index) { checkIndex(index, 2); return buffer.getShort(index); } @Override public short getShortLE(int index) { checkIndex(index, 2); return buffer.getShortLE(index); } @Override public int getUnsignedShort(int index) { checkIndex(index, 2); return buffer.getUnsignedShort(index); } @Override public int getUnsignedShortLE(int index) { checkIndex(index, 2); return buffer.getUnsignedShortLE(index); } @Override public char getChar(int index) { checkIndex(index, 2); return buffer.getChar(index); } @Override public float getFloat(int index) { checkIndex(index, 4); return buffer.getFloat(index); } @Override public double getDouble(int index) { checkIndex(index, 8); return buffer.getDouble(index); } @Override public CharSequence getCharSequence(int index, int length, Charset charset) { checkIndex(index, length); return buffer.getCharSequence(index, length, charset); } @Override public int hashCode() { throw reject(); } @Override public int indexOf(int fromIndex, int toIndex, byte value) { if (fromIndex == toIndex) { return -1; } if (Math.max(fromIndex, toIndex) > buffer.writerIndex()) { decoder.requireWriterIndex(Math.max(fromIndex, toIndex)); throw REPLAY; } return buffer.indexOf(fromIndex, toIndex, value); } @Override public int bytesBefore(byte value) { int bytes = buffer.bytesBefore(value); if (bytes < 0) { throw REPLAY; } return bytes; } @Override public int bytesBefore(int length, byte value) { return bytesBefore(buffer.readerIndex(), length, value); } @Override public int bytesBefore(int index, int length, byte value) { final int writerIndex = buffer.writerIndex(); if (index >= writerIndex) { throw REPLAY; } if (index <= writerIndex - length) { return buffer.bytesBefore(index, length, value); } int res = buffer.bytesBefore(index, writerIndex - index, value); if (res < 0) { throw REPLAY; } else { return res; } } @Override public int forEachByte(ByteProcessor processor) { int ret = buffer.forEachByte(processor); if (ret < 0) { throw REPLAY; } else { return ret; } } @Override public int forEachByte(int index, int length, ByteProcessor processor) { final int writerIndex = buffer.writerIndex(); if (index >= writerIndex) { decoder.requireWriterIndex(index); throw REPLAY; } if (index <= writerIndex - length) { return buffer.forEachByte(index, length, processor); } int ret = buffer.forEachByte(index, writerIndex - index, processor); if (ret < 0) { throw REPLAY; } else { return ret; } } @Override public int forEachByteDesc(ByteProcessor processor) { if (terminated) { return buffer.forEachByteDesc(processor); } else { throw reject(); } } @Override public int forEachByteDesc(int index, int length, ByteProcessor processor) { if (index + length > buffer.writerIndex()) { decoder.requireWriterIndex(index + length); throw REPLAY; } return buffer.forEachByteDesc(index, length, processor); } @Override public ByteBuf markReaderIndex() { buffer.markReaderIndex(); return this; } @Override public ByteBuf markWriterIndex() { throw reject(); } @Override public ByteOrder order() { return buffer.order(); } @Override public ByteBuf order(ByteOrder endianness) { if (endianness == null) { throw new NullPointerException("endianness"); } if (endianness == order()) { return this; } SwappedByteBuf swapped = this.swapped; if (swapped == null) { this.swapped = swapped = new SwappedByteBuf(this); } return swapped; } @Override public boolean isReadable() { return buffer.isReadable(); // see readableBytes(); } @Override public boolean isReadable(int size) { return buffer.isReadable(size); // see readableBytes(); } @Override public int readableBytes() { // Contrary to ReplayingDecoderByteBuf we will provide the correct number. // If someone reads past this number we'll throw the Signal as usual, but we're not fooling anyone. // This is useful when injecting another handler below the decoder (as GetStreamOperation does), // as we can hand over the buffered bytes to be consumed immediately. return buffer.readableBytes(); } @Override public boolean readBoolean() { checkReadableBytes(1); return buffer.readBoolean(); } @Override public byte readByte() { checkReadableBytes(1); return buffer.readByte(); } @Override public short readUnsignedByte() { checkReadableBytes(1); return buffer.readUnsignedByte(); } @Override public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { checkReadableBytes(length); buffer.readBytes(dst, dstIndex, length); return this; } @Override public ByteBuf readBytes(byte[] dst) { checkReadableBytes(dst.length); buffer.readBytes(dst); return this; } @Override public ByteBuf readBytes(ByteBuffer dst) { throw reject(); } @Override public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { checkReadableBytes(length); buffer.readBytes(dst, dstIndex, length); return this; } @Override public ByteBuf readBytes(ByteBuf dst, int length) { throw reject(); } @Override public ByteBuf readBytes(ByteBuf dst) { checkReadableBytes(dst.writableBytes()); buffer.readBytes(dst); return this; } @Override public int readBytes(GatheringByteChannel out, int length) { throw reject(); } @Override public int readBytes(FileChannel out, long position, int length) { throw reject(); } @Override public ByteBuf readBytes(int length) { checkReadableBytes(length); return buffer.readBytes(length); } @Override public ByteBuf readSlice(int length) { checkReadableBytes(length); return buffer.readSlice(length); } @Override public ByteBuf readRetainedSlice(int length) { checkReadableBytes(length); return buffer.readRetainedSlice(length); } @Override public ByteBuf readBytes(OutputStream out, int length) { throw reject(); } @Override public int readerIndex() { return buffer.readerIndex(); } @Override public ByteBuf readerIndex(int readerIndex) { buffer.readerIndex(readerIndex); return this; } @Override public int readInt() { checkReadableBytes(4); return buffer.readInt(); } @Override public int readIntLE() { checkReadableBytes(4); return buffer.readIntLE(); } @Override public long readUnsignedInt() { checkReadableBytes(4); return buffer.readUnsignedInt(); } @Override public long readUnsignedIntLE() { checkReadableBytes(4); return buffer.readUnsignedIntLE(); } @Override public long readLong() { checkReadableBytes(8); return buffer.readLong(); } @Override public long readLongLE() { checkReadableBytes(8); return buffer.readLongLE(); } @Override public int readMedium() { checkReadableBytes(3); return buffer.readMedium(); } @Override public int readMediumLE() { checkReadableBytes(3); return buffer.readMediumLE(); } @Override public int readUnsignedMedium() { checkReadableBytes(3); return buffer.readUnsignedMedium(); } @Override public int readUnsignedMediumLE() { checkReadableBytes(3); return buffer.readUnsignedMediumLE(); } @Override public short readShort() { checkReadableBytes(2); return buffer.readShort(); } @Override public short readShortLE() { checkReadableBytes(2); return buffer.readShortLE(); } @Override public int readUnsignedShort() { checkReadableBytes(2); return buffer.readUnsignedShort(); } @Override public int readUnsignedShortLE() { checkReadableBytes(2); return buffer.readUnsignedShortLE(); } @Override public char readChar() { checkReadableBytes(2); return buffer.readChar(); } @Override public float readFloat() { checkReadableBytes(4); return buffer.readFloat(); } @Override public double readDouble() { checkReadableBytes(8); return buffer.readDouble(); } @Override public CharSequence readCharSequence(int length, Charset charset) { checkReadableBytes(length); return buffer.readCharSequence(length, charset); } @Override public ByteBuf resetReaderIndex() { buffer.resetReaderIndex(); return this; } @Override public ByteBuf resetWriterIndex() { throw reject(); } @Override public ByteBuf setBoolean(int index, boolean value) { throw reject(); } @Override public ByteBuf setByte(int index, int value) { throw reject(); } @Override public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { throw reject(); } @Override public ByteBuf setBytes(int index, byte[] src) { throw reject(); } @Override public ByteBuf setBytes(int index, ByteBuffer src) { throw reject(); } @Override public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { throw reject(); } @Override public ByteBuf setBytes(int index, ByteBuf src, int length) { throw reject(); } @Override public ByteBuf setBytes(int index, ByteBuf src) { throw reject(); } @Override public int setBytes(int index, InputStream in, int length) { throw reject(); } @Override public ByteBuf setZero(int index, int length) { throw reject(); } @Override public int setBytes(int index, ScatteringByteChannel in, int length) { throw reject(); } @Override public int setBytes(int index, FileChannel in, long position, int length) { throw reject(); } @Override public ByteBuf setIndex(int readerIndex, int writerIndex) { throw reject(); } @Override public ByteBuf setInt(int index, int value) { throw reject(); } @Override public ByteBuf setIntLE(int index, int value) { throw reject(); } @Override public ByteBuf setLong(int index, long value) { throw reject(); } @Override public ByteBuf setLongLE(int index, long value) { throw reject(); } @Override public ByteBuf setMedium(int index, int value) { throw reject(); } @Override public ByteBuf setMediumLE(int index, int value) { throw reject(); } @Override public ByteBuf setShort(int index, int value) { throw reject(); } @Override public ByteBuf setShortLE(int index, int value) { throw reject(); } @Override public ByteBuf setChar(int index, int value) { throw reject(); } @Override public ByteBuf setFloat(int index, float value) { throw reject(); } @Override public ByteBuf setDouble(int index, double value) { throw reject(); } @Override public ByteBuf skipBytes(int length) { checkReadableBytes(length); buffer.skipBytes(length); return this; } @Override public ByteBuf slice() { throw reject(); } @Override public ByteBuf retainedSlice() { throw reject(); } @Override public ByteBuf slice(int index, int length) { checkIndex(index, length); return buffer.slice(index, length); } @Override public ByteBuf retainedSlice(int index, int length) { checkIndex(index, length); return buffer.slice(index, length); } @Override public int nioBufferCount() { return buffer.nioBufferCount(); } @Override public ByteBuffer nioBuffer() { throw reject(); } @Override public ByteBuffer nioBuffer(int index, int length) { checkIndex(index, length); return buffer.nioBuffer(index, length); } @Override public ByteBuffer[] nioBuffers() { throw reject(); } @Override public ByteBuffer[] nioBuffers(int index, int length) { checkIndex(index, length); return buffer.nioBuffers(index, length); } @Override public ByteBuffer internalNioBuffer(int index, int length) { checkIndex(index, length); return buffer.internalNioBuffer(index, length); } @Override public String toString(int index, int length, Charset charset) { checkIndex(index, length); return buffer.toString(index, length, charset); } @Override public String toString(Charset charsetName) { throw reject(); } @Override public String toString() { return StringUtil.simpleClassName(this) + '(' + "ridx=" + readerIndex() + ", " + "widx=" + writerIndex() + ')'; } @Override public boolean isWritable() { return false; } @Override public boolean isWritable(int size) { return false; } @Override public int writableBytes() { return 0; } @Override public int maxWritableBytes() { return 0; } @Override public ByteBuf writeBoolean(boolean value) { throw reject(); } @Override public ByteBuf writeByte(int value) { throw reject(); } @Override public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { throw reject(); } @Override public ByteBuf writeBytes(byte[] src) { throw reject(); } @Override public ByteBuf writeBytes(ByteBuffer src) { throw reject(); } @Override public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { throw reject(); } @Override public ByteBuf writeBytes(ByteBuf src, int length) { throw reject(); } @Override public ByteBuf writeBytes(ByteBuf src) { throw reject(); } @Override public int writeBytes(InputStream in, int length) { throw reject(); } @Override public int writeBytes(ScatteringByteChannel in, int length) { throw reject(); } @Override public int writeBytes(FileChannel in, long position, int length) { throw reject(); } @Override public ByteBuf writeInt(int value) { throw reject(); } @Override public ByteBuf writeIntLE(int value) { throw reject(); } @Override public ByteBuf writeLong(long value) { throw reject(); } @Override public ByteBuf writeLongLE(long value) { throw reject(); } @Override public ByteBuf writeMedium(int value) { throw reject(); } @Override public ByteBuf writeMediumLE(int value) { throw reject(); } @Override public ByteBuf writeZero(int length) { throw reject(); } @Override public int writerIndex() { return buffer.writerIndex(); } @Override public ByteBuf writerIndex(int writerIndex) { throw reject(); } @Override public ByteBuf writeShort(int value) { throw reject(); } @Override public ByteBuf writeShortLE(int value) { throw reject(); } @Override public ByteBuf writeChar(int value) { throw reject(); } @Override public ByteBuf writeFloat(float value) { throw reject(); } @Override public ByteBuf writeDouble(double value) { throw reject(); } @Override public int setCharSequence(int index, CharSequence sequence, Charset charset) { throw reject(); } @Override public int writeCharSequence(CharSequence sequence, Charset charset) { throw reject(); } private void checkIndex(int index, int length) { if (index + length > buffer.writerIndex()) { decoder.requireWriterIndex(index + length); throw REPLAY; } } private void checkReadableBytes(int readableBytes) { if (buffer.readableBytes() < readableBytes) { decoder.requireWriterIndex(buffer.readerIndex() + readableBytes); throw REPLAY; } } @Override public ByteBuf discardSomeReadBytes() { throw reject(); } @Override public int refCnt() { return buffer.refCnt(); } @Override public ByteBuf retain() { throw reject(); } @Override public ByteBuf retain(int increment) { throw reject(); } @Override public ByteBuf touch() { buffer.touch(); return this; } @Override public ByteBuf touch(Object hint) { buffer.touch(hint); return this; } @Override public boolean release() { throw reject(); } @Override public boolean release(int decrement) { throw reject(); } @Override public ByteBuf unwrap() { throw reject(); } private static UnsupportedOperationException reject() { return new UnsupportedOperationException("not a replayable operation"); } }
23,775
20.022104
114
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/DefaultTransportFactory.java
package org.infinispan.client.hotrod.impl.transport.netty; import java.util.concurrent.ExecutorService; import org.infinispan.client.hotrod.TransportFactory; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.SocketChannel; /** * Default implementation of the {@link TransportFactory} interface which delegates the selection of transport to {@link NativeTransport} */ public class DefaultTransportFactory implements TransportFactory { public Class<? extends SocketChannel> socketChannelClass() { return NativeTransport.socketChannelClass(); } public EventLoopGroup createEventLoopGroup(int maxExecutors, ExecutorService executorService) { return NativeTransport.createEventLoopGroup(maxExecutors, executorService); } @Override public Class<? extends DatagramChannel> datagramChannelClass() { return NativeTransport.datagramChannelClass(); } }
958
33.25
137
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/ChannelInitializer.java
package org.infinispan.client.hotrod.impl.transport.netty; import java.io.File; import java.net.SocketAddress; import java.security.Principal; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.Provider; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import javax.net.ssl.SNIHostName; import javax.net.ssl.SSLParameters; import javax.security.auth.Subject; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslClientFactory; import javax.security.sasl.SaslException; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.AuthenticationConfiguration; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.configuration.SslConfiguration; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.util.SaslUtils; import org.infinispan.commons.util.SslContextFactory; import org.infinispan.commons.util.Util; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.JdkSslContext; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslHandler; import io.netty.handler.timeout.IdleStateHandler; class ChannelInitializer extends io.netty.channel.ChannelInitializer<Channel> { private static final Log log = LogFactory.getLog(ChannelInitializer.class); private final Bootstrap bootstrap; private final SocketAddress unresolvedAddress; private final OperationsFactory operationsFactory; private final Configuration configuration; private final ChannelFactory channelFactory; private ChannelPool channelPool; private volatile boolean isFirstPing = true; private static final Provider[] SECURITY_PROVIDERS; static { // Register only the providers that matter to us List<Provider> providers = new ArrayList<>(); for (String name : Arrays.asList( "org.wildfly.security.sasl.plain.WildFlyElytronSaslPlainProvider", "org.wildfly.security.sasl.digest.WildFlyElytronSaslDigestProvider", "org.wildfly.security.sasl.external.WildFlyElytronSaslExternalProvider", "org.wildfly.security.sasl.oauth2.WildFlyElytronSaslOAuth2Provider", "org.wildfly.security.sasl.scram.WildFlyElytronSaslScramProvider", "org.wildfly.security.sasl.gssapi.WildFlyElytronSaslGssapiProvider", "org.wildfly.security.sasl.gs2.WildFlyElytronSaslGs2Provider" )) { Provider provider = Util.getInstance(name, RemoteCacheManager.class.getClassLoader()); providers.add(provider); } SECURITY_PROVIDERS = providers.toArray(new Provider[0]); } ChannelInitializer(Bootstrap bootstrap, SocketAddress unresolvedAddress, OperationsFactory operationsFactory, Configuration configuration, ChannelFactory channelFactory) { this.bootstrap = bootstrap; this.unresolvedAddress = unresolvedAddress; this.operationsFactory = operationsFactory; this.configuration = configuration; this.channelFactory = channelFactory; } CompletableFuture<Channel> createChannel() { ChannelFuture connect = bootstrap.clone().connect(); ActivationFuture activationFuture = new ActivationFuture(); connect.addListener(activationFuture); return activationFuture; } @Override protected void initChannel(Channel channel) throws Exception { if (log.isTraceEnabled()) { log.tracef("Created channel %s", channel); } if (configuration.security().ssl().enabled()) { initSsl(channel); } AuthenticationConfiguration authentication = configuration.security().authentication(); if (authentication.enabled()) { initAuthentication(channel, authentication); } if (configuration.connectionPool().minEvictableIdleTime() > 0) { channel.pipeline().addLast("idle-state-handler", new IdleStateHandler(0, 0, configuration.connectionPool().minEvictableIdleTime(), TimeUnit.MILLISECONDS)); } ChannelRecord channelRecord = new ChannelRecord(unresolvedAddress, channelPool); channel.attr(ChannelRecord.KEY).set(channelRecord); if (isFirstPing) { isFirstPing = false; channel.pipeline().addLast(InitialPingHandler.NAME, new InitialPingHandler(operationsFactory.newPingOperation(false))); } else { channel.pipeline().addLast(ActivationHandler.NAME, ActivationHandler.INSTANCE); } channel.pipeline().addLast(HeaderDecoder.NAME, new HeaderDecoder(channelFactory, configuration, operationsFactory.getListenerNotifier())); if (configuration.connectionPool().minEvictableIdleTime() > 0) { // This handler needs to be the last so that HeaderDecoder has the chance to cancel the idle event channel.pipeline().addLast(IdleStateHandlerProvider.NAME, new IdleStateHandlerProvider(configuration.connectionPool().minIdle(), channelPool)); } } private void initSsl(Channel channel) { SslConfiguration ssl = configuration.security().ssl(); SslContext sslContext; if (ssl.sslContext() == null) { SslContextBuilder builder = SslContextBuilder.forClient(); try { if (ssl.keyStoreFileName() != null) { builder.keyManager(new SslContextFactory() .keyStoreFileName(ssl.keyStoreFileName()) .keyStoreType(ssl.keyStoreType()) .keyStorePassword(ssl.keyStorePassword()) .keyAlias(ssl.keyAlias()) .keyStoreCertificatePassword(ssl.keyStoreCertificatePassword()) .classLoader(configuration.classLoader()) .provider(ssl.provider()) .getKeyManagerFactory()); } if (ssl.trustStoreFileName() != null) { if ("pem".equalsIgnoreCase(ssl.trustStoreType())) { builder.trustManager(new File(ssl.trustStoreFileName())); } else { builder.trustManager(new SslContextFactory() .trustStoreFileName(ssl.trustStoreFileName()) .trustStoreType(ssl.trustStoreType()) .trustStorePassword(ssl.trustStorePassword()) .classLoader(configuration.classLoader()) .provider(ssl.provider()) .getTrustManagerFactory()); } } if (ssl.trustStorePath() != null) { builder.trustManager(new File(ssl.trustStorePath())); } if (ssl.protocol() != null) { builder.protocols(ssl.protocol()); } if (ssl.ciphers() != null) { builder.ciphers(ssl.ciphers()); } if (ssl.provider() != null) { Provider provider = SslContextFactory.findProvider(ssl.provider(), SslContext.class.getSimpleName(), "TLS"); builder.sslContextProvider(provider); } sslContext = builder.build(); } catch (Exception e) { throw new CacheConfigurationException(e); } } else { sslContext = new JdkSslContext(ssl.sslContext(), true, ClientAuth.NONE); } SslHandler sslHandler = sslContext.newHandler(channel.alloc(), ssl.sniHostName(), -1); if (ssl.sniHostName() != null) { SSLParameters sslParameters = sslHandler.engine().getSSLParameters(); sslParameters.setServerNames(Collections.singletonList(new SNIHostName(ssl.sniHostName()))); sslHandler.engine().setSSLParameters(sslParameters); } channel.pipeline().addFirst(sslHandler, SslHandshakeExceptionHandler.INSTANCE); } private void initAuthentication(Channel channel, AuthenticationConfiguration authentication) throws PrivilegedActionException, SaslException { SaslClient saslClient; SaslClientFactory scf = getSaslClientFactory(authentication); SslHandler sslHandler = channel.pipeline().get(SslHandler.class); Principal principal = sslHandler != null ? sslHandler.engine().getSession().getLocalPrincipal() : null; String authorizationId = principal != null ? principal.getName() : null; if (authentication.clientSubject() != null) { // We must use Subject.doAs() instead of Security.doAs() saslClient = Subject.doAs(authentication.clientSubject(), (PrivilegedExceptionAction<SaslClient>) () -> scf.createSaslClient(new String[]{authentication.saslMechanism()}, authorizationId, "hotrod", authentication.serverName(), authentication.saslProperties(), authentication.callbackHandler()) ); } else { saslClient = scf.createSaslClient(new String[]{authentication.saslMechanism()}, authorizationId, "hotrod", authentication.serverName(), authentication.saslProperties(), authentication.callbackHandler()); } channel.pipeline().addLast(AuthHandler.NAME, new AuthHandler(authentication, saslClient, operationsFactory)); } private SaslClientFactory getSaslClientFactory(AuthenticationConfiguration configuration) { if (log.isTraceEnabled()) { log.tracef("Attempting to load SaslClientFactory implementation with mech=%s, props=%s", configuration.saslMechanism(), configuration.saslProperties()); } Collection<SaslClientFactory> clientFactories = SaslUtils.getSaslClientFactories(this.getClass().getClassLoader(), SECURITY_PROVIDERS, true); for (SaslClientFactory saslFactory : clientFactories) { try { String[] saslFactoryMechs = saslFactory.getMechanismNames(configuration.saslProperties()); for (String supportedMech : saslFactoryMechs) { if (supportedMech.equals(configuration.saslMechanism())) { if (log.isTraceEnabled()) { log.tracef("Loaded SaslClientFactory: %s", saslFactory.getClass().getName()); } return saslFactory; } } } catch (Throwable t) { // Catch any errors that can happen when calling to a Sasl mech log.tracef("Error while trying to obtain mechanism names supported by SaslClientFactory: %s", saslFactory.getClass().getName()); } } throw new IllegalStateException("SaslClientFactory implementation not found"); } void setChannelPool(ChannelPool channelPool) { this.channelPool = channelPool; } private static class ActivationFuture extends CompletableFuture<Channel> implements ChannelFutureListener, BiConsumer<Channel, Throwable> { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { Channel channel = future.channel(); ChannelRecord.of(channel).whenComplete(this); } else { completeExceptionally(future.cause()); } } @Override public void accept(Channel channel, Throwable throwable) { if (throwable != null) { completeExceptionally(throwable); } else { complete(channel); } } } }
11,967
45.208494
174
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/ChannelFactory.java
package org.infinispan.client.hotrod.impl.transport.netty; import static org.infinispan.client.hotrod.impl.Util.await; import static org.infinispan.client.hotrod.impl.Util.wrapBytes; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; 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.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Function; import org.infinispan.client.hotrod.CacheTopologyInfo; import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ClientIntelligence; import org.infinispan.client.hotrod.configuration.ClusterConfiguration; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.configuration.ServerConfiguration; import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.hotrod.impl.MarshallerRegistry; import org.infinispan.client.hotrod.impl.TopologyInfo; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHashFactory; import org.infinispan.client.hotrod.impl.consistenthash.SegmentConsistentHash; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.protocol.CodecHolder; import org.infinispan.client.hotrod.impl.topology.CacheInfo; import org.infinispan.client.hotrod.impl.topology.ClusterInfo; import org.infinispan.client.hotrod.impl.transport.netty.ChannelPool.ChannelEventType; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.marshall.WrappedBytes; import org.infinispan.commons.util.Immutables; import org.infinispan.commons.util.ProcessorInfo; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.resolver.AddressResolverGroup; import io.netty.resolver.dns.DnsNameResolverBuilder; import io.netty.resolver.dns.RoundRobinDnsAddressResolverGroup; import net.jcip.annotations.GuardedBy; import net.jcip.annotations.ThreadSafe; /** * Central component providing connections to remote server. Most of the code originates in TcpTransportFactory. * * @since 9.3 */ @ThreadSafe public class ChannelFactory { public static final String DEFAULT_CLUSTER_NAME = "___DEFAULT-CLUSTER___"; private static final Log log = LogFactory.getLog(ChannelFactory.class, Log.class); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final ConcurrentMap<SocketAddress, ChannelPool> channelPoolMap = new ConcurrentHashMap<>(); private final Function<SocketAddress, ChannelPool> newPool = this::newPool; private EventLoopGroup eventLoopGroup; private ExecutorService executorService; private OperationsFactory operationsFactory; private Configuration configuration; private int maxRetries; private Marshaller marshaller; private ClientListenerNotifier listenerNotifier; @GuardedBy("lock") private volatile TopologyInfo topologyInfo; private List<ClusterInfo> clusters; private MarshallerRegistry marshallerRegistry; private final LongAdder totalRetries = new LongAdder(); @GuardedBy("lock") private CompletableFuture<Void> clusterSwitchStage; // Servers for which the last connection attempt failed and which have no established connections @GuardedBy("lock") private final Set<SocketAddress> failedServers = new HashSet<>(); private final CodecHolder codecHolder; public ChannelFactory(CodecHolder codecHolder) { this.codecHolder = codecHolder; } public void start(Configuration configuration, Marshaller marshaller, ExecutorService executorService, ClientListenerNotifier listenerNotifier, MarshallerRegistry marshallerRegistry) { this.marshallerRegistry = marshallerRegistry; lock.writeLock().lock(); try { this.marshaller = marshaller; this.configuration = configuration; this.executorService = executorService; this.listenerNotifier = listenerNotifier; int asyncThreads = maxAsyncThreads(executorService, configuration); // static field with default is private in MultithreadEventLoopGroup int eventLoopThreads = Integer.getInteger("io.netty.eventLoopThreads", ProcessorInfo.availableProcessors() * 2); // Note that each event loop opens a selector which counts int maxExecutors = Math.min(asyncThreads, eventLoopThreads); this.eventLoopGroup = configuration.transportFactory().createEventLoopGroup(maxExecutors, executorService); List<InetSocketAddress> initialServers = new ArrayList<>(); for (ServerConfiguration server : configuration.servers()) { initialServers.add(InetSocketAddress.createUnresolved(server.host(), server.port())); } ClusterInfo mainCluster = new ClusterInfo(DEFAULT_CLUSTER_NAME, initialServers, configuration.clientIntelligence()); List<ClusterInfo> clustersDefinitions = new ArrayList<>(); if (log.isDebugEnabled()) { log.debugf("Statically configured servers: %s", initialServers); log.debugf("Tcp no delay = %b; client socket timeout = %d ms; connect timeout = %d ms", configuration.tcpNoDelay(), configuration.socketTimeout(), configuration.connectionTimeout()); } if (!configuration.clusters().isEmpty()) { for (ClusterConfiguration clusterConfiguration : configuration.clusters()) { List<InetSocketAddress> alternateServers = new ArrayList<>(); for (ServerConfiguration server : clusterConfiguration.getCluster()) { alternateServers.add(InetSocketAddress.createUnresolved(server.host(), server.port())); } ClientIntelligence intelligence = clusterConfiguration.getClientIntelligence() != null ? clusterConfiguration.getClientIntelligence() : configuration.clientIntelligence(); ClusterInfo alternateCluster = new ClusterInfo(clusterConfiguration.getClusterName(), alternateServers, intelligence); log.debugf("Add secondary cluster: %s", alternateCluster); clustersDefinitions.add(alternateCluster); } clustersDefinitions.add(mainCluster); } clusters = Immutables.immutableListCopy(clustersDefinitions); topologyInfo = new TopologyInfo(configuration, mainCluster); operationsFactory = new OperationsFactory(this, listenerNotifier, configuration); maxRetries = configuration.maxRetries(); WrappedByteArray defaultCacheName = wrapBytes(RemoteCacheManager.cacheNameBytes()); topologyInfo.getOrCreateCacheInfo(defaultCacheName); } finally { lock.writeLock().unlock(); } pingServersIgnoreException(); } public Codec getNegotiatedCodec() { return codecHolder.getCodec(); } public void setNegotiatedCodec(Codec negotiatedCodec) { codecHolder.setCodec(negotiatedCodec); } private int maxAsyncThreads(ExecutorService executorService, Configuration configuration) { if (executorService instanceof ThreadPoolExecutor) { return ((ThreadPoolExecutor) executorService).getMaximumPoolSize(); } // Note: this is quite dangerous, if someone sets different executor factory and does not update this setting // we might deadlock return new ConfigurationProperties(configuration.asyncExecutorFactory().properties()).getDefaultExecutorFactoryPoolSize(); } public MarshallerRegistry getMarshallerRegistry() { return marshallerRegistry; } private ChannelPool newPool(SocketAddress address) { log.debugf("Creating new channel pool for %s", address); DnsNameResolverBuilder builder = new DnsNameResolverBuilder() .channelType(configuration.transportFactory().datagramChannelClass()) .ttl(configuration.dnsResolverMinTTL(), configuration.dnsResolverMaxTTL()) .negativeTtl(configuration.dnsResolverNegativeTTL()); AddressResolverGroup<?> dnsResolver = new RoundRobinDnsAddressResolverGroup(builder); Bootstrap bootstrap = new Bootstrap() .group(eventLoopGroup) .channel(configuration.transportFactory().socketChannelClass()) .resolver(dnsResolver) .remoteAddress(address) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.connectionTimeout()) .option(ChannelOption.SO_KEEPALIVE, configuration.tcpKeepAlive()) .option(ChannelOption.TCP_NODELAY, configuration.tcpNoDelay()) .option(ChannelOption.SO_RCVBUF, 1024576); ChannelInitializer channelInitializer = createChannelInitializer(address, bootstrap); bootstrap.handler(channelInitializer); ChannelPool pool = createChannelPool(bootstrap, channelInitializer, address); channelInitializer.setChannelPool(pool); return pool; } public ChannelInitializer createChannelInitializer(SocketAddress address, Bootstrap bootstrap) { return new ChannelInitializer(bootstrap, address, operationsFactory, configuration, this); } protected ChannelPool createChannelPool(Bootstrap bootstrap, ChannelInitializer channelInitializer, SocketAddress address) { int maxConnections = configuration.connectionPool().maxActive(); if (maxConnections < 0) { maxConnections = Integer.MAX_VALUE; } return new ChannelPool(bootstrap.config().group().next(), address, channelInitializer, configuration.connectionPool().exhaustedAction(), this::onConnectionEvent, configuration.connectionPool().maxWait(), maxConnections, configuration.connectionPool().maxPendingRequests()); } protected final OperationsFactory getOperationsFactory() { return operationsFactory; } private void pingServersIgnoreException() { Collection<InetSocketAddress> servers = topologyInfo.getAllServers(); for (SocketAddress addr : servers) { // Go through all statically configured nodes and force a // connection to be established and a ping message to be sent. try { await(fetchChannelAndInvoke(addr, operationsFactory.newPingOperation(true))); } catch (Exception e) { // Ping's objective is to retrieve a potentially newer // version of the Hot Rod cluster topology, so ignore // exceptions from nodes that might not be up any more. if (log.isTraceEnabled()) log.tracef(e, "Ignoring exception pinging configured servers %s to establish a connection", servers); } } } public void destroy() { try { channelPoolMap.values().forEach(ChannelPool::close); eventLoopGroup.shutdownGracefully(0, 0, TimeUnit.MILLISECONDS).get(); executorService.shutdownNow(); } catch (Exception e) { log.warn("Exception while shutting down the connection pool.", e); } } public CacheTopologyInfo getCacheTopologyInfo(byte[] cacheName) { lock.readLock().lock(); try { return topologyInfo.getCacheTopologyInfo(cacheName); } finally { lock.readLock().unlock(); } } public Map<SocketAddress, Set<Integer>> getPrimarySegmentsByAddress(byte[] cacheName) { lock.readLock().lock(); try { return topologyInfo.getPrimarySegmentsByServer(cacheName); } finally { lock.readLock().unlock(); } } public <T extends ChannelOperation> T fetchChannelAndInvoke(Set<SocketAddress> failedServers, byte[] cacheName, T operation) { return fetchChannelAndInvoke(failedServers, cacheName, operation, true); } private <T extends ChannelOperation> T fetchChannelAndInvoke(Set<SocketAddress> failedServers, byte[] cacheName, T operation, boolean checkServer) { SocketAddress server; // Need the write lock because FailoverRequestBalancingStrategy is not thread-safe lock.writeLock().lock(); try { if (failedServers != null) { CompletableFuture<Void> switchStage = this.clusterSwitchStage; if (switchStage != null) { switchStage.whenComplete((__, t) -> fetchChannelAndInvoke(failedServers, cacheName, operation)); return operation; } } CacheInfo cacheInfo = topologyInfo.getCacheInfo(wrapBytes(cacheName)); FailoverRequestBalancingStrategy balancer = cacheInfo.getBalancer(); server = balancer.nextServer(failedServers); } finally { lock.writeLock().unlock(); } return checkServer ? fetchChannelAndInvoke(server, cacheName, operation) : fetchChannelAndInvoke(server, operation); } // Package-private for testing purposes. <T extends ChannelOperation> T fetchChannelAndInvoke(SocketAddress preferred, byte[] cacheName, T operation) { boolean suspect; lock.readLock().lock(); try { suspect = failedServers.contains(preferred); } finally { lock.readLock().unlock(); } if (suspect) { if (log.isTraceEnabled()) log.tracef("Server %s is suspected, trying another for %s", preferred, operation); return fetchChannelAndInvoke(failedServers, cacheName, operation, false); } return fetchChannelAndInvoke(preferred, operation); } public <T extends ChannelOperation> T fetchChannelAndInvoke(SocketAddress server, T operation) { ChannelPool pool = channelPoolMap.computeIfAbsent(server, newPool); pool.acquire(operation); return operation; } private void closeChannelPools(Set<? extends SocketAddress> servers) { for (SocketAddress server : servers) { HOTROD.removingServer(server); ChannelPool pool = channelPoolMap.remove(server); if (pool != null) { pool.close(); } } // We don't care if the server is failed any more lock.writeLock().lock(); try { this.failedServers.removeAll(servers); } finally { lock.writeLock().unlock(); } } public SocketAddress getHashAwareServer(Object key, byte[] cacheName) { CacheInfo cacheInfo = topologyInfo.getCacheInfo(wrapBytes(cacheName)); if (cacheInfo != null && cacheInfo.getConsistentHash() != null) { return cacheInfo.getConsistentHash().getServer(key); } return null; } public <T extends ChannelOperation> T fetchChannelAndInvoke(Object key, Set<SocketAddress> failedServers, byte[] cacheName, T operation) { CacheInfo cacheInfo = topologyInfo.getCacheInfo(wrapBytes(cacheName)); if (cacheInfo != null && cacheInfo.getConsistentHash() != null) { SocketAddress server = cacheInfo.getConsistentHash().getServer(key); if (server != null && (failedServers == null || !failedServers.contains(server))) { return fetchChannelAndInvoke(server, cacheName, operation); } } return fetchChannelAndInvoke(failedServers, cacheName, operation); } public void releaseChannel(Channel channel) { // Due to ISPN-7955 we need to keep addresses unresolved. However resolved and unresolved addresses // are not deemed equal, and that breaks the comparison in channelPool - had we used channel.remoteAddress() // we'd create another pool for this resolved address. Therefore we need to find out appropriate pool this // channel belongs using the attribute. ChannelRecord record = ChannelRecord.of(channel); record.release(channel); } public void receiveTopology(byte[] cacheName, int responseTopologyAge, int responseTopologyId, InetSocketAddress[] addresses, SocketAddress[][] segmentOwners, short hashFunctionVersion) { WrappedByteArray wrappedCacheName = wrapBytes(cacheName); lock.writeLock().lock(); try { CacheInfo cacheInfo = topologyInfo.getCacheInfo(wrappedCacheName); assert cacheInfo != null : "The cache info must exist before receiving a topology update"; // Only accept the update if it's from the current age and the topology id is greater than the current one // Relies on TopologyInfo.switchCluster() to update the topologyAge for caches first if (responseTopologyAge == cacheInfo.getTopologyAge() && responseTopologyId != cacheInfo.getTopologyId()) { List<InetSocketAddress> addressList = Arrays.asList(addresses); HOTROD.newTopology(responseTopologyId, responseTopologyAge, addresses.length, addressList); CacheInfo newCacheInfo; if (hashFunctionVersion >= 0) { SegmentConsistentHash consistentHash = createConsistentHash(segmentOwners, hashFunctionVersion, cacheInfo.getCacheName()); newCacheInfo = cacheInfo.withNewHash(responseTopologyAge, responseTopologyId, addressList, consistentHash, segmentOwners.length); } else { newCacheInfo = cacheInfo.withNewServers(responseTopologyAge, responseTopologyId, addressList); } updateCacheInfo(wrappedCacheName, newCacheInfo, false); } else { if (log.isTraceEnabled()) log.tracef("[%s] Ignoring outdated topology: topology id = %s, topology age = %s, servers = %s", cacheInfo.getCacheName(), responseTopologyId, responseTopologyAge, Arrays.toString(addresses)); } } finally { lock.writeLock().unlock(); } } private SegmentConsistentHash createConsistentHash(SocketAddress[][] segmentOwners, short hashFunctionVersion, String cacheNameString) { if (log.isTraceEnabled()) { if (hashFunctionVersion == 0) log.tracef("[%s] Not using a consistent hash function (hash function version == 0).", cacheNameString); else log.tracef("[%s] Updating client hash function with %s number of segments", cacheNameString, segmentOwners.length); } return topologyInfo.createConsistentHash(segmentOwners.length, hashFunctionVersion, segmentOwners); } @GuardedBy("lock") protected void updateCacheInfo(WrappedBytes cacheName, CacheInfo newCacheInfo, boolean quiet) { List<InetSocketAddress> newServers = newCacheInfo.getServers(); CacheInfo oldCacheInfo = topologyInfo.getCacheInfo(cacheName); List<InetSocketAddress> oldServers = oldCacheInfo.getServers(); Set<SocketAddress> addedServers = new HashSet<>(newServers); oldServers.forEach(addedServers::remove); Set<SocketAddress> removedServers = new HashSet<>(oldServers); newServers.forEach(removedServers::remove); if (log.isTraceEnabled()) { String cacheNameString = newCacheInfo.getCacheName(); log.tracef("[%s] Current list: %s", cacheNameString, oldServers); log.tracef("[%s] New list: %s", cacheNameString, newServers); log.tracef("[%s] Added servers: %s", cacheNameString, addedServers); log.tracef("[%s] Removed servers: %s", cacheNameString, removedServers); } // First add new servers. For servers that went down, the returned transport will fail for now for (SocketAddress server : addedServers) { HOTROD.newServerAdded(server); fetchChannelAndInvoke(server, new ReleaseChannelOperation(quiet)); } // Then update the server list for new operations topologyInfo.updateCacheInfo(cacheName, oldCacheInfo, newCacheInfo); // TODO Do not close a server pool until the server has been removed from all cache infos // And finally remove the failed servers closeChannelPools(removedServers); if (!removedServers.isEmpty()) { listenerNotifier.failoverListeners(removedServers); } } public Collection<InetSocketAddress> getServers() { lock.readLock().lock(); try { return topologyInfo.getAllServers(); } finally { lock.readLock().unlock(); } } public Collection<InetSocketAddress> getServers(byte[] cacheName) { lock.readLock().lock(); try { return topologyInfo.getServers(wrapBytes(cacheName)); } finally { lock.readLock().unlock(); } } /** * Note that the returned <code>ConsistentHash</code> may not be thread-safe. */ public ConsistentHash getConsistentHash(byte[] cacheName) { lock.readLock().lock(); try { return topologyInfo.getCacheInfo(wrapBytes(cacheName)).getConsistentHash(); } finally { lock.readLock().unlock(); } } public ConsistentHashFactory getConsistentHashFactory() { return topologyInfo.getConsistentHashFactory(); } public boolean isTcpNoDelay() { return configuration.tcpNoDelay(); } public boolean isTcpKeepAlive() { return configuration.tcpKeepAlive(); } public int getMaxRetries() { return maxRetries; } public AtomicReference<ClientTopology> createTopologyId(byte[] cacheName) { lock.writeLock().lock(); try { return topologyInfo.getOrCreateCacheInfo(wrapBytes(cacheName)).getClientTopologyRef(); } finally { lock.writeLock().unlock(); } } public int getTopologyId(byte[] cacheName) { return topologyInfo.getCacheInfo(wrapBytes(cacheName)).getTopologyId(); } public void onConnectionEvent(ChannelPool pool, ChannelEventType type) { boolean allInitialServersFailed; lock.writeLock().lock(); try { // TODO Replace with a simpler "pool healthy/unhealthy" event? if (type == ChannelEventType.CONNECTED) { failedServers.remove(pool.getAddress()); return; } else if (type == ChannelEventType.CONNECT_FAILED) { if (pool.getConnected() == 0) { failedServers.add(pool.getAddress()); } } else { // Nothing to do return; } if (log.isTraceEnabled()) log.tracef("Connection attempt failed, we now have %d servers with no established connections: %s", failedServers.size(), failedServers); allInitialServersFailed = failedServers.containsAll(topologyInfo.getCluster().getInitialServers()); if (!allInitialServersFailed || clusters.isEmpty()) { resetCachesWithFailedServers(); } } finally { lock.writeLock().unlock(); } if (allInitialServersFailed && !clusters.isEmpty()) { trySwitchCluster(); } } private void trySwitchCluster() { int ageBeforeSwitch; ClusterInfo cluster; lock.writeLock().lock(); try { ageBeforeSwitch = topologyInfo.getTopologyAge(); cluster = topologyInfo.getCluster(); if (clusterSwitchStage != null) { if (log.isTraceEnabled()) log.tracef("Cluster switch is already in progress for topology age %d", ageBeforeSwitch); return; } clusterSwitchStage = new CompletableFuture<>(); } finally { lock.writeLock().unlock(); } checkServersAlive(cluster.getInitialServers()) .thenCompose(alive -> { if (alive) { // The live check removed the server from failedServers when it established a connection if (log.isTraceEnabled()) log.tracef("Cluster %s is still alive, not switching", cluster); return CompletableFuture.completedFuture(null); } if (log.isTraceEnabled()) log.tracef("Trying to switch cluster away from '%s'", cluster.getName()); return findLiveCluster(cluster, ageBeforeSwitch); }) .thenAccept(newCluster -> { if (newCluster != null) { automaticSwitchToCluster(newCluster, cluster, ageBeforeSwitch); } }) .whenComplete((__, t) -> completeClusterSwitch()); } @GuardedBy("lock") private void resetCachesWithFailedServers() { List<WrappedBytes> failedCaches = new ArrayList<>(); List<String> nameStrings = new ArrayList<>(); topologyInfo.forEachCache((cacheNameBytes, cacheInfo) -> { List<InetSocketAddress> cacheServers = cacheInfo.getServers(); boolean currentServersHaveFailed = failedServers.containsAll(cacheServers); boolean canReset = !cacheServers.equals(topologyInfo.getCluster().getInitialServers()); if (currentServersHaveFailed && canReset) { failedCaches.add(cacheNameBytes); nameStrings.add(cacheInfo.getCacheName()); } }); if (!failedCaches.isEmpty()) { HOTROD.revertCacheToInitialServerList(nameStrings); for (WrappedBytes cacheNameBytes : failedCaches) { topologyInfo.reset(cacheNameBytes); } } } private void completeClusterSwitch() { CompletableFuture<Void> localStage; lock.writeLock().lock(); try { localStage = this.clusterSwitchStage; this.clusterSwitchStage = null; } finally { lock.writeLock().unlock(); } // An automatic cluster switch could be cancelled by a manual switch, // and a manual cluster switch would not have a stage to begin with if (localStage != null) { localStage.complete(null); } } private CompletionStage<ClusterInfo> findLiveCluster(ClusterInfo failedCluster, int ageBeforeSwitch) { List<ClusterInfo> candidateClusters = new ArrayList<>(); for (ClusterInfo cluster : clusters) { String clusterName = cluster.getName(); if (!clusterName.equals(failedCluster.getName())) candidateClusters.add(cluster); } Iterator<ClusterInfo> clusterIterator = candidateClusters.iterator(); return findLiveCluster0(false, null, clusterIterator, ageBeforeSwitch); } private CompletionStage<ClusterInfo> findLiveCluster0(boolean alive, ClusterInfo testedCluster, Iterator<ClusterInfo> clusterIterator, int ageBeforeSwitch) { lock.writeLock().lock(); try { if (clusterSwitchStage == null || topologyInfo.getTopologyAge() != ageBeforeSwitch) { log.debugf("Cluster switch already completed by another thread, bailing out"); return CompletableFuture.completedFuture(null); } } finally { lock.writeLock().unlock(); } if (alive) return CompletableFuture.completedFuture(testedCluster); if (!clusterIterator.hasNext()) { log.debugf("All cluster addresses viewed and none worked: %s", clusters); return CompletableFuture.completedFuture(null); } ClusterInfo nextCluster = clusterIterator.next(); return checkServersAlive(nextCluster.getInitialServers()) .thenCompose(aliveNext -> findLiveCluster0(aliveNext, nextCluster, clusterIterator, ageBeforeSwitch)); } private CompletionStage<Boolean> checkServersAlive(Collection<InetSocketAddress> servers) { if (servers.isEmpty()) return CompletableFuture.completedFuture(false); AtomicInteger remainingResponses = new AtomicInteger(servers.size()); CompletableFuture<Boolean> allFuture = new CompletableFuture<>(); for (SocketAddress server : servers) { fetchChannelAndInvoke(server, operationsFactory.newPingOperation(true)).whenComplete((result, throwable) -> { if (throwable != null) { if (log.isTraceEnabled()) { log.tracef(throwable, "Error checking whether this server is alive: %s", server); } if (remainingResponses.decrementAndGet() == 0) { allFuture.complete(false); } } else { // One successful response is enough to be able to switch to this cluster log.tracef("Ping to server %s succeeded", server); allFuture.complete(true); } }); } return allFuture; } private void automaticSwitchToCluster(ClusterInfo newCluster, ClusterInfo failedCluster, int ageBeforeSwitch) { lock.writeLock().lock(); try { if (clusterSwitchStage == null || topologyInfo.getTopologyAge() != ageBeforeSwitch) { log.debugf("Cluster switch already completed by another thread, bailing out"); return; } topologyInfo.switchCluster(newCluster); } finally { lock.writeLock().unlock(); } if (!newCluster.getName().equals(DEFAULT_CLUSTER_NAME)) HOTROD.switchedToCluster(newCluster.getName()); else HOTROD.switchedBackToMainCluster(); } /** * Switch to an alternate cluster (or from an alternate cluster back to the main cluster). * * <p>Overrides any automatic cluster switch in progress, which may be useful * when the automatic switch takes too long.</p> */ public boolean manualSwitchToCluster(String clusterName) { if (clusters.isEmpty()) { log.debugf("No alternative clusters configured, so can't switch cluster"); return false; } ClusterInfo cluster = findCluster(clusterName); if (cluster == null) { log.debugf("Cluster named %s does not exist in the configuration", clusterName); return false; } lock.writeLock().lock(); boolean shouldComplete = false; try { if (clusterSwitchStage != null) { log.debugf("Another cluster switch is already in progress, overriding it"); shouldComplete = true; } log.debugf("Switching to cluster %s, servers: %s", clusterName, cluster.getInitialServers()); topologyInfo.switchCluster(cluster); } finally { lock.writeLock().unlock(); } if (!clusterName.equals(DEFAULT_CLUSTER_NAME)) HOTROD.manuallySwitchedToCluster(clusterName); else HOTROD.manuallySwitchedBackToMainCluster(); if (shouldComplete) { completeClusterSwitch(); } return true; } public Marshaller getMarshaller() { return marshaller; } public String getCurrentClusterName() { return topologyInfo.getCluster().getName(); } public int getTopologyAge() { return topologyInfo.getTopologyAge(); } private ClusterInfo findCluster(String clusterName) { for (ClusterInfo cluster : clusters) { if (cluster.getName().equals(clusterName)) return cluster; } return null; } /** * Note that the returned <code>RequestBalancingStrategy</code> may not be thread-safe. */ public FailoverRequestBalancingStrategy getBalancer(byte[] cacheName) { lock.readLock().lock(); try { return topologyInfo.getCacheInfo(wrapBytes(cacheName)).getBalancer(); } finally { lock.readLock().unlock(); } } public int socketTimeout() { return configuration.socketTimeout(); } public int getNumActive(SocketAddress address) { ChannelPool pool = channelPoolMap.get(address); return pool == null ? 0 : pool.getActive(); } public int getNumIdle(SocketAddress address) { ChannelPool pool = channelPoolMap.get(address); return pool == null ? 0 : pool.getIdle(); } public int getNumActive() { return channelPoolMap.values().stream().mapToInt(ChannelPool::getActive).sum(); } public int getNumIdle() { return channelPoolMap.values().stream().mapToInt(ChannelPool::getIdle).sum(); } public Configuration getConfiguration() { return configuration; } public long getRetries() { return totalRetries.longValue(); } public void incrementRetryCount() { totalRetries.increment(); } public ClientIntelligence getClientIntelligence() { lock.readLock().lock(); try { return topologyInfo.getCluster().getIntelligence(); } finally { lock.readLock().unlock(); } } private class ReleaseChannelOperation implements ChannelOperation { private final boolean quiet; private ReleaseChannelOperation(boolean quiet) { this.quiet = quiet; } @Override public void invoke(Channel channel) { releaseChannel(channel); } @Override public void cancel(SocketAddress address, Throwable cause) { if (!quiet) { HOTROD.failedAddingNewServer(address, cause); } } } }
34,516
39.896919
128
java