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/server/hotrod/src/test/java/org/infinispan/server/hotrod/counter/impl/TestCounterEventResponse.java
|
package org.infinispan.server.hotrod.counter.impl;
import static org.infinispan.server.hotrod.counter.listener.ClientCounterEvent.decodeNewState;
import static org.infinispan.server.hotrod.counter.listener.ClientCounterEvent.decodeOldState;
import org.infinispan.commons.marshall.WrappedByteArray;
import org.infinispan.counter.api.CounterEvent;
import org.infinispan.counter.api.CounterState;
import org.infinispan.server.hotrod.HotRodOperation;
import org.infinispan.server.hotrod.OperationStatus;
import org.infinispan.server.hotrod.test.TestResponse;
import org.infinispan.server.hotrod.transport.ExtendedByteBuf;
import io.netty.buffer.ByteBuf;
/**
* The test counter event.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class TestCounterEventResponse extends TestResponse {
private final String counterName;
private final WrappedByteArray listenerId;
private final CounterEvent counterEvent;
public TestCounterEventResponse(byte version, long messageId, HotRodOperation operation, ByteBuf buffer) {
super(version, messageId, "", (byte) 0, operation, OperationStatus.Success, 0, null);
counterName = ExtendedByteBuf.readString(buffer);
listenerId = new WrappedByteArray(ExtendedByteBuf.readRangedBytes(buffer));
byte counterState = buffer.readByte();
counterEvent = new CounterEventImpl(buffer.readLong(), decodeOldState(counterState), buffer.readLong(),
decodeNewState(counterState));
}
public String getCounterName() {
return counterName;
}
public WrappedByteArray getListenerId() {
return listenerId;
}
CounterEvent getCounterEvent() {
return counterEvent;
}
private static class CounterEventImpl implements CounterEvent {
private final long oldValue;
private final CounterState oldState;
private final long newValue;
private final CounterState newState;
private CounterEventImpl(long oldValue, CounterState oldState, long newValue,
CounterState newState) {
this.oldValue = oldValue;
this.oldState = oldState;
this.newValue = newValue;
this.newState = newState;
}
@Override
public long getOldValue() {
return oldValue;
}
@Override
public CounterState getOldState() {
return oldState;
}
@Override
public long getNewValue() {
return newValue;
}
@Override
public CounterState getNewState() {
return newState;
}
}
}
| 2,535
| 28.149425
| 109
|
java
|
null |
infinispan-main/server/hotrod/src/test/java/org/infinispan/server/hotrod/counter/impl/WeakCounterImplTestStrategy.java
|
package org.infinispan.server.hotrod.counter.impl;
import static java.util.Collections.singletonList;
import static org.infinispan.counter.api.CounterConfiguration.builder;
import static org.infinispan.counter.api.CounterType.WEAK;
import static org.infinispan.counter.impl.Util.awaitCounterOperation;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterListener;
import org.infinispan.counter.api.CounterManager;
import org.infinispan.counter.api.Handle;
import org.infinispan.counter.api.WeakCounter;
import org.infinispan.server.hotrod.counter.WeakCounterTestStrategy;
/**
* The {@link WeakCounterTestStrategy} implementation.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class WeakCounterImplTestStrategy extends BaseCounterImplTest<WeakCounter> implements WeakCounterTestStrategy {
private final Supplier<Collection<CounterManager>> allCounterManagerSupplier;
public WeakCounterImplTestStrategy(Supplier<CounterManager> counterManagerSupplier,
Supplier<Collection<CounterManager>> allCounterManagerSupplier) {
super(counterManagerSupplier);
this.allCounterManagerSupplier = allCounterManagerSupplier;
}
@Override
public <L extends CounterListener> Handle<L> addListenerTo(WeakCounter counter, L logger) {
return counter.addListener(logger);
}
@Override
public WeakCounter defineAndCreateCounter(String counterName, long initialValue) {
final CounterManager counterManager = counterManagerSupplier.get();
assertTrue(counterManager
.defineCounter(counterName, builder(WEAK).initialValue(initialValue).concurrencyLevel(8).build()));
return counterManager.getWeakCounter(counterName);
}
@Override
public void add(WeakCounter counter, long delta, long result) {
awaitCounterOperation(counter.add(delta));
}
@Override
void remove(WeakCounter counter) {
awaitCounterOperation(counter.remove());
}
@Override
void assertCounterValue(WeakCounter counter, long value) {
assertEquals(value, counter.getValue());
}
@Override
void reset(WeakCounter counter) {
awaitCounterOperation(counter.reset());
}
@Override
List<CounterConfiguration> configurationsToTest() {
return singletonList(builder(WEAK).initialValue(1).concurrencyLevel(2).build());
}
@Override
void assertCounterNameAndConfiguration(String counterName, CounterConfiguration configuration) {
allCounterManagerSupplier.get().forEach(counterManager -> {
WeakCounter counter = counterManager.getWeakCounter(counterName);
assertEquals(counterName, counter.getName());
assertEquals(configuration, counter.getConfiguration());
});
}
}
| 2,943
| 34.047619
| 118
|
java
|
null |
infinispan-main/server/hotrod/src/test/java/org/infinispan/server/hotrod/counter/impl/TestWeakCounter.java
|
package org.infinispan.server.hotrod.counter.impl;
import static org.infinispan.server.hotrod.HotRodOperation.COUNTER_GET;
import static org.infinispan.server.hotrod.HotRodOperation.COUNTER_REMOVE;
import static org.infinispan.server.hotrod.HotRodOperation.COUNTER_RESET;
import java.util.concurrent.CompletableFuture;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterListener;
import org.infinispan.counter.api.Handle;
import org.infinispan.counter.api.SyncWeakCounter;
import org.infinispan.counter.api.WeakCounter;
import org.infinispan.counter.exception.CounterException;
import org.infinispan.server.hotrod.counter.op.CounterAddOp;
import org.infinispan.server.hotrod.counter.op.CounterOp;
import org.infinispan.server.hotrod.counter.response.CounterValueTestResponse;
import org.infinispan.server.hotrod.test.HotRodClient;
import org.infinispan.server.hotrod.test.TestErrorResponse;
import org.infinispan.server.hotrod.test.TestResponse;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* A {@link WeakCounter} implementation for Hot Rod server testing.
*
* @author Pedro Ruivo
* @since 9.2
*/
class TestWeakCounter implements WeakCounter {
private final String name;
private final CounterConfiguration configuration;
private final HotRodClient client;
private final TestCounterNotificationManager notificationManager;
TestWeakCounter(String name, CounterConfiguration configuration, HotRodClient client,
TestCounterNotificationManager notificationManager) {
this.name = name;
this.configuration = configuration;
this.client = client;
this.notificationManager = notificationManager;
}
@Override
public String getName() {
return name;
}
@Override
public long getValue() {
CounterOp op = new CounterOp(client.protocolVersion(), COUNTER_GET, name);
TestResponse response = client.execute(op);
switch (response.getStatus()) {
case Success:
return ((CounterValueTestResponse) response).getValue();
case ServerError:
throw new CounterException(((TestErrorResponse) response).msg);
default:
throw new CounterException("unknown response " + response);
}
}
@Override
public CompletableFuture<Void> add(long delta) {
CounterAddOp op = new CounterAddOp(client.protocolVersion(), name, delta);
return executeOp(op);
}
@Override
public CompletableFuture<Void> reset() {
CounterOp op = new CounterOp(client.protocolVersion(), COUNTER_RESET, name);
return executeOp(op);
}
@Override
public <T extends CounterListener> Handle<T> addListener(T listener) {
return notificationManager.register(name, listener);
}
@Override
public CounterConfiguration getConfiguration() {
return configuration;
}
@Override
public CompletableFuture<Void> remove() {
CounterOp op = new CounterOp(client.protocolVersion(), COUNTER_REMOVE, name);
client.execute(op);
return CompletableFutures.completedNull();
}
@Override
public SyncWeakCounter sync() {
throw new UnsupportedOperationException(); //no need for testing
}
private CompletableFuture<Void> executeOp(CounterOp op) {
TestResponse response = client.execute(op);
CompletableFuture<Void> future = new CompletableFuture<>();
switch (response.getStatus()) {
case Success:
future.complete(null);
break;
case OperationNotExecuted:
future.complete(null);
break;
case KeyDoesNotExist:
future.completeExceptionally(new IllegalStateException("Counter Not Found!"));
break;
case ServerError:
future.completeExceptionally(new CounterException(((TestErrorResponse) response).msg));
break;
default:
future.completeExceptionally(new Exception("unknown response " + response));
}
return future;
}
}
| 4,064
| 33.159664
| 99
|
java
|
null |
infinispan-main/server/hotrod/src/test/java/org/infinispan/server/hotrod/counter/impl/CounterManagerImplTestStrategy.java
|
package org.infinispan.server.hotrod.counter.impl;
import static java.lang.Math.abs;
import static org.infinispan.counter.api.CounterConfiguration.builder;
import static org.infinispan.counter.impl.Util.awaitCounterOperation;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.function.Supplier;
import org.infinispan.Cache;
import org.infinispan.counter.EmbeddedCounterManagerFactory;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterManager;
import org.infinispan.counter.api.CounterType;
import org.infinispan.counter.api.Storage;
import org.infinispan.counter.impl.CounterModuleLifecycle;
import org.infinispan.counter.impl.manager.CounterConfigurationManager;
import org.infinispan.globalstate.GlobalConfigurationManager;
import org.infinispan.globalstate.ScopedState;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.counter.CounterManagerTestStrategy;
import org.infinispan.util.logging.Log;
/**
* The {@link CounterManagerTestStrategy} implementation.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class CounterManagerImplTestStrategy implements CounterManagerTestStrategy {
private final Supplier<List<CounterManager>> allRemoteCounterManagerSupplier;
private final Supplier<Log> logSupplier;
private final Supplier<EmbeddedCacheManager> cacheManagerSupplier;
public CounterManagerImplTestStrategy(Supplier<List<CounterManager>> allRemoteCounterManagerSupplier,
Supplier<Log> logSupplier, Supplier<EmbeddedCacheManager> cacheManagerSupplier) {
this.allRemoteCounterManagerSupplier = allRemoteCounterManagerSupplier;
this.logSupplier = logSupplier;
this.cacheManagerSupplier = cacheManagerSupplier;
}
@Override
public void testWeakCounter(Method method) {
final Random random = generateRandom();
final String counterName = method.getName();
CounterConfiguration config = builder(CounterType.WEAK)
.initialValue(random.nextInt())
.storage(random.nextBoolean() ? Storage.VOLATILE : Storage.PERSISTENT)
.concurrencyLevel(abs(random.nextInt()))
.build();
doCreationTest(counterName, config);
}
@Override
public void testUnboundedStrongCounter(Method method) {
final Random random = generateRandom();
final String counterName = method.getName();
CounterConfiguration config = builder(CounterType.UNBOUNDED_STRONG)
.initialValue(random.nextInt())
.storage(random.nextBoolean() ? Storage.VOLATILE : Storage.PERSISTENT)
.build();
doCreationTest(counterName, config);
}
@Override
public void testUpperBoundedStrongCounter(Method method) {
final Random random = generateRandom();
final String counterName = method.getName();
CounterConfiguration config = builder(CounterType.BOUNDED_STRONG)
.initialValue(5)
.upperBound(15)
.storage(random.nextBoolean() ? Storage.VOLATILE : Storage.PERSISTENT)
.build();
doCreationTest(counterName, config);
}
@Override
public void testLowerBoundedStrongCounter(Method method) {
final Random random = generateRandom();
final String counterName = method.getName();
CounterConfiguration config = builder(CounterType.BOUNDED_STRONG)
.initialValue(15)
.lowerBound(5)
.storage(random.nextBoolean() ? Storage.VOLATILE : Storage.PERSISTENT)
.build();
doCreationTest(counterName, config);
}
@Override
public void testBoundedStrongCounter(Method method) {
final Random random = generateRandom();
final String counterName = method.getName();
CounterConfiguration config = builder(CounterType.BOUNDED_STRONG)
.initialValue(15)
.lowerBound(5)
.upperBound(20)
.storage(random.nextBoolean() ? Storage.VOLATILE : Storage.PERSISTENT)
.build();
doCreationTest(counterName, config);
}
@Override
public void testUndefinedCounter() {
CounterManager counterManager = getTestedCounterManager();
assertFalse(counterManager.isDefined("not-defined-counter"));
assertEquals(null, counterManager.getConfiguration("not-defined-counter"));
}
@Override
public void testRemove(Method method) {
//we need to cleanup other tests counters from the caches because of cache.size()
clearCaches();
final Random random = generateRandom();
final String counterName = method.getName();
final CounterManager counterManager = getTestedCounterManager();
CounterConfiguration config = builder(CounterType.UNBOUNDED_STRONG).initialValue(random.nextLong()).build();
assertTrue(counterManager.defineCounter(counterName, config));
awaitCounterOperation(counterManager.getStrongCounter(counterName).addAndGet(10));
EmbeddedCacheManager cacheManager = cacheManagerSupplier.get();
Cache<?, ?> cache = cacheManager.getCache(CounterModuleLifecycle.COUNTER_CACHE_NAME);
assertEquals(1, cache.size());
counterManager.remove(counterName);
assertEquals(0, cache.size());
}
@Override
public void testGetCounterNames(Method method) {
//we need to cleanup other tests counters from the caches.
clearCaches();
final Random random = generateRandom();
final String counterNamePrefix = method.getName();
final CounterManager counterManager = getTestedCounterManager();
final int numCounters = random.nextInt(10) + 1;
final List<CounterConfiguration> configList = new ArrayList<>(numCounters);
final Set<String> counterSet = new HashSet<>();
//adds some randomness to the test by adding 1 to 10 counters
for (int i = 0; i < numCounters; ++i) {
CounterConfiguration config = builder(CounterType.valueOf(random.nextInt(3))).initialValue(random.nextLong())
.build();
assertTrue(counterManager.defineCounter(counterNamePrefix + i, config));
configList.add(config);
counterSet.add(counterNamePrefix + i);
}
Set<String> counterNames = new HashSet<>(counterManager.getCounterNames());
assertEquals(counterSet, counterNames);
for (int i = 0; i < numCounters; ++i) {
final String counterName = counterNamePrefix + i;
assertTrue(counterNames.contains(counterName));
CounterConfiguration config = configList.get(i);
CounterConfiguration storedConfig = config.type() == CounterType.WEAK ?
counterManager.getWeakCounter(counterName).getConfiguration() :
counterManager.getStrongCounter(counterName).getConfiguration();
assertEquals(config, storedConfig);
}
}
private Random generateRandom() {
final long seed = System.nanoTime();
logSupplier.get().debugf("Using SEED: '%d'", seed);
return new Random(seed);
}
private void doCreationTest(String name, CounterConfiguration config) {
List<CounterManager> remoteCounterManagers = allRemoteCounterManagerSupplier.get();
assertTrue(remoteCounterManagers.get(0).defineCounter(name, config));
remoteCounterManagers.forEach(cm -> assertFalse(cm.defineCounter(name, builder(CounterType.WEAK).build())));
remoteCounterManagers.forEach(cm -> assertTrue(cm.isDefined(name)));
remoteCounterManagers.forEach(cm -> assertEquals(config, cm.getConfiguration(name)));
//test single embedded counter manager to check if everything is correctly stored
EmbeddedCacheManager cacheManager = cacheManagerSupplier.get();
CounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager(cacheManager);
assertTrue(counterManager.isDefined(name));
assertEquals(config, counterManager.getConfiguration(name));
}
private CounterManager getTestedCounterManager() {
return allRemoteCounterManagerSupplier.get().get(0);
}
private void clearCaches() {
//we need to cleanup other tests counter from the caches.
EmbeddedCacheManager cacheManager = cacheManagerSupplier.get();
cacheManager.getCache(CounterModuleLifecycle.COUNTER_CACHE_NAME).clear();
cacheManager.<ScopedState, Object>getCache(GlobalConfigurationManager.CONFIG_STATE_CACHE_NAME).keySet().removeIf(o -> CounterConfigurationManager.COUNTER_SCOPE.equals(o.getScope()));
}
}
| 8,788
| 41.873171
| 188
|
java
|
null |
infinispan-main/server/hotrod/src/test/java/org/infinispan/server/hotrod/counter/impl/TestCounterNotificationManager.java
|
package org.infinispan.server.hotrod.counter.impl;
import static org.infinispan.server.hotrod.counter.op.CounterListenerOp.createListener;
import static org.infinispan.server.hotrod.counter.op.CounterListenerOp.removeListener;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import org.infinispan.commons.marshall.WrappedByteArray;
import org.infinispan.counter.api.CounterEvent;
import org.infinispan.counter.api.CounterListener;
import org.infinispan.counter.api.Handle;
import org.infinispan.counter.exception.CounterException;
import org.infinispan.server.hotrod.counter.op.CounterListenerOp;
import org.infinispan.server.hotrod.test.HotRodClient;
import org.infinispan.server.hotrod.test.TestResponse;
/**
* A test client notification manager.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class TestCounterNotificationManager {
private final WrappedByteArray listenerId;
private final Map<String, List<UserListener<?>>> userListenerList;
private final HotRodClient client;
TestCounterNotificationManager(HotRodClient client) {
this.client = client;
byte[] listenerId = new byte[16];
ThreadLocalRandom.current().nextBytes(listenerId);
this.listenerId = new WrappedByteArray(listenerId);
userListenerList = new ConcurrentHashMap<>();
}
public WrappedByteArray getListenerId() {
return listenerId;
}
public void accept(TestCounterEventResponse event) {
List<UserListener<?>> list = userListenerList.get(event.getCounterName());
list.parallelStream().forEach(userListener -> userListener.trigger(event.getCounterEvent()));
}
public <T extends CounterListener> Handle<T> register(String counterName, T listener) {
UserListener<T> ul = new UserListener<>(listener, userListener -> remove(counterName, userListener));
userListenerList.compute(counterName, (s, userListeners) -> add(s, userListeners, ul));
return ul;
}
public void start() {
client.registerCounterNotificationManager(this);
}
private List<UserListener<?>> add(String counterName, List<UserListener<?>> list, UserListener<?> listener) {
if (list == null) {
CounterListenerOp op = createListener(client.protocolVersion(), counterName, listenerId.getBytes());
TestResponse response = client.execute(op);
switch (response.getStatus()) {
case Success:
break;
case OperationNotExecuted:
break;
case KeyDoesNotExist:
throw new CounterException("Counter " + counterName + " doesn't exist");
default:
throw new IllegalStateException("Unknown status " + response.getStatus());
}
list = new CopyOnWriteArrayList<>();
}
list.add(listener);
return list;
}
private void remove(String counterName, UserListener<?> listener) {
userListenerList.computeIfPresent(counterName, (name, list) -> {
list.remove(listener);
if (list.isEmpty()) {
CounterListenerOp op = removeListener(client.protocolVersion(), counterName, listenerId.getBytes());
TestResponse response = client.execute(op);
switch (response.getStatus()) {
case Success:
break;
case OperationNotExecuted:
break;
case KeyDoesNotExist:
throw new CounterException("Counter " + counterName + " doesn't exist");
default:
throw new IllegalStateException("Unknown status " + response.getStatus());
}
return null;
}
return list;
});
}
private static class UserListener<T extends CounterListener> implements Handle<T> {
private final T listener;
private final Consumer<UserListener<?>> removeConsumer;
private UserListener(T listener,
Consumer<UserListener<?>> removeConsumer) {
this.listener = listener;
this.removeConsumer = removeConsumer;
}
@Override
public T getCounterListener() {
return listener;
}
@Override
public void remove() {
removeConsumer.accept(this);
}
void trigger(CounterEvent event) {
try {
listener.onUpdate(event);
} catch (Exception e) {
//ignored
}
}
}
}
| 4,594
| 33.548872
| 112
|
java
|
null |
infinispan-main/server/hotrod/src/test/java/org/infinispan/server/hotrod/counter/op/CounterOp.java
|
package org.infinispan.server.hotrod.counter.op;
import static org.infinispan.server.hotrod.transport.ExtendedByteBuf.writeRangedBytes;
import org.infinispan.server.hotrod.HotRodOperation;
import org.infinispan.server.hotrod.test.Op;
import io.netty.buffer.ByteBuf;
/**
* A base counter test operation.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class CounterOp extends Op {
private final String counterName;
public CounterOp(byte version, HotRodOperation operation, String counterName) {
super(0xA0, version, (byte) operation.getRequestOpCode(), "", null, 0, 0, null, 0, 0, (byte) 0, 0);
this.counterName = counterName;
}
public void writeTo(ByteBuf buffer) {
writeRangedBytes(counterName.getBytes(), buffer);
}
}
| 764
| 25.37931
| 105
|
java
|
null |
infinispan-main/server/hotrod/src/test/java/org/infinispan/server/hotrod/counter/op/CounterSetOp.java
|
package org.infinispan.server.hotrod.counter.op;
import static org.infinispan.server.hotrod.HotRodOperation.COUNTER_GET_AND_SET;
import io.netty.buffer.ByteBuf;
public class CounterSetOp extends CounterOp {
private final long value;
public CounterSetOp(byte version, String counterName, long value) {
super(version, COUNTER_GET_AND_SET, counterName);
this.value = value;
}
@Override
public void writeTo(ByteBuf buffer) {
super.writeTo(buffer);
buffer.writeLong(value);
}
}
| 521
| 22.727273
| 79
|
java
|
null |
infinispan-main/server/hotrod/src/test/java/org/infinispan/server/hotrod/counter/op/CounterCompareAndSwapOp.java
|
package org.infinispan.server.hotrod.counter.op;
import static org.infinispan.server.hotrod.HotRodOperation.COUNTER_CAS;
import org.infinispan.server.hotrod.HotRodOperation;
import io.netty.buffer.ByteBuf;
/**
* A test operation for {@link HotRodOperation#COUNTER_CAS} operation.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class CounterCompareAndSwapOp extends CounterOp {
private final long expected;
private final long update;
public CounterCompareAndSwapOp(byte version, String counterName, long expected, long update) {
super(version, COUNTER_CAS, counterName);
this.expected = expected;
this.update = update;
}
@Override
public void writeTo(ByteBuf buffer) {
super.writeTo(buffer);
buffer.writeLong(expected);
buffer.writeLong(update);
}
}
| 818
| 23.818182
| 97
|
java
|
null |
infinispan-main/server/hotrod/src/test/java/org/infinispan/server/hotrod/counter/op/CreateCounterOp.java
|
package org.infinispan.server.hotrod.counter.op;
import static org.infinispan.counter.util.EncodeUtil.encodeConfiguration;
import static org.infinispan.server.hotrod.HotRodOperation.COUNTER_CREATE;
import static org.infinispan.server.hotrod.transport.ExtendedByteBuf.writeUnsignedInt;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.server.hotrod.HotRodOperation;
import io.netty.buffer.ByteBuf;
/**
* A test {@link HotRodOperation#COUNTER_CREATE} operation.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class CreateCounterOp extends CounterOp {
private final CounterConfiguration configuration;
public CreateCounterOp(byte version, String counterName, CounterConfiguration configuration) {
super(version, COUNTER_CREATE, counterName);
this.configuration = configuration;
}
@Override
public void writeTo(ByteBuf buffer) {
super.writeTo(buffer);
encodeConfiguration(configuration, buffer::writeByte, buffer::writeLong,
value -> writeUnsignedInt(value, buffer));
}
}
| 1,063
| 30.294118
| 97
|
java
|
null |
infinispan-main/server/hotrod/src/test/java/org/infinispan/server/hotrod/counter/op/CounterAddOp.java
|
package org.infinispan.server.hotrod.counter.op;
import static org.infinispan.server.hotrod.HotRodOperation.COUNTER_ADD_AND_GET;
import org.infinispan.server.hotrod.HotRodOperation;
import io.netty.buffer.ByteBuf;
/**
* Test operation for {@link HotRodOperation#COUNTER_ADD_AND_GET} operation.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class CounterAddOp extends CounterOp {
private final long value;
public CounterAddOp(byte version, String counterName, long value) {
super(version, COUNTER_ADD_AND_GET, counterName);
this.value = value;
}
@Override
public void writeTo(ByteBuf buffer) {
super.writeTo(buffer);
buffer.writeLong(value);
}
}
| 700
| 22.366667
| 79
|
java
|
null |
infinispan-main/server/hotrod/src/test/java/org/infinispan/server/hotrod/counter/op/CounterListenerOp.java
|
package org.infinispan.server.hotrod.counter.op;
import org.infinispan.server.hotrod.HotRodOperation;
import org.infinispan.server.hotrod.transport.ExtendedByteBuf;
import io.netty.buffer.ByteBuf;
/**
* Test operation for {@link HotRodOperation#COUNTER_ADD_LISTENER} and {@link HotRodOperation#COUNTER_REMOVE_LISTENER}
* operation.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class CounterListenerOp extends CounterOp {
private final byte[] listenerId;
private CounterListenerOp(byte version, HotRodOperation operation,
String counterName, byte[] listenerId) {
super(version, operation, counterName);
this.listenerId = listenerId;
}
public static CounterListenerOp createListener(byte version, String counterName, byte[] id) {
return new CounterListenerOp(version, HotRodOperation.COUNTER_ADD_LISTENER, counterName, id);
}
public static CounterListenerOp removeListener(byte version, String counterName, byte[] id) {
return new CounterListenerOp(version, HotRodOperation.COUNTER_REMOVE_LISTENER, counterName, id);
}
@Override
public void writeTo(ByteBuf buffer) {
super.writeTo(buffer);
ExtendedByteBuf.writeRangedBytes(listenerId, buffer);
}
}
| 1,237
| 30.74359
| 118
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/Constants.java
|
package org.infinispan.server.hotrod;
/**
* Constant values
*
* @author Galder Zamarreño
* @since 5.1
*/
public class Constants {
private Constants() {
}
static final public byte MAGIC_REQ = (byte) 0xA0;
static final public short MAGIC_RES = 0xA1;
static final public byte DEFAULT_CONSISTENT_HASH_VERSION_1x = 2;
static final public byte DEFAULT_CONSISTENT_HASH_VERSION = 3;
static final public byte INTELLIGENCE_BASIC = 0x01;
static final public byte INTELLIGENCE_TOPOLOGY_AWARE = 0x02;
static final public byte INTELLIGENCE_HASH_DISTRIBUTION_AWARE = 0x03;
static final public byte INFINITE_LIFESPAN = 0x01;
static final public byte INFINITE_MAXIDLE = 0x02;
static final public int DEFAULT_TOPOLOGY_ID = -1;
}
| 758
| 26.107143
| 72
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/CounterRequestProcessor.java
|
package org.infinispan.server.hotrod;
import static org.infinispan.commons.util.concurrent.CompletableFutures.extractException;
import java.util.Collection;
import java.util.concurrent.Executor;
import javax.security.auth.Subject;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.exception.CounterNotFoundException;
import org.infinispan.counter.exception.CounterOutOfBoundsException;
import org.infinispan.counter.impl.CounterModuleLifecycle;
import org.infinispan.counter.impl.manager.EmbeddedCounterManager;
import org.infinispan.counter.impl.manager.InternalCounterAdmin;
import org.infinispan.server.hotrod.counter.listener.ClientCounterManagerNotificationManager;
import org.infinispan.server.hotrod.counter.listener.ListenerOperationStatus;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
class CounterRequestProcessor extends BaseRequestProcessor {
private final ClientCounterManagerNotificationManager notificationManager;
private final EmbeddedCounterManager counterManager;
CounterRequestProcessor(Channel channel, EmbeddedCounterManager counterManager, Executor executor, HotRodServer server) {
super(channel, executor, server);
this.counterManager = counterManager;
notificationManager = server.getClientCounterNotificationManager();
}
private EmbeddedCounterManager counterManager(HotRodHeader header) {
header.cacheName = CounterModuleLifecycle.COUNTER_CACHE_NAME;
return counterManager;
}
void removeCounterListener(HotRodHeader header, Subject subject, String counterName, byte[] listenerId) {
executor.execute(() -> removeCounterListenerInternal(header, counterName, listenerId));
}
private void removeCounterListenerInternal(HotRodHeader header, String counterName, byte[] listenerId) {
try {
writeResponse(header, createResponseFrom(header, notificationManager
.removeCounterListener(listenerId, counterName)));
} catch (Throwable t) {
writeException(header, t);
}
}
void addCounterListener(HotRodHeader header, Subject subject, String counterName, byte[] listenerId) {
executor.execute(() -> addCounterListenerInternal(header, counterName, listenerId));
}
private void addCounterListenerInternal(HotRodHeader header, String counterName, byte[] listenerId) {
try {
writeResponse(header, createResponseFrom(header, notificationManager
.addCounterListener(listenerId, header.getVersion(), counterName, channel, header.encoder())));
} catch (Throwable t) {
writeException(header, t);
}
}
void getCounterNames(HotRodHeader header, Subject subject) {
Collection<String> counterNames = counterManager(header).getCounterNames();
writeResponse(header, header.encoder().counterNamesResponse(header, server, channel, counterNames));
}
void counterRemove(HotRodHeader header, Subject subject, String counterName) {
counterManager(header).removeAsync(counterName, true)
.whenComplete((___, throwable) -> voidResultHandler(header, throwable));
}
void counterCompareAndSwap(HotRodHeader header, Subject subject, String counterName, long expect, long update) {
counterManager(header).getStrongCounterAsync(counterName)
.thenCompose(strongCounter -> strongCounter.compareAndSwap(expect, update))
.whenComplete((returnValue, throwable) -> longResultHandler(header, returnValue, throwable));
}
void counterGet(HotRodHeader header, Subject subject, String counterName) {
counterManager(header).getOrCreateAsync(counterName)
.thenCompose(InternalCounterAdmin::value)
.whenComplete((value, throwable) -> longResultHandler(header, value, throwable));
}
void counterReset(HotRodHeader header, Subject subject, String counterName) {
counterManager(header).getOrCreateAsync(counterName)
.thenCompose(InternalCounterAdmin::reset)
.whenComplete((unused, throwable) -> voidResultHandler(header, throwable));
}
void counterAddAndGet(HotRodHeader header, Subject subject, String counterName, long value) {
counterManager(header).getOrCreateAsync(counterName)
.thenAccept(counter -> {
if (counter.isWeakCounter()) {
counter.asWeakCounter().add(value).whenComplete((___, t) -> longResultHandler(header, 0L, t));
} else {
counter.asStrongCounter().addAndGet(value).whenComplete((rv, t) -> longResultHandler(header, rv, t));
}
})
.exceptionally(throwable -> {
checkCounterThrowable(header, throwable);
return null;
});
}
void counterSet(HotRodHeader header, Subject subject, String counterName, long value) {
counterManager(header).getStrongCounterAsync(counterName)
.thenCompose(strongCounter -> strongCounter.getAndSet(value))
.whenComplete((returnValue, throwable) -> longResultHandler(header, returnValue, throwable));
}
void getCounterConfiguration(HotRodHeader header, Subject subject, String counterName) {
counterManager(header).getConfigurationAsync(counterName)
.whenComplete((configuration, throwable) -> handleGetCounterConfiguration(header, configuration, throwable));
}
private void handleGetCounterConfiguration(HotRodHeader header, CounterConfiguration configuration, Throwable throwable) {
if (throwable != null) {
checkCounterThrowable(header, throwable);
} else {
ByteBuf response = configuration == null ? missingCounterResponse(header) :
header.encoder().counterConfigurationResponse(header, server, channel, configuration);
writeResponse(header, response);
}
}
void isCounterDefined(HotRodHeader header, Subject subject, String counterName) {
counterManager(header).isDefinedAsync(counterName).whenComplete((value, throwable) -> booleanResultHandler(header, value, throwable));
}
void createCounter(HotRodHeader header, Subject subject, String counterName, CounterConfiguration configuration) {
counterManager(header).defineCounterAsync(counterName, configuration)
.whenComplete((value, throwable) -> booleanResultHandler(header, value, throwable));
}
private ByteBuf createResponseFrom(HotRodHeader header, ListenerOperationStatus status) {
switch (status) {
case OK:
return header.encoder().emptyResponse(header, server, channel, OperationStatus.OperationNotExecuted);
case OK_AND_CHANNEL_IN_USE:
return header.encoder().emptyResponse(header, server, channel, OperationStatus.Success);
case COUNTER_NOT_FOUND:
return missingCounterResponse(header);
default:
throw new IllegalStateException();
}
}
private void checkCounterThrowable(HotRodHeader header, Throwable throwable) {
Throwable cause = extractException(throwable);
if (cause instanceof CounterOutOfBoundsException) {
writeResponse(header, header.encoder().emptyResponse(header, server, channel, OperationStatus.NotExecutedWithPrevious));
} else if (cause instanceof CounterNotFoundException) {
writeResponse(header, missingCounterResponse(header));
} else {
writeException(header, cause);
}
}
private ByteBuf missingCounterResponse(HotRodHeader header) {
return header.encoder().emptyResponse(header, server, channel, OperationStatus.KeyDoesNotExist);
}
private void booleanResultHandler(HotRodHeader header, Boolean value, Throwable throwable) {
if (throwable != null) {
checkCounterThrowable(header, throwable);
} else {
OperationStatus status = value ? OperationStatus.Success : OperationStatus.OperationNotExecuted;
writeResponse(header, header.encoder().emptyResponse(header, server, channel, status));
}
}
private void longResultHandler(HotRodHeader header, Long value, Throwable throwable) {
if (throwable != null) {
checkCounterThrowable(header, throwable);
} else {
writeResponse(header, header.encoder().longResponse(header, server, channel, value));
}
}
private void voidResultHandler(HotRodHeader header, Throwable throwable) {
if (throwable != null) {
checkCounterThrowable(header, throwable);
} else {
writeResponse(header, header.encoder().emptyResponse(header, server, channel, OperationStatus.Success));
}
}
}
| 8,660
| 44.584211
| 140
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/Events.java
|
package org.infinispan.server.hotrod;
import java.util.concurrent.CompletableFuture;
import org.infinispan.commons.util.Util;
import org.infinispan.server.hotrod.transport.ExtendedByteBuf;
import io.netty.buffer.ByteBuf;
/**
* @author Galder Zamarreño
*/
class Events {
abstract static class Event {
protected final byte version;
protected final long messageId;
protected final HotRodOperation op;
protected final byte[] listenerId;
protected final boolean isRetried;
protected final byte marker;
// Delays the operation that generated this event
protected final CompletableFuture<Void> eventFuture;
protected Event(byte version, long messageId, HotRodOperation op, byte[] listenerId, boolean isRetried, byte marker,
CompletableFuture<Void> eventFuture) {
this.version = version;
this.messageId = messageId;
this.op = op;
this.listenerId = listenerId;
this.isRetried = isRetried;
this.marker = marker;
this.eventFuture = eventFuture;
}
abstract void writeEvent(ByteBuf buf);
void defaultEvent(ByteBuf buf) {
buf.writeByte(marker); // custom marker
buf.writeByte(isRetried ? 1 : 0);
}
}
static class KeyEvent extends Event {
protected final byte[] key;
protected KeyEvent(byte version, long messageId, HotRodOperation op, byte[] listenerId, boolean isRetried,
byte[] key, CompletableFuture<Void> eventFuture) {
super(version, messageId, op, listenerId, isRetried, (byte) 0, eventFuture);
this.key = key;
}
@Override
public String toString() {
return "KeyEvent{" +
"version=" + version +
", messageId=" + messageId +
", op=" + op +
", listenerId=" + Util.printArray(listenerId, false) +
", isRetried=" + isRetried +
", key=" + Util.toStr(key) +
'}';
}
@Override
void writeEvent(ByteBuf buf) {
defaultEvent(buf);
ExtendedByteBuf.writeRangedBytes(key, buf);
}
}
static class KeyWithVersionEvent extends Event {
protected final byte[] key;
protected final long dataVersion;
protected KeyWithVersionEvent(byte version, long messageId, HotRodOperation op, byte[] listenerId, boolean isRetried,
byte[] key, long dataVersion, CompletableFuture<Void> eventFuture) {
super(version, messageId, op, listenerId, isRetried, (byte) 0, eventFuture);
this.key = key;
this.dataVersion = dataVersion;
}
@Override
public String toString() {
return "KeyWithVersionEvent{" +
"version=" + version +
", messageId=" + messageId +
", op=" + op +
", listenerId=" + Util.printArray(listenerId, false) +
", isRetried=" + isRetried +
", key=" + Util.toStr(key) +
", dataVersion=" + dataVersion +
'}';
}
@Override
void writeEvent(ByteBuf buf) {
defaultEvent(buf);
ExtendedByteBuf.writeRangedBytes(key, buf);
buf.writeLong(dataVersion);
}
}
static class CustomEvent extends Event {
protected final byte[] eventData;
protected CustomEvent(byte version, long messageId, HotRodOperation op, byte[] listenerId, boolean isRetried,
byte[] eventData, CompletableFuture<Void> eventFuture) {
super(version, messageId, op, listenerId, isRetried, (byte) 1, eventFuture);
this.eventData = eventData;
}
@Override
public String toString() {
return "CustomEvent{" +
"version=" + version +
", messageId=" + messageId +
", op=" + op +
", listenerId=" + Util.printArray(listenerId, false) +
", isRetried=" + isRetried +
", event=" + Util.toStr(eventData) +
'}';
}
@Override
void writeEvent(ByteBuf buf) {
defaultEvent(buf);
ExtendedByteBuf.writeRangedBytes(eventData, buf);
}
}
static class CustomRawEvent extends Event {
protected final byte[] eventData;
protected CustomRawEvent(byte version, long messageId, HotRodOperation op, byte[] listenerId, boolean isRetried,
byte[] eventData, CompletableFuture<Void> eventFuture) {
super(version, messageId, op, listenerId, isRetried, (byte) 2, eventFuture);
this.eventData = eventData;
}
@Override
public String toString() {
return "CustomRawEvent{" +
"version=" + version +
", messageId=" + messageId +
", op=" + op +
", listenerId=" + Util.printArray(listenerId, false) +
", isRetried=" + isRetried +
", event=" + Util.toStr(eventData) +
'}';
}
@Override
void writeEvent(ByteBuf buf) {
defaultEvent(buf);
ExtendedByteBuf.writeRangedBytes(eventData, buf);
}
}
}
| 5,270
| 31.73913
| 123
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/AccessLoggingHeader.java
|
package org.infinispan.server.hotrod;
import java.time.temporal.Temporal;
import javax.security.auth.Subject;
import org.infinispan.security.Security;
public class AccessLoggingHeader extends HotRodHeader {
public final Object principalName;
public final Object key;
public final int requestBytes;
public final Temporal requestStart;
public AccessLoggingHeader(HotRodHeader header, Subject subject, Object key, int requestBytes, Temporal requestStart) {
super(header);
this.principalName = subject != null ? Security.getSubjectUserPrincipal(subject).getName() : null;
this.key = key;
this.requestBytes = requestBytes;
this.requestStart = requestStart;
}
}
| 709
| 29.869565
| 122
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/ProtocolFlag.java
|
package org.infinispan.server.hotrod;
/**
* @author Galder Zamarreño
*/
public enum ProtocolFlag {
NoFlag(0),
ForceReturnPreviousValue(1),
DefaultLifespan(1 << 1),
DefaultMaxIdle(1 << 2),
SkipCacheLoader(1 << 3),
SkipIndexing(1 << 4),
SkipListenerNotification(1 << 5);
private final byte value;
ProtocolFlag(int value) {
this.value = (byte) value;
}
public byte getValue() {
return value;
}
}
| 447
| 16.92
| 37
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/MissingFactoryException.java
|
package org.infinispan.server.hotrod;
/**
* Exception thrown when a named factory is chosen that doesn't exist
*
* @author wburns
* @since 9.0
*/
public class MissingFactoryException extends IllegalArgumentException {
public MissingFactoryException(String reason) {
super(reason);
}
}
| 303
| 20.714286
| 71
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/LifecycleCallbacks.java
|
package org.infinispan.server.hotrod;
import static org.infinispan.server.core.ExternalizerIds.CACHE_XID;
import static org.infinispan.server.core.ExternalizerIds.CLIENT_ADDRESS;
import static org.infinispan.server.core.ExternalizerIds.COMPLETE_FUNCTION;
import static org.infinispan.server.core.ExternalizerIds.CONDITIONAL_MARK_ROLLBACK_FUNCTION;
import static org.infinispan.server.core.ExternalizerIds.CREATE_STATE_FUNCTION;
import static org.infinispan.server.core.ExternalizerIds.DECISION_FUNCTION;
import static org.infinispan.server.core.ExternalizerIds.ITERATION_FILTER;
import static org.infinispan.server.core.ExternalizerIds.KEY_VALUE_VERSION_CONVERTER;
import static org.infinispan.server.core.ExternalizerIds.KEY_VALUE_WITH_PREVIOUS_CONVERTER;
import static org.infinispan.server.core.ExternalizerIds.MULTI_HOMED_SERVER_ADDRESS;
import static org.infinispan.server.core.ExternalizerIds.PREPARED_FUNCTION;
import static org.infinispan.server.core.ExternalizerIds.PREPARING_FUNCTION;
import static org.infinispan.server.core.ExternalizerIds.SINGLE_HOMED_SERVER_ADDRESS;
import static org.infinispan.server.core.ExternalizerIds.TX_STATE;
import static org.infinispan.server.core.ExternalizerIds.XID_PREDICATE;
import java.util.EnumSet;
import java.util.Map;
import org.infinispan.Cache;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.factories.annotations.InfinispanModule;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.lifecycle.ModuleLifecycle;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.server.hotrod.event.KeyValueWithPreviousEventConverterExternalizer;
import org.infinispan.server.hotrod.tx.ServerTransactionOriginatorChecker;
import org.infinispan.server.hotrod.tx.table.CacheXid;
import org.infinispan.server.hotrod.tx.table.ClientAddress;
import org.infinispan.server.hotrod.tx.table.GlobalTxTable;
import org.infinispan.server.hotrod.tx.table.PerCacheTxTable;
import org.infinispan.server.hotrod.tx.table.TxState;
import org.infinispan.server.hotrod.tx.table.functions.ConditionalMarkAsRollbackFunction;
import org.infinispan.server.hotrod.tx.table.functions.CreateStateFunction;
import org.infinispan.server.hotrod.tx.table.functions.PreparingDecisionFunction;
import org.infinispan.server.hotrod.tx.table.functions.SetCompletedTransactionFunction;
import org.infinispan.server.hotrod.tx.table.functions.SetDecisionFunction;
import org.infinispan.server.hotrod.tx.table.functions.SetPreparedFunction;
import org.infinispan.server.hotrod.tx.table.functions.XidPredicate;
import org.infinispan.server.iteration.IterationFilter;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.impl.TransactionOriginatorChecker;
import net.jcip.annotations.GuardedBy;
/**
* Module lifecycle callbacks implementation that enables module specific {@link AdvancedExternalizer} implementations
* to be registered.
*
* @author Galder Zamarreño
* @since 5.0
*/
@InfinispanModule(name = "server-hotrod", requiredModules = "core")
public class LifecycleCallbacks implements ModuleLifecycle {
/**
* Cache name to store the global transaction table. It contains the state of the client transactions.
*/
private static final String GLOBAL_TX_TABLE_CACHE_NAME = "org.infinispan.CLIENT_SERVER_TX_TABLE";
@GuardedBy("this")
private boolean registered = false;
private GlobalComponentRegistry globalComponentRegistry;
private GlobalConfiguration globalCfg;
@Override
public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalCfg) {
this.globalComponentRegistry = gcr;
this.globalCfg = globalCfg;
Map<Integer, AdvancedExternalizer<?>> externalizers = globalCfg.serialization().advancedExternalizers();
externalizers.put(SINGLE_HOMED_SERVER_ADDRESS, new SingleHomedServerAddress.Externalizer());
externalizers.put(MULTI_HOMED_SERVER_ADDRESS, new MultiHomedServerAddress.Externalizer());
externalizers.put(KEY_VALUE_VERSION_CONVERTER, new KeyValueVersionConverter.Externalizer());
externalizers.put(KEY_VALUE_WITH_PREVIOUS_CONVERTER, new KeyValueWithPreviousEventConverterExternalizer());
externalizers.put(ITERATION_FILTER, new IterationFilter.IterationFilterExternalizer());
externalizers.put(TX_STATE, TxState.EXTERNALIZER);
externalizers.put(CACHE_XID, CacheXid.EXTERNALIZER);
externalizers.put(CLIENT_ADDRESS, ClientAddress.EXTERNALIZER);
externalizers.put(CREATE_STATE_FUNCTION, CreateStateFunction.EXTERNALIZER);
externalizers.put(PREPARING_FUNCTION, PreparingDecisionFunction.EXTERNALIZER);
externalizers.put(COMPLETE_FUNCTION, SetCompletedTransactionFunction.EXTERNALIZER);
externalizers.put(DECISION_FUNCTION, SetDecisionFunction.EXTERNALIZER);
externalizers.put(PREPARED_FUNCTION, SetPreparedFunction.EXTERNALIZER);
externalizers.put(XID_PREDICATE, XidPredicate.EXTERNALIZER);
externalizers.put(CONDITIONAL_MARK_ROLLBACK_FUNCTION, ConditionalMarkAsRollbackFunction.EXTERNALIZER);
registerGlobalTxTable();
}
@Override
public void cacheManagerStarted(GlobalComponentRegistry gcr) {
// It's too late to register components here, internal caches have already started
}
@Override
public void cacheStarting(ComponentRegistry cr, Configuration configuration, String cacheName) {
registerServerTransactionTable(cr, cacheName);
}
/**
* Registers the {@link PerCacheTxTable} to a transactional cache.
*/
private void registerServerTransactionTable(ComponentRegistry componentRegistry, String cacheName) {
//skip for global tx table and non-transactional cache
if (GLOBAL_TX_TABLE_CACHE_NAME.equals(cacheName) ||
!componentRegistry.getComponent(Configuration.class).transaction().transactionMode().isTransactional()) {
return;
}
EmbeddedCacheManager cacheManager = globalComponentRegistry.getComponent(EmbeddedCacheManager.class);
createGlobalTxTable(cacheManager);
// TODO We need a way for a module to install a factory before the default implementation is instantiated
BasicComponentRegistry basicComponentRegistry = componentRegistry.getComponent(BasicComponentRegistry.class);
basicComponentRegistry.replaceComponent(PerCacheTxTable.class.getName(), new PerCacheTxTable(cacheManager.getAddress()), true);
basicComponentRegistry.replaceComponent(TransactionOriginatorChecker.class.getName(), new ServerTransactionOriginatorChecker(), true);
componentRegistry.rewire();
}
/**
* Creates the global transaction internal cache.
*/
private void registerGlobalTxTable() {
InternalCacheRegistry registry = globalComponentRegistry.getComponent(InternalCacheRegistry.class);
ConfigurationBuilder builder = new ConfigurationBuilder();
//we can't lose transactions. distributed cache can lose data is num_owner nodes crash at the same time
// If this cache is changed from REPL/LOCAL it will also become blocking - and the blockhound exception in
// ServerHotrodBlockHoundIntegration will no longer be correct
builder.clustering().cacheMode(globalCfg.isClustered() ?
CacheMode.REPL_SYNC :
CacheMode.LOCAL);
builder.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL);
//persistent? should we keep the transaction after restart?
registry.registerInternalCache(GLOBAL_TX_TABLE_CACHE_NAME, builder.build(),
EnumSet.noneOf(InternalCacheRegistry.Flag.class));
}
private synchronized void createGlobalTxTable(EmbeddedCacheManager cacheManager) {
if (!registered) {
Cache<CacheXid, TxState> cache = cacheManager.getCache(GLOBAL_TX_TABLE_CACHE_NAME);
GlobalTxTable txTable = new GlobalTxTable(cache, globalComponentRegistry);
globalComponentRegistry.registerComponent(txTable, GlobalTxTable.class);
registered = true;
}
}
}
| 8,437
| 52.745223
| 140
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/TransactionRequestProcessor.java
|
package org.infinispan.server.hotrod;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Executor;
import javax.security.auth.Subject;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.container.versioning.VersionGenerator;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.server.hotrod.tracing.HotRodTelemetryService;
import org.infinispan.server.hotrod.tx.PrepareCoordinator;
import org.infinispan.server.hotrod.tx.operation.CommitTransactionOperation;
import org.infinispan.server.hotrod.tx.operation.RollbackTransactionOperation;
import org.infinispan.server.hotrod.tx.table.GlobalTxTable;
import org.infinispan.server.hotrod.tx.table.TxState;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.infinispan.util.concurrent.IsolationLevel;
import org.infinispan.util.logging.LogFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
class TransactionRequestProcessor extends CacheRequestProcessor {
private static final Log log = LogFactory.getLog(TransactionRequestProcessor.class, Log.class);
TransactionRequestProcessor(Channel channel, Executor executor, HotRodServer server, HotRodTelemetryService telemetryService) {
super(channel, executor, server, telemetryService);
}
private void writeTransactionResponse(HotRodHeader header, int value) {
writeResponse(header, createTransactionResponse(header, value));
}
/**
* Handles a rollback request from a client.
*/
void rollbackTransaction(HotRodHeader header, Subject subject, XidImpl xid) {
RollbackTransactionOperation operation = new RollbackTransactionOperation(header, server, subject, xid,
this::writeTransactionResponse);
executor.execute(operation);
}
/**
* Handles a commit request from a client
*/
void commitTransaction(HotRodHeader header, Subject subject, XidImpl xid) {
CommitTransactionOperation operation = new CommitTransactionOperation(header, server, subject, xid,
this::writeTransactionResponse);
executor.execute(operation);
}
/**
* Handles a prepare request from a client
*/
void prepareTransaction(HotRodHeader header, Subject subject, XidImpl xid, boolean onePhaseCommit,
List<TransactionWrite> writes, boolean recoverable, long timeout) {
HotRodServer.ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
validateConfiguration(cache);
executor.execute(() -> prepareTransactionInternal(header, cache, cacheInfo.versionGenerator, xid, onePhaseCommit,
writes, recoverable, timeout));
}
void forgetTransaction(HotRodHeader header, Subject subject, XidImpl xid) {
//TODO authentication?
GlobalTxTable txTable = SecurityActions.getGlobalComponentRegistry(server.getCacheManager()).getComponent(GlobalTxTable.class);
executor.execute(() -> {
try {
txTable.forgetTransaction(xid);
writeSuccess(header);
} catch (Throwable t) {
writeException(header, t);
}
});
}
void getPreparedTransactions(HotRodHeader header, Subject subject) {
//TODO authentication?
if (log.isTraceEnabled()) {
log.trace("Fetching transactions for recovery");
}
executor.execute(() -> {
try {
GlobalTxTable txTable = SecurityActions.getGlobalComponentRegistry(server.getCacheManager())
.getComponent(GlobalTxTable.class);
Collection<XidImpl> preparedTx = txTable.getPreparedTransactions();
writeResponse(header, createRecoveryResponse(header, preparedTx));
} catch (Throwable t) {
writeException(header, t);
}
});
}
private void prepareTransactionInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache,
VersionGenerator versionGenerator, XidImpl xid,
boolean onePhaseCommit, List<TransactionWrite> writes,
boolean recoverable, long timeout) {
try {
if (writes.isEmpty()) {
//the client can optimize and avoid contacting the server when no data is written.
if (log.isTraceEnabled()) {
log.tracef("Transaction %s is read only.", xid);
}
writeResponse(header, createTransactionResponse(header, XAResource.XA_RDONLY));
return;
}
PrepareCoordinator prepareCoordinator = new PrepareCoordinator(cache, xid, recoverable, timeout);
if (checkExistingTxForPrepare(header, prepareCoordinator)) {
if (log.isTraceEnabled()) {
log.tracef("Transaction %s conflicts with another node.", xid);
}
return;
}
if (!prepareCoordinator.startTransaction()) {
if (log.isTraceEnabled()) {
log.tracef("Unable to start transaction %s", xid);
}
writeNotExecuted(header);
return;
}
//forces the write-lock. used by pessimistic transaction. it ensures the key is not written after is it read and validated
//optimistic transaction will use the write-skew check.
AdvancedCache<byte[], byte[]> txCache = prepareCoordinator.decorateCache(cache);
try {
boolean rollback = false;
for (TransactionWrite write : writes) {
if (isValid(write, txCache)) {
if (write.isRemove()) {
txCache.remove(write.key);
} else {
write.metadata.version(versionGenerator.generateNew());
txCache.put(write.key, write.value, write.metadata.build());
}
} else {
prepareCoordinator.setRollbackOnly();
rollback = true;
break;
}
}
int xaCode = rollback ?
prepareCoordinator.rollback() :
prepareCoordinator.prepare(onePhaseCommit);
writeResponse(header, createTransactionResponse(header, xaCode));
} catch (Exception e) {
writeResponse(header, createTransactionResponse(header, prepareCoordinator.rollback()));
} finally {
EmbeddedTransactionManager.dissociateTransaction();
}
} catch (Throwable t) {
log.debugf(t, "Exception while replaying transaction %s for cache %s", xid, cache.getName());
writeException(header, t);
}
}
/**
* Checks if the configuration (and the transaction manager) is able to handle client transactions.
*/
private void validateConfiguration(AdvancedCache<byte[], byte[]> cache) {
Configuration configuration = cache.getCacheConfiguration();
if (!configuration.transaction().transactionMode().isTransactional()) {
throw log.expectedTransactionalCache(cache.getName());
}
if (configuration.locking().isolationLevel() != IsolationLevel.REPEATABLE_READ) {
throw log.unexpectedIsolationLevel(cache.getName());
}
}
/**
* Checks if the transaction was already prepared in another node
* <p>
* The client can send multiple requests to the server (in case of timeout or similar). This request is ignored when
* (1) the originator is still alive; (2) the transaction is prepared or committed/rolled-back
* <p>
* If the transaction isn't prepared and the originator left the cluster, the previous transaction is rolled-back and
* a new one is started.
*/
private boolean checkExistingTxForPrepare(HotRodHeader header, PrepareCoordinator txCoordinator) {
TxState txState = txCoordinator.getTxState();
if (txState == null) {
return false;
}
if (txCoordinator.isAlive(txState.getOriginator())) {
//transaction started on another node but the node is still in the topology. 2 possible scenarios:
// #1, the topology isn't updated
// #2, the client timed-out waiting for the reply
//in any case, we send a ignore reply and the client is free to retry (or rollback)
writeNotExecuted(header);
return true;
}
//originator is dead...
//First phase state machine
//success ACTIVE -> PREPARING -> PREPARED
//failed ACTIVE -> MARK_ROLLBACK -> ROLLED_BACK or ACTIVE -> PREPARING -> ROLLED_BACK
//1PC success ACTIVE -> PREPARING -> MARK_COMMIT -> COMMITTED
switch (txState.getStatus()) {
case ACTIVE:
case PREPARING:
//rollback existing transaction and retry with a new one
txCoordinator.rollbackRemoteTransaction(txState.getGlobalTransaction());
return false;
case PREPARED:
case COMMITTED:
//2PC since 1PC never reaches this state
writeResponse(header, createTransactionResponse(header, XAResource.XA_OK));
return true;
case MARK_ROLLBACK:
//make sure it is rolled back and reply to the client
txCoordinator.rollbackRemoteTransaction(txState.getGlobalTransaction());
case ROLLED_BACK:
writeResponse(header, createTransactionResponse(header, XAException.XA_RBROLLBACK));
return true;
case MARK_COMMIT:
writeResponse(header, createTransactionResponse(header, txCoordinator.onePhaseCommitRemoteTransaction(txState.getGlobalTransaction(), txState.getModifications())));
return true;
default:
throw new IllegalStateException();
}
}
/**
* Validates if the value read is still valid and the write operation can proceed.
*/
private boolean isValid(TransactionWrite write, AdvancedCache<byte[], byte[]> readCache) {
if (write.skipRead()) {
if (log.isTraceEnabled()) {
log.tracef("Operation %s wasn't read.", write);
}
return true;
}
CacheEntry<byte[], byte[]> entry = readCache.getCacheEntry(write.key);
if (write.wasNonExisting()) {
if (log.isTraceEnabled()) {
log.tracef("Key didn't exist for operation %s. Entry is %s", write, entry);
}
return entry == null || entry.getValue() == null;
}
if (log.isTraceEnabled()) {
log.tracef("Checking version for operation %s. Entry is %s", write, entry);
}
return entry != null && write.versionRead == MetadataUtils.extractVersion(entry);
}
private ByteBuf createTransactionResponse(HotRodHeader header, int xaReturnCode) {
return header.encoder().transactionResponse(header, server, channel, xaReturnCode);
}
private ByteBuf createRecoveryResponse(HotRodHeader header, Collection<XidImpl> xids) {
return header.encoder().recoveryResponse(header, server, channel, xids);
}
}
| 11,402
| 42.193182
| 176
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/KeyValueVersionConverter.java
|
package org.infinispan.server.hotrod;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.container.versioning.EntryVersion;
import org.infinispan.container.versioning.NumericVersion;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.EventType;
class KeyValueVersionConverter implements CacheEventConverter<byte[], byte[], byte[]> {
private final boolean returnOldValue;
private KeyValueVersionConverter(boolean returnOldValue) {
this.returnOldValue = returnOldValue;
}
public static KeyValueVersionConverter EXCLUDING_OLD_VALUE_CONVERTER = new KeyValueVersionConverter(false);
public static KeyValueVersionConverter INCLUDING_OLD_VALUE_CONVERTER = new KeyValueVersionConverter(true);
@Override
public byte[] convert(byte[] key, byte[] oldValue, Metadata oldMetadata, byte[] newValue, Metadata newMetadata, EventType eventType) {
int capacity = UnsignedNumeric.sizeUnsignedInt(key.length) + key.length +
(newValue != null ? UnsignedNumeric.sizeUnsignedInt(newValue.length) + newValue.length + 8 : 0);
if (newValue == null && returnOldValue && oldValue != null) {
capacity += UnsignedNumeric.sizeUnsignedInt(oldValue.length) + oldValue.length + 8;
}
byte[] out = new byte[capacity];
int offset = UnsignedNumeric.writeUnsignedInt(out, 0, key.length);
offset += putBytes(key, offset, out);
if (newValue != null) {
offset += UnsignedNumeric.writeUnsignedInt(out, offset, newValue.length);
offset += putBytes(newValue, offset, out);
writeVersion(newMetadata, offset, out);
}
if (newValue == null && returnOldValue && oldValue != null) {
offset += UnsignedNumeric.writeUnsignedInt(out, offset, oldValue.length);
offset += putBytes(oldValue, offset, out);
writeVersion(oldMetadata, offset, out);
}
return out;
}
private static void writeVersion(Metadata metadata, int offset, byte[] out) {
if (metadata == null || metadata.version() == null) {
return;
}
EntryVersion version = metadata.version();
if (version instanceof NumericVersion) {
putLong(((NumericVersion) version).getVersion(), offset, out);
}
}
private static int putBytes(byte[] bytes, int offset, byte[] out) {
System.arraycopy(bytes, 0, out, offset, bytes.length);
return bytes.length;
}
private static int putLong(long l, int offset, byte[] out) {
out[offset] = (byte) (l >> 56);
out[offset + 1] = (byte) (l >> 48);
out[offset + 2] = (byte) (l >> 40);
out[offset + 3] = (byte) (l >> 32);
out[offset + 4] = (byte) (l >> 24);
out[offset + 5] = (byte) (l >> 16);
out[offset + 6] = (byte) (l >> 8);
out[offset + 7] = (byte) l;
return offset + 8;
}
@Override
public boolean useRequestFormat() {
return true;
}
static class Externalizer extends AbstractExternalizer<KeyValueVersionConverter> {
@Override
public Set<Class<? extends KeyValueVersionConverter>> getTypeClasses() {
return Collections.singleton(KeyValueVersionConverter.class);
}
@Override
public void writeObject(ObjectOutput output, KeyValueVersionConverter object) throws IOException {
output.writeBoolean(object.returnOldValue);
}
@Override
public KeyValueVersionConverter readObject(ObjectInput input) throws IOException {
boolean returnOldValue = input.readBoolean();
return returnOldValue ? KeyValueVersionConverter.INCLUDING_OLD_VALUE_CONVERTER
: KeyValueVersionConverter.EXCLUDING_OLD_VALUE_CONVERTER;
}
}
}
| 4,017
| 38.009709
| 137
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/BaseRequestProcessor.java
|
package org.infinispan.server.hotrod;
import static java.lang.String.format;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.server.hotrod.logging.HotRodAccessLogging;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.topology.MissingMembersException;
import org.infinispan.util.concurrent.TimeoutException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
public class BaseRequestProcessor {
private static final Log log = LogFactory.getLog(BaseRequestProcessor.class, Log.class);
protected final Channel channel;
protected final Executor executor;
protected final HotRodServer server;
private final HotRodAccessLogging accessLogging;
BaseRequestProcessor(Channel channel, Executor executor, HotRodServer server) {
this.channel = channel;
this.executor = executor;
this.server = server;
this.accessLogging = server.accessLogging();
}
Channel channel() {
return channel;
}
void writeException(HotRodHeader header, Throwable cause) {
if (cause instanceof CompletionException && cause.getCause() != null) {
cause = cause.getCause();
}
String msg = cause.toString();
OperationStatus status;
if (cause instanceof InvalidMagicIdException) {
log.exceptionReported(cause);
status = OperationStatus.InvalidMagicOrMsgId;
} else if (cause instanceof HotRodUnknownOperationException) {
log.exceptionReported(cause);
HotRodUnknownOperationException hruoe = (HotRodUnknownOperationException) cause;
header = hruoe.toHeader();
status = OperationStatus.UnknownOperation;
} else if (cause instanceof UnknownVersionException) {
log.exceptionReported(cause);
UnknownVersionException uve = (UnknownVersionException) cause;
header = uve.toHeader();
status = OperationStatus.UnknownVersion;
} else if (cause instanceof RequestParsingException) {
if (cause instanceof CacheNotFoundException)
log.debug(cause.getMessage());
else
log.exceptionReported(cause);
msg = cause.getCause() == null ? cause.toString() : format("%s: %s", cause.getMessage(), cause.getCause().toString());
RequestParsingException rpe = (RequestParsingException) cause;
header = rpe.toHeader();
status = OperationStatus.ParseError;
} else if (cause instanceof IOException) {
status = OperationStatus.ParseError;
} else if (cause instanceof TimeoutException) {
status = OperationStatus.OperationTimedOut;
} else if (cause instanceof IllegalStateException || isExceptionTrace(cause)) {
if (isExceptionTrace(cause)) {
log.trace("Exception reported", cause);
} else {
// Some internal server code could throw this, so make sure it's logged
log.exceptionReported(cause);
}
if (header != null) {
status = header.encoder().errorStatus(cause);
msg = createErrorMsg(cause);
} else {
status = OperationStatus.ServerError;
}
} else if (header != null) {
if (cause instanceof MissingMembersException) log.warn(cause.getMessage());
else log.exceptionReported(cause);
status = header.encoder().errorStatus(cause);
msg = createErrorMsg(cause);
} else {
log.exceptionReported(cause);
status = OperationStatus.ServerError;
}
if (header == null) {
header = new HotRodHeader(HotRodOperation.ERROR, (byte) 0, 0, "", 0, (short) 1, 0, MediaType.MATCH_ALL, MediaType.MATCH_ALL, null);
} else {
header.op = HotRodOperation.ERROR;
}
ByteBuf buf = header.encoder().errorResponse(header, server, channel, msg, status);
int responseBytes = buf.readableBytes();
ChannelFuture future = channel.writeAndFlush(buf);
if (header instanceof AccessLoggingHeader) {
accessLogging.logException(future, (AccessLoggingHeader) header, cause.toString(), responseBytes);
}
}
void writeSuccess(HotRodHeader header, CacheEntry<byte[], byte[]> entry) {
if (header.hasFlag(ProtocolFlag.ForceReturnPreviousValue)) {
writeResponse(header, header.encoder().successResponse(header, server, channel, entry));
} else {
writeResponse(header, header.encoder().emptyResponse(header, server, channel, OperationStatus.Success));
}
}
void writeSuccess(HotRodHeader header) {
writeResponse(header, header.encoder().emptyResponse(header, server, channel, OperationStatus.Success));
}
void writeNotExecuted(HotRodHeader header, CacheEntry<byte[], byte[]> prev) {
if (header.hasFlag(ProtocolFlag.ForceReturnPreviousValue)) {
writeResponse(header, header.encoder().notExecutedResponse(header, server, channel, prev));
} else {
writeResponse(header, header.encoder().emptyResponse(header, server, channel, OperationStatus.OperationNotExecuted));
}
}
void writeNotExecuted(HotRodHeader header) {
writeResponse(header, header.encoder().emptyResponse(header, server, channel, OperationStatus.OperationNotExecuted));
}
void writeNotExist(HotRodHeader header) {
writeResponse(header, header.encoder().notExistResponse(header, server, channel));
}
protected void writeResponse(HotRodHeader header, ByteBuf buf) {
int responseBytes = buf.readableBytes();
ChannelFuture future = channel.writeAndFlush(buf);
if (header instanceof AccessLoggingHeader) {
accessLogging.logOK(future, (AccessLoggingHeader) header, responseBytes);
}
}
private String createErrorMsg(Throwable t) {
Set<Throwable> causes = new LinkedHashSet<>();
Throwable initial = t;
while (initial != null && !causes.contains(initial)) {
causes.add(initial);
initial = initial.getCause();
}
return causes.stream().map(Object::toString).collect(Collectors.joining("\n"));
}
private boolean isExceptionTrace(Throwable t) {
return t instanceof MissingMembersException;
}
}
| 6,560
| 39.751553
| 140
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodServer.java
|
package org.infinispan.server.hotrod;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JBOSS_MARSHALLING;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_UNKNOWN;
import static org.infinispan.counter.EmbeddedCounterManagerFactory.asCounterManager;
import static org.infinispan.factories.KnownComponentNames.NON_BLOCKING_EXECUTOR;
import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Function;
import javax.security.auth.Subject;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.marshall.Externalizer;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.marshall.SerializeWith;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.ServiceFinder;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.Configurations;
import org.infinispan.container.versioning.VersionGenerator;
import org.infinispan.context.Flag;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.filter.AbstractKeyValueFilterConverter;
import org.infinispan.filter.KeyValueFilterConverter;
import org.infinispan.filter.KeyValueFilterConverterFactory;
import org.infinispan.filter.NamedFactory;
import org.infinispan.filter.ParamKeyValueFilterConverterFactory;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.ClusterExecutor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.core.EncoderRegistry;
import org.infinispan.metadata.EmbeddedMetadata;
import org.infinispan.metadata.Metadata;
import org.infinispan.multimap.impl.EmbeddedMultimapCache;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.TopologyChanged;
import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverterFactory;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterFactory;
import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStopped;
import org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.core.AbstractProtocolServer;
import org.infinispan.server.core.CacheInfo;
import org.infinispan.server.core.QueryFacade;
import org.infinispan.server.core.ServerConstants;
import org.infinispan.server.core.transport.NettyChannelInitializer;
import org.infinispan.server.core.transport.NettyInitializers;
import org.infinispan.server.hotrod.configuration.HotRodServerConfiguration;
import org.infinispan.server.hotrod.counter.listener.ClientCounterManagerNotificationManager;
import org.infinispan.server.hotrod.event.KeyValueWithPreviousEventConverterFactory;
import org.infinispan.server.hotrod.logging.HotRodAccessLogging;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.server.hotrod.transport.TimeoutEnabledChannelInitializer;
import org.infinispan.server.iteration.DefaultIterationManager;
import org.infinispan.server.iteration.IterationManager;
import org.infinispan.util.KeyValuePair;
import org.infinispan.util.concurrent.AggregateCompletionStage;
import org.infinispan.util.concurrent.CompletionStages;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.channel.group.ChannelMatcher;
import io.netty.util.concurrent.DefaultThreadFactory;
/**
* Hot Rod server, in charge of defining its encoder/decoder and, if clustered, update the topology information on
* startup and shutdown.
*
* @author Galder Zamarreño
* @since 4.1
*/
public class HotRodServer extends AbstractProtocolServer<HotRodServerConfiguration> {
static final Log log = LogFactory.getLog(HotRodServer.class, Log.class);
private static final long MILLISECONDS_IN_30_DAYS = TimeUnit.DAYS.toMillis(30);
public static final int DEFAULT_HOTROD_PORT = 11222;
public static final int LISTENERS_CHECK_INTERVAL = 10;
private boolean hasDefaultCache;
private Address clusterAddress;
private ServerAddress address;
private Cache<Address, ServerAddress> addressCache;
private final Map<String, ExtendedCacheInfo> knownCaches = new ConcurrentHashMap<>();
private QueryFacade queryFacade;
private ClientListenerRegistry clientListenerRegistry;
private Marshaller marshaller;
private ClusterExecutor clusterExecutor;
private CrashedMemberDetectorListener viewChangeListener;
private ReAddMyAddressListener topologyChangeListener;
private IterationManager iterationManager;
private RemoveCacheListener removeCacheListener;
private ClientCounterManagerNotificationManager clientCounterNotificationManager;
private HotRodAccessLogging accessLogging = new HotRodAccessLogging();
private ScheduledExecutorService scheduledExecutor;
private TimeService timeService;
public HotRodServer() {
super("HotRod");
}
public boolean hasDefaultCache() {
return hasDefaultCache;
}
public ServerAddress getAddress() {
return address;
}
public Marshaller getMarshaller() {
return marshaller;
}
public TimeService getTimeService() {
return timeService;
}
byte[] query(AdvancedCache<byte[], byte[]> cache, byte[] query) {
return queryFacade.query(cache, query);
}
public ClientListenerRegistry getClientListenerRegistry() {
return clientListenerRegistry;
}
public ClientCounterManagerNotificationManager getClientCounterNotificationManager() {
return clientCounterNotificationManager;
}
@Override
public ChannelOutboundHandler getEncoder() {
return null;
}
@Override
public HotRodDecoder getDecoder() {
return new HotRodDecoder(cacheManager, getExecutor(), this);
}
@Override
public ChannelMatcher getChannelMatcher() {
return channel -> channel.pipeline().get(HotRodDecoder.class) != null;
}
@Override
public void installDetector(Channel ch) {
ch.pipeline().addLast(HotRodDetector.NAME, new HotRodDetector(this));
}
/**
* Class used to create to empty filter converters that ignores marshalling of keys and values
*/
static class ToEmptyBytesFactory implements ParamKeyValueFilterConverterFactory {
@Override
public KeyValueFilterConverter getFilterConverter(Object[] params) {
return ToEmptyBytesKeyValueFilterConverter.INSTANCE;
}
@Override
public boolean binaryParam() {
// No reason to unmarshall keys/values as we just ignore them anyways
return true;
}
}
/**
* Class used to allow for remote clients to essentially ignore the value by returning an empty byte[].
*/
@SerializeWith(value = ToEmptyBytesKeyValueFilterConverter.ToEmptyBytesKeyValueFilterConverterExternalizer.class)
static class ToEmptyBytesKeyValueFilterConverter extends AbstractKeyValueFilterConverter {
private ToEmptyBytesKeyValueFilterConverter() {
}
public static ToEmptyBytesKeyValueFilterConverter INSTANCE = new ToEmptyBytesKeyValueFilterConverter();
static final byte[] bytes = Util.EMPTY_BYTE_ARRAY;
@Override
public Object filterAndConvert(Object key, Object value, Metadata metadata) {
return bytes;
}
@Override
public MediaType format() {
return null;
}
public static final class ToEmptyBytesKeyValueFilterConverterExternalizer implements
Externalizer<ToEmptyBytesKeyValueFilterConverter> {
@Override
public void writeObject(ObjectOutput output, ToEmptyBytesKeyValueFilterConverter object) {
}
@Override
public ToEmptyBytesKeyValueFilterConverter readObject(ObjectInput input) {
return INSTANCE;
}
}
}
@Override
protected void startInternal() {
GlobalComponentRegistry gcr = SecurityActions.getGlobalComponentRegistry(cacheManager);
this.iterationManager = new DefaultIterationManager(gcr.getTimeService());
this.hasDefaultCache = configuration.defaultCacheName() != null || cacheManager.getCacheManagerConfiguration().defaultCacheName().isPresent();
// Initialize query-specific stuff
queryFacade = loadQueryFacade();
clientListenerRegistry = new ClientListenerRegistry(gcr.getComponent(EncoderRegistry.class),
gcr.getComponent(ExecutorService.class, NON_BLOCKING_EXECUTOR));
clientCounterNotificationManager = new ClientCounterManagerNotificationManager(asCounterManager(cacheManager));
addKeyValueFilterConverterFactory(ToEmptyBytesKeyValueFilterConverter.class.getName(), new ToEmptyBytesFactory());
addCacheEventConverterFactory("key-value-with-previous-converter-factory",
new KeyValueWithPreviousEventConverterFactory());
addCacheEventConverterFactory("___eager-key-value-version-converter", KeyValueVersionConverterFactory.SINGLETON);
loadFilterConverterFactories(ParamKeyValueFilterConverterFactory.class, this::addKeyValueFilterConverterFactory);
loadFilterConverterFactories(CacheEventFilterConverterFactory.class, this::addCacheEventFilterConverterFactory);
loadFilterConverterFactories(CacheEventConverterFactory.class, this::addCacheEventConverterFactory);
loadFilterConverterFactories(KeyValueFilterConverterFactory.class, this::addKeyValueFilterConverterFactory);
DefaultThreadFactory factory = new DefaultThreadFactory(getQualifiedName() + "-Scheduled");
scheduledExecutor = Executors.newSingleThreadScheduledExecutor(factory);
removeCacheListener = new RemoveCacheListener();
SecurityActions.addListener(cacheManager, removeCacheListener);
// Start default cache and the endpoint before adding self to
// topology in order to avoid topology updates being used before
// endpoint is available.
super.startInternal();
// Add self to topology cache last, after everything is initialized
if (Configurations.isClustered(SecurityActions.getCacheManagerConfiguration(cacheManager))) {
defineTopologyCacheConfig(cacheManager);
if (log.isDebugEnabled())
log.debugf("Externally facing address is %s:%d", configuration.proxyHost(), configuration.proxyPort());
addSelfToTopologyView(cacheManager);
}
}
@Override
public ChannelInitializer<Channel> getInitializer() {
if (configuration.idleTimeout() > 0)
return new NettyInitializers(new NettyChannelInitializer(this, transport, getEncoder(), this::getDecoder),
new TimeoutEnabledChannelInitializer<>(this));
else // Idle timeout logic is disabled with -1 or 0 values
return new NettyInitializers(new NettyChannelInitializer(this, transport, getEncoder(), this::getDecoder));
}
private <T> void loadFilterConverterFactories(Class<T> c, BiConsumer<String, T> biConsumer) {
ServiceFinder.load(c).forEach(factory -> {
NamedFactory annotation = factory.getClass().getAnnotation(NamedFactory.class);
if (annotation != null) {
String name = annotation.name();
biConsumer.accept(name, factory);
}
});
}
private QueryFacade loadQueryFacade() {
QueryFacade facadeImpl = null;
Iterator<QueryFacade> iterator = ServiceLoader.load(QueryFacade.class, getClass().getClassLoader()).iterator();
if (iterator.hasNext()) {
facadeImpl = iterator.next();
if (iterator.hasNext()) {
throw new IllegalStateException("Found multiple QueryFacade service implementations: "
+ facadeImpl.getClass().getName() + " and "
+ iterator.next().getClass().getName());
}
}
return facadeImpl;
}
@Override
protected void startTransport() {
super.startTransport();
}
@Override
protected void startCaches() {
super.startCaches();
// Periodically update cache info about potentially blocking operations
scheduledExecutor.scheduleWithFixedDelay(new CacheInfoUpdateTask(),
LISTENERS_CHECK_INTERVAL, LISTENERS_CHECK_INTERVAL, TimeUnit.SECONDS);
}
private void addSelfToTopologyView(EmbeddedCacheManager cacheManager) {
addressCache = cacheManager.getCache(configuration.topologyCacheName());
clusterAddress = cacheManager.getAddress();
address = ServerAddress.forAddress(configuration.publicHost(), configuration.publicPort(), configuration.networkPrefixOverride());
clusterExecutor = cacheManager.executor();
viewChangeListener = new CrashedMemberDetectorListener(addressCache, this);
cacheManager.addListener(viewChangeListener);
topologyChangeListener = new ReAddMyAddressListener(addressCache, clusterAddress, address);
addressCache.addListener(topologyChangeListener);
timeService = SecurityActions.getGlobalComponentRegistry(cacheManager).getTimeService();
// Map cluster address to server endpoint address
log.debugf("Map %s cluster address with %s server endpoint in address cache", clusterAddress, address);
addressCache.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES)
.put(clusterAddress, address);
}
private void defineTopologyCacheConfig(EmbeddedCacheManager cacheManager) {
InternalCacheRegistry internalCacheRegistry = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(
InternalCacheRegistry.class);
internalCacheRegistry.registerInternalCache(configuration.topologyCacheName(),
createTopologyCacheConfig(
cacheManager.getCacheManagerConfiguration().transport()
.distributedSyncTimeout()).build(),
EnumSet.of(InternalCacheRegistry.Flag.EXCLUSIVE));
}
protected ConfigurationBuilder createTopologyCacheConfig(long distSyncTimeout) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.clustering().cacheMode(CacheMode.REPL_SYNC).remoteTimeout(configuration.topologyReplTimeout())
.locking().lockAcquisitionTimeout(configuration.topologyLockTimeout())
.clustering().partitionHandling().mergePolicy(null)
.expiration().lifespan(-1).maxIdle(-1);
if (configuration.topologyStateTransfer()) {
builder
.clustering()
.stateTransfer()
.awaitInitialTransfer(configuration.topologyAwaitInitialTransfer())
.fetchInMemoryState(true)
.timeout(distSyncTimeout + configuration.topologyReplTimeout());
} else {
builder.persistence()
.addClusterLoader()
.segmented(false)
.remoteCallTimeout(configuration.topologyReplTimeout());
}
return builder;
}
public AdvancedCache<byte[], byte[]> cache(ExtendedCacheInfo cacheInfo, HotRodHeader header, Subject subject) {
KeyValuePair<MediaType, MediaType> requestMediaTypes = getRequestMediaTypes(header, cacheInfo.configuration);
AdvancedCache<byte[], byte[]> cache =
cacheInfo.getCache(requestMediaTypes, subject);
cache = header.getOptimizedCache(cache, cacheInfo.transactional, cacheInfo.clustered);
return cache;
}
public EmbeddedMultimapCache<byte[], byte[]> multimap(HotRodHeader header, Subject subject, boolean supportsDuplicates) {
AdvancedCache<byte[], byte[]> cache = cache(getCacheInfo(header), header, subject).withStorageMediaType();
return new EmbeddedMultimapCache(cache, supportsDuplicates);
}
public ExtendedCacheInfo getCacheInfo(HotRodHeader header) {
return getCacheInfo(header.cacheName, header.version, header.messageId, true);
}
public ExtendedCacheInfo getCacheInfo(String cacheName, byte hotRodVersion, long messageId, boolean checkIgnored) {
if (checkIgnored && isCacheIgnored(cacheName)) {
throw new CacheUnavailableException();
}
ExtendedCacheInfo info = knownCaches.get(cacheName);
if (info == null) {
boolean keep = checkCacheIsAvailable(cacheName, hotRodVersion, messageId);
AdvancedCache<byte[], byte[]> cache = obtainAnonymizedCache(cacheName);
Configuration cacheCfg = SecurityActions.getCacheConfiguration(cache);
info = new ExtendedCacheInfo(cache, cacheCfg);
updateCacheInfo(info);
if (keep) {
knownCaches.put(cacheName, info);
}
}
return info;
}
private boolean checkCacheIsAvailable(String cacheName, byte hotRodVersion, long messageId) {
InternalCacheRegistry icr = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(InternalCacheRegistry.class);
boolean keep;
if (icr.isPrivateCache(cacheName)) {
throw new RequestParsingException(
String.format("Remote requests are not allowed to private caches. Do no send remote requests to cache '%s'",
cacheName),
hotRodVersion, messageId);
} else if (icr.internalCacheHasFlag(cacheName, InternalCacheRegistry.Flag.PROTECTED)) {
// We want to make sure the cache access is checked every time, so don't store it as a "known" cache.
// More expensive, but these caches should not be accessed frequently
keep = false;
} else if (!cacheName.isEmpty() && !cacheManager.getCacheNames().contains(cacheName)) {
throw new CacheNotFoundException(
String.format("Cache with name '%s' not found amongst the configured caches", cacheName),
hotRodVersion, messageId);
} else if (cacheName.isEmpty() && !hasDefaultCache) {
throw new CacheNotFoundException("Default cache requested but not configured", hotRodVersion, messageId);
} else {
keep = true;
}
return keep;
}
public void updateCacheInfo(ExtendedCacheInfo info) {
if (info.getCache().getStatus() != ComponentStatus.RUNNING)
return;
boolean hasIndexing = SecurityActions.getCacheConfiguration(info.getCache()).indexing().enabled();
info.update(hasIndexing);
}
private AdvancedCache<byte[], byte[]> obtainAnonymizedCache(String cacheName) {
String validCacheName = cacheName.isEmpty() ? defaultCacheName() : cacheName;
Cache<byte[], byte[]> cache = SecurityActions.getCache(cacheManager, validCacheName);
return cache.getAdvancedCache();
}
public Cache<Address, ServerAddress> getAddressCache() {
return addressCache;
}
public void addCacheEventFilterFactory(String name, CacheEventFilterFactory factory) {
clientListenerRegistry.addCacheEventFilterFactory(name, factory);
}
public void removeCacheEventFilterFactory(String name) {
clientListenerRegistry.removeCacheEventFilterFactory(name);
}
public void addCacheEventConverterFactory(String name, CacheEventConverterFactory factory) {
clientListenerRegistry.addCacheEventConverterFactory(name, factory);
}
public void removeCacheEventConverterFactory(String name) {
clientListenerRegistry.removeCacheEventConverterFactory(name);
}
public void addCacheEventFilterConverterFactory(String name, CacheEventFilterConverterFactory factory) {
clientListenerRegistry.addCacheEventFilterConverterFactory(name, factory);
}
public void removeCacheEventFilterConverterFactory(String name) {
clientListenerRegistry.removeCacheEventFilterConverterFactory(name);
}
public void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
Optional<Marshaller> optMarshaller = Optional.ofNullable(marshaller);
clientListenerRegistry.setEventMarshaller(optMarshaller);
}
public void addKeyValueFilterConverterFactory(String name, KeyValueFilterConverterFactory factory) {
iterationManager.addKeyValueFilterConverterFactory(name, factory);
}
public void removeKeyValueFilterConverterFactory(String name) {
iterationManager.removeKeyValueFilterConverterFactory(name);
}
public IterationManager getIterationManager() {
return iterationManager;
}
private static KeyValuePair<MediaType, MediaType> getRequestMediaTypes(HotRodHeader header,
Configuration configuration) {
MediaType keyRequestType = header == null ? APPLICATION_UNKNOWN : header.getKeyMediaType();
MediaType valueRequestType = header == null ? APPLICATION_UNKNOWN : header.getValueMediaType();
if (header != null && HotRodVersion.HOTROD_28.isOlder(header.version)) {
// Pre-2.8 clients always send protobuf payload to the metadata cache
if (header.cacheName.equals(PROTOBUF_METADATA_CACHE_NAME)) {
keyRequestType = APPLICATION_PROTOSTREAM;
valueRequestType = APPLICATION_PROTOSTREAM;
} else {
// Pre-2.8 clients always sent query encoded as protobuf unless object store is used.
if (header.op == HotRodOperation.QUERY) {
boolean objectStorage = APPLICATION_OBJECT.match(configuration.encoding().valueDataType().mediaType());
keyRequestType = objectStorage ? APPLICATION_JBOSS_MARSHALLING : APPLICATION_PROTOSTREAM;
valueRequestType = objectStorage ? APPLICATION_JBOSS_MARSHALLING : APPLICATION_PROTOSTREAM;
}
}
}
return new KeyValuePair<>(keyRequestType, valueRequestType);
}
@Override
public void stop() {
if (log.isDebugEnabled())
log.debugf("Stopping server %s listening at %s:%d", getQualifiedName(), configuration.host(), configuration.port());
AggregateCompletionStage<Void> removeAllStage = CompletionStages.aggregateCompletionStage();
if (removeCacheListener != null) {
removeAllStage.dependsOn(SecurityActions.removeListenerAsync(cacheManager, removeCacheListener));
}
if (viewChangeListener != null) {
removeAllStage.dependsOn(SecurityActions.removeListenerAsync(cacheManager, viewChangeListener));
}
if (topologyChangeListener != null) {
removeAllStage.dependsOn(SecurityActions.removeListenerAsync(addressCache, topologyChangeListener));
}
CompletionStages.join(removeAllStage.freeze());
if (cacheManager != null && Configurations.isClustered(SecurityActions.getCacheManagerConfiguration(cacheManager))) {
InternalCacheRegistry internalCacheRegistry =
SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(InternalCacheRegistry.class);
if (internalCacheRegistry != null)
internalCacheRegistry.unregisterInternalCache(configuration.topologyCacheName());
}
if (scheduledExecutor != null) {
scheduledExecutor.shutdownNow();
}
if (clientListenerRegistry != null) clientListenerRegistry.stop();
if (clientCounterNotificationManager != null) clientCounterNotificationManager.stop();
super.stop();
}
public HotRodAccessLogging accessLogging() {
return accessLogging;
}
public Metadata.Builder buildMetadata2x(long lifespan, TimeUnitValue lifespanUnit, long maxIdle, TimeUnitValue maxIdleUnit) {
EmbeddedMetadata.Builder metadata = new EmbeddedMetadata.Builder();
if (lifespan != ServerConstants.EXPIRATION_DEFAULT && lifespanUnit != TimeUnitValue.DEFAULT) {
if (lifespanUnit == TimeUnitValue.INFINITE) {
metadata.lifespan(ServerConstants.EXPIRATION_NONE);
} else {
metadata.lifespan(toMillis(lifespan, lifespanUnit));
}
}
if (maxIdle != ServerConstants.EXPIRATION_DEFAULT && maxIdleUnit != TimeUnitValue.DEFAULT) {
if (maxIdleUnit == TimeUnitValue.INFINITE) {
metadata.maxIdle(ServerConstants.EXPIRATION_NONE);
} else {
metadata.maxIdle(toMillis(maxIdle, maxIdleUnit));
}
}
return metadata;
}
public Metadata.Builder buildMetadata(long lifespan, TimeUnitValue lifespanUnit, long maxIdle, TimeUnitValue maxIdleUnit) {
EmbeddedMetadata.Builder metadata = new EmbeddedMetadata.Builder();
if (lifespan != ServerConstants.EXPIRATION_DEFAULT && lifespanUnit != TimeUnitValue.DEFAULT) {
if (lifespanUnit == TimeUnitValue.INFINITE) {
metadata.lifespan(ServerConstants.EXPIRATION_NONE);
} else {
metadata.lifespan(lifespanUnit.toTimeUnit().toMillis(lifespan));
}
}
if (maxIdle != ServerConstants.EXPIRATION_DEFAULT && maxIdleUnit != TimeUnitValue.DEFAULT) {
if (maxIdleUnit == TimeUnitValue.INFINITE) {
metadata.maxIdle(ServerConstants.EXPIRATION_NONE);
} else {
metadata.maxIdle(maxIdleUnit.toTimeUnit().toMillis(maxIdle));
}
}
return metadata;
}
/**
* Transforms lifespan pass as seconds into milliseconds following this rule (inspired by Memcached):
* <p>
* If lifespan is bigger than number of seconds in 30 days, then it is considered unix time. After converting it to
* milliseconds, we subtract the current time in and the result is returned.
* <p>
* Otherwise it's just considered number of seconds from now and it's returned in milliseconds unit.
*/
private static long toMillis(long duration, TimeUnitValue unit) {
if (duration > 0) {
long milliseconds = unit.toTimeUnit().toMillis(duration);
if (milliseconds > MILLISECONDS_IN_30_DAYS) {
long unixTimeExpiry = milliseconds - System.currentTimeMillis();
return unixTimeExpiry < 0 ? 0 : unixTimeExpiry;
} else {
return milliseconds;
}
} else {
return duration;
}
}
public String toString() {
return "HotRodServer[" +
"configuration=" + configuration +
']';
}
public static class ExtendedCacheInfo extends CacheInfo<byte[], byte[]> {
final DistributionManager distributionManager;
final VersionGenerator versionGenerator;
final Configuration configuration;
final boolean transactional;
final boolean clustered;
volatile boolean indexing;
ExtendedCacheInfo(AdvancedCache<byte[], byte[]> cache, Configuration configuration) {
super(SecurityActions.anonymizeSecureCache(cache));
this.distributionManager = SecurityActions.getDistributionManager(cache);
ComponentRegistry componentRegistry = SecurityActions.getCacheComponentRegistry(cache);
//Note: HotRod cannot use the same version generator as Optimistic Transaction.
this.versionGenerator = componentRegistry.getComponent(VersionGenerator.class, KnownComponentNames.HOT_ROD_VERSION_GENERATOR);
this.configuration = configuration;
this.transactional = configuration.transaction().transactionMode().isTransactional();
this.clustered = configuration.clustering().cacheMode().isClustered();
// Start conservative and assume we have all the stuff that can cause operations to block
this.indexing = true;
}
public void update(boolean indexing) {
this.indexing = indexing;
}
}
@Listener(sync = false, observation = Listener.Observation.POST)
class ReAddMyAddressListener {
private final Cache<Address, ServerAddress> addressCache;
private final Address clusterAddress;
private final ServerAddress address;
ReAddMyAddressListener(Cache<Address, ServerAddress> addressCache, Address clusterAddress, ServerAddress address) {
this.addressCache = addressCache;
this.clusterAddress = clusterAddress;
this.address = address;
}
@TopologyChanged
public void topologyChanged(TopologyChangedEvent<Address, ServerAddress> event) {
recursionTopologyChanged();
}
private void recursionTopologyChanged() {
// Check the manager status, not the address cache status, because it changes to STOPPING first
if (cacheManager.getStatus().allowInvocations()) {
// No need for a timeout here, the cluster executor has a default timeout
clusterExecutor.submitConsumer(new CheckAddressTask(addressCache.getName(), clusterAddress), (a, v, t) -> {
if (t != null && !(t instanceof IllegalLifecycleStateException)) {
log.debug("Error re-adding address to topology cache, retrying", t);
recursionTopologyChanged();
}
if (t == null && !v) {
log.debugf("Re-adding %s to the topology cache", clusterAddress);
addressCache.putAsync(clusterAddress, address);
}
});
}
}
}
@Listener
class RemoveCacheListener {
@CacheStopped
public void cacheStopped(CacheStoppedEvent event) {
knownCaches.remove(event.getCacheName());
}
}
private class CacheInfoUpdateTask implements Runnable {
@Override
public void run() {
for (ExtendedCacheInfo cacheInfo : knownCaches.values()) {
updateCacheInfo(cacheInfo);
}
}
}
}
@SerializeWith(value = CheckAddressTask.CheckAddressTaskExternalizer.class)
class CheckAddressTask implements Function<EmbeddedCacheManager, Boolean> {
private final String cacheName;
private final Address clusterAddress;
CheckAddressTask(String cacheName, Address clusterAddress) {
this.cacheName = cacheName;
this.clusterAddress = clusterAddress;
}
@Override
public Boolean apply(EmbeddedCacheManager embeddedCacheManager) {
if (embeddedCacheManager.isRunning(cacheName)) {
Cache<Address, ServerAddress> cache = embeddedCacheManager.getCache(cacheName);
return cache.containsKey(clusterAddress);
}
// If the cache isn't started just play like this node has the address in the cache - it will be added as it
// joins, so no worries
return true;
}
public static final class CheckAddressTaskExternalizer implements Externalizer<CheckAddressTask> {
@Override
public void writeObject(ObjectOutput output, CheckAddressTask object) throws IOException {
output.writeUTF(object.cacheName);
output.writeObject(object.clusterAddress);
}
@Override
public CheckAddressTask readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new CheckAddressTask(input.readUTF(), (Address) input.readObject());
}
}
}
| 32,584
| 43.454297
| 148
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/ClientListenerRegistry.java
|
package org.infinispan.server.hotrod;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.TranscoderMarshallerAdapter;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.marshall.WrappedByteArray;
import org.infinispan.commons.util.BloomFilter;
import org.infinispan.commons.util.Util;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.container.versioning.NumericVersion;
import org.infinispan.marshall.core.EncoderRegistry;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverterFactory;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterFactory;
import org.infinispan.notifications.cachelistener.filter.KeyValueFilterConverterAsCacheEventFilterConverter;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.util.KeyValuePair;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.EventLoop;
/**
* @author Galder Zamarreño
*/
class ClientListenerRegistry {
private final EncoderRegistry encoderRegistry;
private final Executor nonBlockingExecutor;
ClientListenerRegistry(EncoderRegistry encoderRegistry, Executor nonBlockingExecutor) {
this.encoderRegistry = encoderRegistry;
this.nonBlockingExecutor = nonBlockingExecutor;
}
private final static Log log = LogFactory.getLog(ClientListenerRegistry.class, Log.class);
private final ConcurrentMap<WrappedByteArray, Object> eventSenders = new ConcurrentHashMap<>();
private final ConcurrentMap<String, CacheEventFilterFactory> cacheEventFilterFactories = new ConcurrentHashMap<>(4, 0.9f, 16);
private final ConcurrentMap<String, CacheEventConverterFactory> cacheEventConverterFactories = new ConcurrentHashMap<>(4, 0.9f, 16);
private final ConcurrentMap<String, CacheEventFilterConverterFactory> cacheEventFilterConverterFactories = new ConcurrentHashMap<>(4, 0.9f, 16);
void setEventMarshaller(Optional<Marshaller> eventMarshaller) {
eventMarshaller.ifPresent(m -> {
TranscoderMarshallerAdapter adapter = new TranscoderMarshallerAdapter(m);
if (encoderRegistry.isConversionSupported(MediaType.APPLICATION_OBJECT, m.mediaType())) {
log.skippingMarshallerWrapping(m.mediaType().toString());
} else {
encoderRegistry.registerTranscoder(adapter);
}
});
}
void addCacheEventFilterFactory(String name, CacheEventFilterFactory factory) {
if (factory instanceof CacheEventConverterFactory) {
throw log.illegalFilterConverterEventFactory(name);
}
cacheEventFilterFactories.put(name, factory);
}
void removeCacheEventFilterFactory(String name) {
cacheEventFilterFactories.remove(name);
}
void addCacheEventConverterFactory(String name, CacheEventConverterFactory factory) {
if (factory instanceof CacheEventFilterFactory) {
throw log.illegalFilterConverterEventFactory(name);
}
cacheEventConverterFactories.put(name, factory);
}
void removeCacheEventConverterFactory(String name) {
cacheEventConverterFactories.remove(name);
}
void addCacheEventFilterConverterFactory(String name, CacheEventFilterConverterFactory factory) {
cacheEventFilterConverterFactories.put(name, factory);
}
void removeCacheEventFilterConverterFactory(String name) {
cacheEventFilterConverterFactories.remove(name);
}
CompletionStage<Void> addClientListener(Channel ch, HotRodHeader h, byte[] listenerId,
AdvancedCache<byte[], byte[]> cache, boolean includeState,
String filterFactory, List<byte[]> binaryFilterParams,
String converterFactory, List<byte[]> binaryConverterParams,
boolean useRawData, int listenerInterests, BloomFilter<byte[]> bloomFilter) {
CacheEventFilter<byte[], byte[]> filter;
CacheEventConverter<byte[], byte[], byte[]> converter;
ClientEventType eventType;
if (bloomFilter != null) {
assert filterFactory == null || filterFactory.isEmpty();
assert converterFactory == null || converterFactory.isEmpty();
assert !includeState;
eventType = ClientEventType.createType(false, useRawData, h.version);
filter = null;
converter = new KeyValueFilterConverterAsCacheEventFilterConverter<>(HotRodServer.ToEmptyBytesKeyValueFilterConverter.INSTANCE);
} else {
boolean hasFilter = filterFactory != null && !filterFactory.isEmpty();
boolean hasConverter = converterFactory != null && !converterFactory.isEmpty();
eventType = ClientEventType.createType(hasConverter, useRawData, h.version);
if (hasFilter) {
if (hasConverter) {
if (filterFactory.equals(converterFactory)) {
List<byte[]> binaryParams = binaryFilterParams.isEmpty() ? binaryConverterParams : binaryFilterParams;
CacheEventFilterConverter<byte[], byte[], byte[]> filterConverter = getFilterConverter(h.getValueMediaType(),
filterFactory, useRawData, binaryParams);
filter = filterConverter;
converter = filterConverter;
} else {
filter = getFilter(h.getValueMediaType(), filterFactory, useRawData, binaryFilterParams);
converter = getConverter(h.getValueMediaType(), converterFactory, useRawData, binaryConverterParams);
}
} else {
filter = getFilter(h.getValueMediaType(), filterFactory, useRawData, binaryFilterParams);
converter = null;
}
} else if (hasConverter) {
filter = null;
converter = getConverter(h.getValueMediaType(), converterFactory, useRawData, binaryConverterParams);
} else {
filter = null;
converter = null;
}
}
BaseClientEventSender clientEventSender = getClientEventSender(includeState, ch, h.encoder(), h.version, cache,
listenerId, eventType, h.messageId, bloomFilter);
eventSenders.put(new WrappedByteArray(listenerId), clientEventSender);
return addCacheListener(cache, clientEventSender, filter, converter, listenerInterests, useRawData)
.whenComplete((__, t) -> {
if (t != null) {
// Don't try to remove the listener when
eventSenders.remove(new WrappedByteArray(listenerId));
}
});
}
private CompletionStage<Void> addCacheListener(AdvancedCache<byte[], byte[]> cache, Object clientEventSender,
CacheEventFilter<byte[], byte[]> filter, CacheEventConverter<byte[], byte[], byte[]> converter,
int listenerInterests, boolean useRawData) {
Set<Class<? extends Annotation>> filterAnnotations;
if (listenerInterests == 0x00) {
filterAnnotations = new HashSet<>(Arrays.asList(
CacheEntryCreated.class, CacheEntryModified.class,
CacheEntryRemoved.class, CacheEntryExpired.class));
} else {
filterAnnotations = new HashSet<>();
if ((listenerInterests & 0x01) == 0x01)
filterAnnotations.add(CacheEntryCreated.class);
if ((listenerInterests & 0x02) == 0x02)
filterAnnotations.add(CacheEntryModified.class);
if ((listenerInterests & 0x04) == 0x04)
filterAnnotations.add(CacheEntryRemoved.class);
if ((listenerInterests & 0x08) == 0x08)
filterAnnotations.add(CacheEntryExpired.class);
}
// If no filter or converter are supplied, we can apply a converter so we don't have to return the value - since
// events will only use the key
if (converter == null && filter == null) {
converter = new KeyValueFilterConverterAsCacheEventFilterConverter<>(HotRodServer.ToEmptyBytesKeyValueFilterConverter.INSTANCE);
// We have to use storage format - otherwise passing converer will force it to change to incorrect format
return cache.addStorageFormatFilteredListenerAsync(clientEventSender, filter, converter, filterAnnotations);
} else if (useRawData) {
return cache.addStorageFormatFilteredListenerAsync(clientEventSender, filter, converter, filterAnnotations);
} else {
return cache.addFilteredListenerAsync(clientEventSender, filter, converter, filterAnnotations);
}
}
private CacheEventFilter<byte[], byte[]> getFilter(MediaType requestMedia, String name, Boolean useRawData, List<byte[]> binaryParams) {
CacheEventFilterFactory factory = findFactory(name, cacheEventFilterFactories, "key/value filter");
List<?> params = unmarshallParams(requestMedia, binaryParams, useRawData);
return factory.getFilter(params.toArray());
}
private CacheEventConverter<byte[], byte[], byte[]> getConverter(MediaType requestMedia, String name, Boolean useRawData, List<byte[]> binaryParams) {
CacheEventConverterFactory factory = findFactory(name, cacheEventConverterFactories, "converter");
List<?> params = unmarshallParams(requestMedia, binaryParams, useRawData);
return factory.getConverter(params.toArray());
}
private CacheEventFilterConverter<byte[], byte[], byte[]> getFilterConverter(MediaType requestMedia, String name, boolean useRawData, List<byte[]> binaryParams) {
CacheEventFilterConverterFactory factory = findFactory(name, cacheEventFilterConverterFactories, "converter");
List<?> params = unmarshallParams(requestMedia, binaryParams, useRawData);
return factory.getFilterConverter(params.toArray());
}
private <T> T findFactory(String name, ConcurrentMap<String, T> factories, String factoryType) {
T factory = factories.get(name);
if (factory == null) throw log.missingCacheEventFactory(factoryType, name);
return factory;
}
private List<?> unmarshallParams(MediaType requestMedia, List<byte[]> binaryParams, boolean useRawData) {
if (useRawData) return binaryParams;
return binaryParams.stream().map(bp -> encoderRegistry.convert(bp, requestMedia, APPLICATION_OBJECT)).collect(Collectors.toList());
}
CompletionStage<Boolean> removeClientListener(byte[] listenerId, Cache cache) {
Object sender = eventSenders.remove(new WrappedByteArray(listenerId));
if (sender != null) {
// No permission check needed: Either the client had the LISTEN permission to add the listener,
// or the listener was never added and removing it is a no-op
return SecurityActions.removeListenerAsync(cache, sender)
.thenCompose(ignore -> CompletableFutures.completedTrue());
} else return CompletableFutures.completedFalse();
}
public void stop() {
eventSenders.clear();
cacheEventFilterFactories.clear();
cacheEventConverterFactories.clear();
}
void findAndWriteEvents(Channel channel) {
// Make sure we write any event in main event loop
channel.eventLoop().execute(() -> eventSenders.values().forEach(s -> {
if (s instanceof BaseClientEventSender) {
BaseClientEventSender bces = (BaseClientEventSender) s;
if (bces.hasChannel(channel)) bces.writeEventsIfPossible();
}
}));
}
// Do not make sync=false, instead move cache operation causing
// listener calls out of the Netty event loop thread
@Listener(clustered = true, includeCurrentState = true)
private class StatefulClientEventSender extends BaseClientEventSender {
private final long messageId;
StatefulClientEventSender(Cache cache, Channel ch, VersionedEncoder encoder, byte[] listenerId, byte version, ClientEventType targetEventType, long messageId) {
super(cache, ch, encoder, listenerId, version, targetEventType);
this.messageId = messageId;
}
@Override
protected long getEventId(CacheEntryEvent event) {
return event.isCurrentState() ? messageId : 0;
}
}
@Listener(clustered = true)
private class StatelessClientEventSender extends BaseClientEventSender {
StatelessClientEventSender(Cache cache, Channel ch, VersionedEncoder encoder, byte[] listenerId, byte version, ClientEventType targetEventType) {
super(cache, ch, encoder, listenerId, version, targetEventType);
}
}
@Listener(clustered = true)
private class BloomAwareStatelessClientEventSender extends StatelessClientEventSender {
private final BloomFilter<byte[]> bloomFilter;
BloomAwareStatelessClientEventSender(Cache cache, Channel ch, VersionedEncoder encoder, byte[] listenerId,
byte version, ClientEventType targetEventType, BloomFilter<byte[]> bloomFilter) {
super(cache, ch, encoder, listenerId, version, targetEventType);
this.bloomFilter = bloomFilter;
}
boolean isSendEvent(CacheEntryEvent<byte[], byte[]> event) {
if (super.isSendEvent(event)) {
if (bloomFilter.possiblyPresent(event.getKey())) {
if (log.isTraceEnabled()) {
log.tracef("Event %s passed bloom filter", event);
}
return true;
} else if (log.isTraceEnabled()) {
log.tracef("Event %s didn't pass bloom filter", event);
}
}
return false;
}
}
private abstract class BaseClientEventSender {
protected final Channel ch;
protected final VersionedEncoder encoder;
protected final byte[] listenerId;
protected final byte version;
protected final ClientEventType targetEventType;
protected final Cache cache;
final int maxQueueSize = 100;
final AtomicInteger eventSize = new AtomicInteger();
final Queue<Events.Event> eventQueue = new ConcurrentLinkedQueue<>();
private final Runnable writeEventsIfPossible = this::writeEventsIfPossible;
BaseClientEventSender(Cache cache, Channel ch, VersionedEncoder encoder, byte[] listenerId, byte version, ClientEventType targetEventType) {
this.cache = cache;
this.ch = ch;
this.encoder = encoder;
this.listenerId = listenerId;
this.version = version;
this.targetEventType = targetEventType;
}
void init() {
ch.closeFuture().addListener(f -> {
log.debug("Channel disconnected, removing event sender listener for id: " + Util.printArray(listenerId));
removeClientListener(listenerId, cache)
.whenComplete((ignore, t) -> unblockCommands());
});
}
private void unblockCommands() {
// Have to allow all waiting listeners to proceed
for (Events.Event event : eventQueue) {
event.eventFuture.complete(null);
}
}
boolean hasChannel(Channel channel) {
return ch == channel;
}
// This method can only be invoked from the Event Loop thread!
void writeEventsIfPossible() {
boolean submittedUnblock = false;
boolean written = false;
while (!eventQueue.isEmpty() && ch.isWritable()) {
eventSize.decrementAndGet();
Events.Event event = eventQueue.remove();
if (log.isTraceEnabled()) log.tracef("Write event: %s to channel %s", event, ch);
CompletableFuture<Void> cf = event.eventFuture;
// We can just check instance equality as this is used to symbolize the event was not blocked below
if (cf != CompletableFutures.<Void>completedNull()) {
nonBlockingExecutor.execute(() -> event.eventFuture.complete(null));
}
ByteBuf buf = ch.alloc().ioBuffer();
encoder.writeEvent(event, buf);
ch.write(buf);
written = true;
}
if (written) {
ch.flush();
}
}
@CacheEntryCreated
@CacheEntryModified
@CacheEntryRemoved
@CacheEntryExpired
public CompletionStage<Void> onCacheEvent(CacheEntryEvent<byte[], byte[]> event) {
if (isSendEvent(event)) {
long version;
Metadata metadata;
if ((metadata = event.getMetadata()) != null && metadata.version() != null) {
version = ((NumericVersion) metadata.version()).getVersion();
} else {
version = 0;
}
Object k = event.getKey();
Object v = event.getValue();
return sendEvent((byte[]) k, (byte[]) v, version, event);
}
return null;
}
boolean isSendEvent(CacheEntryEvent<byte[], byte[]> event) {
if (isChannelDisconnected()) {
log.debug("Channel disconnected, ignoring event");
return false;
} else {
switch (event.getType()) {
case CACHE_ENTRY_CREATED:
case CACHE_ENTRY_MODIFIED:
return !event.isPre();
case CACHE_ENTRY_REMOVED:
CacheEntryRemovedEvent removedEvent = (CacheEntryRemovedEvent) event;
return !event.isPre() && removedEvent.getOldValue() != null;
case CACHE_ENTRY_EXPIRED:
return true;
default:
throw log.unexpectedEvent(event);
}
}
}
boolean isChannelDisconnected() {
return !ch.isOpen();
}
CompletionStage<Void> sendEvent(byte[] key, byte[] value, long dataVersion, CacheEntryEvent event) {
EventLoop loop = ch.eventLoop();
int size = eventSize.incrementAndGet();
boolean forceWait = size >= maxQueueSize;
final CompletableFuture<Void> cf;
if (forceWait) {
if (log.isTraceEnabled()) {
log.tracef("Pending event size is %s which is forcing %s to delay operation until it is sent", size, event);
}
cf = new CompletableFuture<>();
} else {
cf = CompletableFutures.completedNull();
}
Events.Event remoteEvent = createRemoteEvent(key, value, dataVersion, event, cf);
if (log.isTraceEnabled())
log.tracef("Queue event %s, before queuing event queue size is %d", remoteEvent, size - 1);
eventQueue.add(remoteEvent);
if (ch.isWritable()) {
// Make sure we write any event in main event loop
loop.submit(writeEventsIfPossible);
}
return cf;
}
private Events.Event createRemoteEvent(byte[] key, byte[] value, long dataVersion, CacheEntryEvent event,
CompletableFuture<Void> eventFuture) {
// Embedded listener event implementation implements all interfaces,
// so can't pattern match on the event instance itself. Instead, pattern
// match on the type and the cast down to the expected event instance type
switch (targetEventType) {
case PLAIN:
switch (event.getType()) {
case CACHE_ENTRY_CREATED:
case CACHE_ENTRY_MODIFIED:
KeyValuePair<HotRodOperation, Boolean> responseType = getEventResponseType(event);
return new Events.KeyWithVersionEvent(version, getEventId(event), responseType.getKey(), listenerId,
responseType.getValue(), key, dataVersion, eventFuture);
case CACHE_ENTRY_REMOVED:
case CACHE_ENTRY_EXPIRED:
responseType = getEventResponseType(event);
return new Events.KeyEvent(version, getEventId(event), responseType.getKey(), listenerId,
responseType.getValue(), key, eventFuture);
default:
throw log.unexpectedEvent(event);
}
case CUSTOM_PLAIN:
KeyValuePair<HotRodOperation, Boolean> responseType = getEventResponseType(event);
return new Events.CustomEvent(version, getEventId(event), responseType.getKey(), listenerId,
responseType.getValue(), value, eventFuture);
case CUSTOM_RAW:
responseType = getEventResponseType(event);
return new Events.CustomRawEvent(version, getEventId(event), responseType.getKey(), listenerId,
responseType.getValue(), value, eventFuture);
default:
throw new IllegalArgumentException("Event type not supported: " + targetEventType);
}
}
protected long getEventId(CacheEntryEvent event) {
return 0;
}
private KeyValuePair<HotRodOperation, Boolean> getEventResponseType(CacheEntryEvent event) {
switch (event.getType()) {
case CACHE_ENTRY_CREATED:
return new KeyValuePair<>(HotRodOperation.CACHE_ENTRY_CREATED_EVENT,
((CacheEntryCreatedEvent) event).isCommandRetried());
case CACHE_ENTRY_MODIFIED:
return new KeyValuePair<>(HotRodOperation.CACHE_ENTRY_MODIFIED_EVENT,
((CacheEntryModifiedEvent) event).isCommandRetried());
case CACHE_ENTRY_REMOVED:
return new KeyValuePair<>(HotRodOperation.CACHE_ENTRY_REMOVED_EVENT,
((CacheEntryRemovedEvent) event).isCommandRetried());
case CACHE_ENTRY_EXPIRED:
return new KeyValuePair<>(HotRodOperation.CACHE_ENTRY_EXPIRED_EVENT, false);
default:
throw log.unexpectedEvent(event);
}
}
}
private BaseClientEventSender getClientEventSender(boolean includeState, Channel ch, VersionedEncoder encoder,
byte version, Cache cache, byte[] listenerId,
ClientEventType eventType, long messageId,
BloomFilter<byte[]> bloomFilter) {
BaseClientEventSender bces;
if (includeState) {
bces = new StatefulClientEventSender(cache, ch, encoder, listenerId, version, eventType, messageId);
} else {
if (bloomFilter != null) {
bces = new BloomAwareStatelessClientEventSender(cache, ch, encoder, listenerId, version, eventType,
bloomFilter);
} else {
bces = new StatelessClientEventSender(cache, ch, encoder, listenerId, version, eventType);
}
}
bces.init();
return bces;
}
}
enum ClientEventType {
PLAIN,
CUSTOM_PLAIN,
CUSTOM_RAW;
static ClientEventType createType(boolean isCustom, boolean useRawData, byte version) {
if (isCustom) {
if (useRawData && HotRodVersion.HOTROD_21.isAtLeast(version)) {
return CUSTOM_RAW;
}
return CUSTOM_PLAIN;
}
return PLAIN;
}
}
| 25,135
| 44.618875
| 166
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodOperation.java
|
package org.infinispan.server.hotrod;
import java.util.EnumSet;
/**
* Enumeration defining all of the possible hotrod operations
*
* @author wburns
* @since 9.0
*/
public enum HotRodOperation {
// Puts
PUT(0x01, 0x02, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_VALUE, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_INDEXING, OpReqs.CAN_RETURN_PREVIOUS_VALUE, OpReqs.CAN_SKIP_CACHE_LOAD)),
PUT_IF_ABSENT(0x05, 0x06, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_VALUE, OpReqs.REQUIRES_AUTH, OpReqs.IS_CONDITIONAL, OpReqs.CAN_SKIP_INDEXING, OpReqs.CAN_RETURN_PREVIOUS_VALUE)),
// Replace
REPLACE(0x07, 0x08, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_VALUE, OpReqs.REQUIRES_AUTH, OpReqs.IS_CONDITIONAL, OpReqs.CAN_SKIP_INDEXING, OpReqs.CAN_RETURN_PREVIOUS_VALUE)),
REPLACE_IF_UNMODIFIED(0x09, 0x0A, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_VALUE, OpReqs.REQUIRES_AUTH, OpReqs.IS_CONDITIONAL, OpReqs.CAN_SKIP_INDEXING, OpReqs.CAN_RETURN_PREVIOUS_VALUE)),
// Contains
CONTAINS_KEY(0x0F, 0x10, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
// Gets
GET(0x03, 0x04, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
GET_WITH_VERSION(0x11, 0x12, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
GET_WITH_METADATA(0x1B, 0x1C, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
// Removes
REMOVE(0x0B, 0x0C, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_INDEXING, OpReqs.CAN_RETURN_PREVIOUS_VALUE, OpReqs.CAN_SKIP_CACHE_LOAD)),
REMOVE_IF_UNMODIFIED(0x0D, 0x0E, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_AUTH, OpReqs.IS_CONDITIONAL, OpReqs.CAN_SKIP_INDEXING, OpReqs.CAN_RETURN_PREVIOUS_VALUE)),
// Operation(s) that end after Header is read
PING(0x17, 0x18, EnumSet.noneOf(OpReqs.class)),
STATS(0x15, 0x16, EnumSet.of(OpReqs.REQUIRES_AUTH)),
CLEAR(0x13, 0x14, EnumSet.of(OpReqs.REQUIRES_AUTH)),
SIZE(0x29, 0x2A, EnumSet.of(OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
AUTH_MECH_LIST(0x21, 0x22, EnumSet.noneOf(OpReqs.class)),
// Operation(s) that end after Custom Header is read
AUTH(0x23, 0x24, EnumSet.noneOf(OpReqs.class)),
EXEC(0x2B, 0x2C, EnumSet.of(OpReqs.REQUIRES_AUTH)),
// Operations that end after a Custom Key is read
BULK_GET(0x19, 0x1A, EnumSet.of(OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
BULK_GET_KEYS(0x1D, 0x1E, EnumSet.of(OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
QUERY(0x1F, 0x20, EnumSet.of(OpReqs.REQUIRES_AUTH)),
ADD_CLIENT_LISTENER(0x25, 0x26, EnumSet.of(OpReqs.REQUIRES_AUTH)),
REMOVE_CLIENT_LISTENER(0x27, 0x28, EnumSet.of(OpReqs.REQUIRES_AUTH)),
ITERATION_START(0x31, 0x32, EnumSet.of(OpReqs.REQUIRES_AUTH)),
ITERATION_NEXT(0x33, 0x34, EnumSet.of(OpReqs.REQUIRES_AUTH)),
ITERATION_END(0x35, 0x36, EnumSet.of(OpReqs.REQUIRES_AUTH)),
ADD_BLOOM_FILTER_CLIENT_LISTENER(HotRodConstants.ADD_BLOOM_FILTER_NEAR_CACHE_LISTENER_REQUEST, HotRodConstants.ADD_BLOOM_FILTER_NEAR_CACHE_LISTENER_REQUEST + 1, EnumSet.of(OpReqs.REQUIRES_AUTH)),
UPDATE_BLOOM_FILTER(HotRodConstants.UPDATE_BLOOM_FILTER_REQUEST, HotRodConstants.UPDATE_BLOOM_FILTER_REQUEST + 1, EnumSet.of(OpReqs.REQUIRES_AUTH)),
// Operations that end after a Custom Value is read
PUT_ALL(0x2D, 0x2E, EnumSet.of(OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_INDEXING, OpReqs.CAN_SKIP_CACHE_LOAD)),
GET_ALL(0x2F, 0x30, EnumSet.of(OpReqs.REQUIRES_AUTH)),
// Stream operations
GET_STREAM(0x37, 0x38, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
PUT_STREAM(0x39, 0x3A, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_INDEXING, OpReqs.CAN_SKIP_CACHE_LOAD)),
// Transaction boundaries operations
PREPARE_TX(0x3B, 0x3C, EnumSet.of(OpReqs.REQUIRES_AUTH)),
COMMIT_TX(0x3D, 0x3E, EnumSet.of(OpReqs.REQUIRES_AUTH)),
ROLLBACK_TX(0x3F, 0x40, EnumSet.of(OpReqs.REQUIRES_AUTH)),
FORGET_TX(HotRodConstants.FORGET_TX, HotRodConstants.FORGET_TX + 1, EnumSet.of(OpReqs.REQUIRES_AUTH)),
FETCH_TX_RECOVERY(HotRodConstants.FETCH_TX_RECOVERY, HotRodConstants.FETCH_TX_RECOVERY + 1, EnumSet.of(OpReqs.REQUIRES_AUTH)),
PREPARE_TX_2(HotRodConstants.PREPARE_TX_2, HotRodConstants.PREPARE_TX_2 + 1, EnumSet.of(OpReqs.REQUIRES_AUTH)),
// Counter's operation [0x4B - 0x5F]
COUNTER_CREATE(0x4B, 0x4C, EnumSet.of(OpReqs.REQUIRES_AUTH)),
COUNTER_GET_CONFIGURATION(0x4D, 0x4E, EnumSet.of(OpReqs.REQUIRES_AUTH)),
COUNTER_IS_DEFINED(0x4F, 0x51, EnumSet.of(OpReqs.REQUIRES_AUTH)),
//skip 0x50 => ERROR
COUNTER_ADD_AND_GET(0x52, 0x53, EnumSet.of(OpReqs.REQUIRES_AUTH)),
COUNTER_RESET(0x54, 0x55, EnumSet.of(OpReqs.REQUIRES_AUTH)),
COUNTER_GET(0x56, 0x57, EnumSet.of(OpReqs.REQUIRES_AUTH)),
COUNTER_CAS(0x58, 0x59, EnumSet.of(OpReqs.REQUIRES_AUTH)),
COUNTER_ADD_LISTENER(0x5A, 0x5B, EnumSet.of(OpReqs.REQUIRES_AUTH)),
COUNTER_REMOVE_LISTENER(0x5C, 0x5D, EnumSet.of(OpReqs.REQUIRES_AUTH)),
COUNTER_REMOVE(0x5E, 0x5F, EnumSet.of(OpReqs.REQUIRES_AUTH)),
COUNTER_GET_NAMES(0x64, 0x65, EnumSet.of(OpReqs.REQUIRES_AUTH)),
COUNTER_GET_AND_SET(0x7F, 0x80, EnumSet.of(OpReqs.REQUIRES_AUTH)),
// Multimap operations
GET_MULTIMAP(0x67, 0x68, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
GET_MULTIMAP_WITH_METADATA(0x69, 0x6A, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
PUT_MULTIMAP(0x6B, 0x6C, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_VALUE, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
REMOVE_MULTIMAP(0x6D, 0x6E, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_VALUE, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
REMOVE_ENTRY_MULTIMAP(0x6F, 0x70, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_VALUE, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
SIZE_MULTIMAP(0x71, 0x72, EnumSet.of(OpReqs.REQUIRES_AUTH)),
CONTAINS_ENTRY_MULTIMAP(0x73, 0x74, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_VALUE, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
CONTAINS_KEY_MULTIMAP(0x75, 0x76, EnumSet.of(OpReqs.REQUIRES_KEY, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
CONTAINS_VALUE_MULTIMAP(0x77, 0x78, EnumSet.of(OpReqs.REQUIRES_VALUE, OpReqs.REQUIRES_AUTH, OpReqs.CAN_SKIP_CACHE_LOAD)),
// 0x79 => FORGET_TX request
// 0x7A => FORGET_TX response
// 0x7B => FETCH_TX_RECOVERY request
// 0x7C => FETCH_TX_RECOVERY response
// 0x7D => PREPARE_TX_2 request
// 0x7E => PREPARE_TX_2 response
// Responses
ERROR(0x50),
CACHE_ENTRY_CREATED_EVENT(0x60),
CACHE_ENTRY_MODIFIED_EVENT(0x61),
CACHE_ENTRY_REMOVED_EVENT(0x62),
CACHE_ENTRY_EXPIRED_EVENT(0x63),
COUNTER_EVENT(0x66);
private final int requestOpCode;
private final int responseOpCode;
private final boolean requiresAuthentication;
private final boolean canSkipIndexing;
private final boolean canSkipCacheLoading;
private final boolean canReturnPreviousValue;
private final boolean isConditional;
private static final HotRodOperation REQUEST_OPCODES[];
private static final HotRodOperation RESPONSE_OPCODES[];
public static final int REQUEST_COUNT;
static final HotRodOperation VALUES[] = values();
HotRodOperation(int requestOpCode, int responseOpCode, EnumSet<OpReqs> opRequirements) {
this.requestOpCode = requestOpCode;
this.responseOpCode = responseOpCode;
this.requiresAuthentication = opRequirements.contains(OpReqs.REQUIRES_AUTH);
this.canSkipIndexing = opRequirements.contains(OpReqs.CAN_SKIP_INDEXING);
this.canSkipCacheLoading = opRequirements.contains(OpReqs.CAN_SKIP_CACHE_LOAD);
this.canReturnPreviousValue = opRequirements.contains(OpReqs.CAN_RETURN_PREVIOUS_VALUE);
this.isConditional = opRequirements.contains(OpReqs.IS_CONDITIONAL);
}
HotRodOperation(int responseOpCode) {
this(0, responseOpCode, EnumSet.noneOf(OpReqs.class));
}
public int getRequestOpCode() {
return requestOpCode;
}
public int getResponseOpCode() {
return responseOpCode;
}
boolean requiresAuthentication() {
return requiresAuthentication;
}
boolean canSkipIndexing() {
return canSkipIndexing;
}
boolean canSkipCacheLoading() {
return canSkipCacheLoading;
}
boolean isNotConditionalAndCanReturnPrevious() {
return this == PUT;
}
boolean canReturnPreviousValue() {
return canReturnPreviousValue;
}
boolean isConditional() {
return isConditional;
}
static {
REQUEST_OPCODES = new HotRodOperation[256];
RESPONSE_OPCODES = new HotRodOperation[256];
int requestCount = 0;
for (HotRodOperation op : VALUES) {
if (op.requestOpCode > 0) {
REQUEST_OPCODES[op.requestOpCode] = op;
++requestCount;
}
if (op.responseOpCode > 0)
RESPONSE_OPCODES[op.responseOpCode] = op;
}
REQUEST_COUNT = requestCount;
}
public static HotRodOperation fromRequestOpCode(byte op) {
return REQUEST_OPCODES[op & 0xff];
}
public static HotRodOperation fromResponseOpCode(byte op) {
return RESPONSE_OPCODES[op & 0xff];
}
}
enum OpReqs {
REQUIRES_KEY,
REQUIRES_VALUE,
REQUIRES_AUTH,
CAN_SKIP_INDEXING,
CAN_SKIP_CACHE_LOAD,
CAN_RETURN_PREVIOUS_VALUE,
IS_CONDITIONAL
}
| 9,480
| 46.405
| 198
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/OperationStatus.java
|
package org.infinispan.server.hotrod;
import java.util.HashMap;
import java.util.Map;
/**
* Hot Rod operation possible status outcomes.
*
* @author Galder Zamarreño
* @since 4.1
*/
public enum OperationStatus {
// TODO: need to get codes
Success(0x00),
OperationNotExecuted(0x01),
KeyDoesNotExist(0x02),
SuccessWithPrevious(0x03),
NotExecutedWithPrevious(0x04),
InvalidIteration(0x05),
SuccessObjStorage(0x06),
SuccessWithPreviousObjStorage(0x07),
NotExecutedWithPreviousObjStorage(0x08),
InvalidMagicOrMsgId(0x81),
UnknownOperation(0x82),
UnknownVersion(0x83), // todo: test
ParseError(0x84), // todo: test
ServerError(0x85), // todo: test
OperationTimedOut(0x86), // todo: test
NodeSuspected(0x87),
IllegalLifecycleState(0x88),;
private final static Map<Byte, OperationStatus> intMap = new HashMap<>();
static {
for (OperationStatus status : OperationStatus.values()) {
intMap.put(status.code, status);
}
}
private final byte code;
OperationStatus(int code) {
this.code = (byte) code;
}
public byte getCode() {
return code;
}
public static OperationStatus fromCode(byte code) {
return intMap.get(code);
}
static OperationStatus withLegacyStorageHint(OperationStatus st, boolean isObjectStorage) {
if (isObjectStorage) {
switch (st) {
case Success:
return SuccessObjStorage;
case SuccessWithPrevious:
return SuccessWithPreviousObjStorage;
case NotExecutedWithPrevious:
return NotExecutedWithPreviousObjStorage;
default:
return st;
}
} else return st;
}
}
| 1,739
| 23.507042
| 94
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/BaseDecoder.java
|
package org.infinispan.server.hotrod;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.counter.EmbeddedCounterManagerFactory;
import org.infinispan.counter.impl.manager.EmbeddedCounterManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.core.ServerConstants;
import org.infinispan.server.core.telemetry.TelemetryService;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.server.hotrod.tracing.HotRodTelemetryService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.DecoderException;
abstract class BaseDecoder extends ByteToMessageDecoder {
protected final static Log log = LogFactory.getLog(BaseDecoder.class, Log.class);
protected final EmbeddedCacheManager cacheManager;
protected final Executor executor;
protected final HotRodServer server;
protected Authentication auth;
protected TransactionRequestProcessor cacheProcessor;
protected CounterRequestProcessor counterProcessor;
protected MultimapRequestProcessor multimapProcessor;
protected TaskRequestProcessor taskProcessor;
protected BaseDecoder(EmbeddedCacheManager cacheManager, Executor executor, HotRodServer server) {
this.cacheManager = cacheManager;
this.executor = executor;
this.server = server;
}
public Executor getExecutor() {
return executor;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
TelemetryService telemetryService = SecurityActions.getGlobalComponentRegistry(cacheManager)
.getComponent(TelemetryService.class);
if (telemetryService == null) {
telemetryService = new TelemetryService.NoTelemetry();
}
HotRodTelemetryService hotRodTelemetryService = new HotRodTelemetryService(telemetryService);
auth = new Authentication(ctx.channel(), executor, server);
cacheProcessor = new TransactionRequestProcessor(ctx.channel(), executor, server, hotRodTelemetryService);
counterProcessor = new CounterRequestProcessor(ctx.channel(), (EmbeddedCounterManager) EmbeddedCounterManagerFactory.asCounterManager(cacheManager), executor, server);
multimapProcessor = new MultimapRequestProcessor(ctx.channel(), executor, server);
taskProcessor = new TaskRequestProcessor(ctx.channel(), executor, server);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
if (log.isTraceEnabled()) {
log.tracef("Channel %s became active", ctx.channel());
}
server.getClientListenerRegistry().findAndWriteEvents(ctx.channel());
server.getClientCounterNotificationManager().channelActive(ctx.channel());
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
super.channelWritabilityChanged(ctx);
Channel channel = ctx.channel();
boolean writeable = channel.isWritable();
if (log.isTraceEnabled()) {
log.tracef("Channel %s writability changed to %b", channel, writeable);
}
if (writeable) {
server.getClientListenerRegistry().findAndWriteEvents(channel);
server.getClientCounterNotificationManager().channelActive(channel);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) throws Exception {
if (log.isTraceEnabled()) log.trace("Exception caught", t);
if (t instanceof DecoderException) {
t = t.getCause();
}
if (!ctx.channel().isActive() && t instanceof IllegalStateException &&
t.getMessage().equals("ssl is null")) {
// Workaround for ISPN-12996 -- OpenSSLEngine shut itself down too soon
// Ignore the exception, trying to write a response or close the context will cause a StackOverflowError
return;
}
cacheProcessor.writeException(getHeader(), t);
}
protected abstract HotRodHeader getHeader();
protected int defaultExpiration(int duration, int flags, ProtocolFlag defaultFlag) {
if (duration > 0) return duration;
return (flags & defaultFlag.getValue()) != 0 ? ServerConstants.EXPIRATION_DEFAULT : ServerConstants.EXPIRATION_NONE;
}
/**
* We usually know the size of the map ahead, and we want to return static empty map if we're not going to add anything.
*/
protected <K, V> Map<K, V> allocMap(int size) {
return size == 0 ? Collections.emptyMap() : new HashMap<>(size * 4/3, 0.75f);
}
protected <T> List<T> allocList(int size) {
return size == 0 ? Collections.emptyList() : new ArrayList<>(size);
}
protected <T> Set<T> allocSet(int size) {
return size == 0 ? Collections.emptySet() : new HashSet<>(size);
}
}
| 5,136
| 39.132813
| 173
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodDetector.java
|
package org.infinispan.server.hotrod;
import org.infinispan.server.core.MagicByteDetector;
public class HotRodDetector extends MagicByteDetector {
public static final String NAME = "hotrod-detector";
public HotRodDetector(HotRodServer hotRodServer) {
super(hotRodServer, Constants.MAGIC_REQ);
}
@Override
public String getName() {
return NAME;
}
}
| 382
| 21.529412
| 55
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/KeyValueVersionConverterFactory.java
|
package org.infinispan.server.hotrod;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory;
class KeyValueVersionConverterFactory implements CacheEventConverterFactory {
private KeyValueVersionConverterFactory() {
}
public static KeyValueVersionConverterFactory SINGLETON = new KeyValueVersionConverterFactory();
@Override
public <K, V, C> CacheEventConverter<K, V, C> getConverter(Object[] params) {
KeyValueVersionConverter converter;
// If a parameter is sent, we consider we want the old value. Don't consider the value
// Related to RemoteApplicationPublishedBridge where expiration and deletion events need the value
// https://issues.jboss.org/browse/ISPN-9634
if (params != null && params.length > 0) {
converter = KeyValueVersionConverter.INCLUDING_OLD_VALUE_CONVERTER;
} else {
converter = KeyValueVersionConverter.EXCLUDING_OLD_VALUE_CONVERTER;
}
return (CacheEventConverter<K, V, C>) converter;
}
}
| 1,108
| 41.653846
| 104
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/SingleHomedServerAddress.java
|
package org.infinispan.server.hotrod;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.net.InetAddress;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import org.infinispan.commons.marshall.AbstractExternalizer;
/**
* A Hot Rod server address
*
* @author Galder Zamarreño
* @since 5.1
*/
public class SingleHomedServerAddress implements ServerAddress {
private final String host;
private final int port;
public SingleHomedServerAddress(String host, int port) {
this.host = Objects.requireNonNull(host);
this.port = port;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SingleHomedServerAddress that = (SingleHomedServerAddress) o;
if (port != that.port) return false;
return host.equals(that.host);
}
@Override
public int hashCode() {
int result = host.hashCode();
result = 31 * result + port;
return result;
}
@Override
public String toString() {
return "SingleHomedServerAddress{" + "host='" + host + '\'' + ", port=" + port + '}';
}
@Override
public String getHost(InetAddress localAddress) {
return host;
}
public int getPort() {
return port;
}
static class Externalizer extends AbstractExternalizer<SingleHomedServerAddress> {
@Override
public Set<Class<? extends SingleHomedServerAddress>> getTypeClasses() {
return Collections.singleton(SingleHomedServerAddress.class);
}
@Override
public void writeObject(ObjectOutput output, SingleHomedServerAddress object) throws IOException {
output.writeObject(object.host);
output.writeShort(object.port);
}
@Override
public SingleHomedServerAddress readObject(ObjectInput input) throws IOException, ClassNotFoundException {
String host = (String) input.readObject();
int port = input.readUnsignedShort();
return new SingleHomedServerAddress(host, port);
}
}
}
| 2,138
| 25.407407
| 112
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/Authentication.java
|
package org.infinispan.server.hotrod;
import java.util.concurrent.Executor;
import javax.security.auth.Subject;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.server.core.configuration.SaslAuthenticationConfiguration;
import org.infinispan.server.core.security.sasl.SaslAuthenticator;
import org.infinispan.server.core.security.sasl.SubjectSaslServer;
import org.infinispan.server.core.transport.ConnectionMetadata;
import org.infinispan.server.core.transport.SaslQopHandler;
import org.infinispan.server.hotrod.configuration.HotRodServerConfiguration;
import org.infinispan.server.hotrod.logging.Log;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
/**
* Handler that when added will make sure authentication is applied to requests.
*
* @author wburns
* @since 9.0
*/
public class Authentication extends BaseRequestProcessor {
private final static Log log = LogFactory.getLog(Authentication.class, Log.class);
private final static Subject ANONYMOUS = new Subject();
public static final String HOTROD_SASL_PROTOCOL = "hotrod";
private final HotRodServerConfiguration serverConfig;
private final SaslAuthenticationConfiguration authenticationConfig;
private final boolean enabled;
private final boolean requireAuthentication;
private SaslServer saslServer;
private Subject subject = ANONYMOUS;
public Authentication(Channel channel, Executor executor, HotRodServer server) {
super(channel, executor, server);
serverConfig = server.getConfiguration();
authenticationConfig = serverConfig.authentication();
enabled = authenticationConfig.enabled();
requireAuthentication = !authenticationConfig.sasl().mechProperties().containsKey(Sasl.POLICY_NOANONYMOUS)
|| "true".equals(authenticationConfig.sasl().mechProperties().get(Sasl.POLICY_NOANONYMOUS));
}
public void authMechList(HotRodHeader header) {
writeResponse(header, header.encoder().authMechListResponse(header, server, channel, authenticationConfig.sasl().mechanisms()));
}
public void auth(HotRodHeader header, String mech, byte[] response) {
if (!enabled) {
UnsupportedOperationException cause = log.invalidOperation();
ByteBuf buf = header.encoder().errorResponse(header, server, channel, cause.toString(), OperationStatus.ServerError);
int responseBytes = buf.readableBytes();
ChannelFuture future = channel.writeAndFlush(buf);
if (header instanceof AccessLoggingHeader) {
server.accessLogging().logException(future, (AccessLoggingHeader) header, cause.toString(), responseBytes);
}
} else {
executor.execute(() -> {
try {
authInternal(header, mech, response);
} catch (Throwable t) {
disposeSaslServer();
String message = t.getMessage();
if (message.startsWith("ELY05055") || message.startsWith("ELY05051")) { // wrong credentials
writeException(header, log.authenticationException(t));
} else {
writeException(header, t);
}
}
});
}
}
private void authInternal(HotRodHeader header, String mech, byte[] response) throws Throwable {
if (saslServer == null) {
saslServer = SaslAuthenticator.createSaslServer(serverConfig.authentication().sasl(), channel, mech, HOTROD_SASL_PROTOCOL);
if (saslServer == null) {
throw log.invalidMech(mech);
}
}
byte[] serverChallenge = saslServer.evaluateResponse(response);
if (saslServer.isComplete()) {
authComplete(header, serverChallenge);
} else {
// Write the server challenge
writeResponse(header, header.encoder().authResponse(header, server, channel, serverChallenge));
}
}
private void authComplete(HotRodHeader header, byte[] serverChallenge) {
// Obtaining the subject might be expensive, so do it before sending the final server challenge, otherwise the
// client might send another operation before this is complete
subject = (Subject) saslServer.getNegotiatedProperty(SubjectSaslServer.SUBJECT);
ConnectionMetadata metadata = ConnectionMetadata.getInstance(channel);
metadata.subject(subject);
// Finally we setup the QOP handler if required
String qop = (String) saslServer.getNegotiatedProperty(Sasl.QOP);
if ("auth-int".equals(qop) || "auth-conf".equals(qop)) {
channel.eventLoop().submit(() -> {
writeResponse(header, header.encoder().authResponse(header, server, channel, serverChallenge));
SaslQopHandler qopHandler = new SaslQopHandler(saslServer);
channel.pipeline().addBefore("decoder", "saslQop", qopHandler);
});
} else {
// Send the final server challenge
writeResponse(header, header.encoder().authResponse(header, server, channel, serverChallenge));
disposeSaslServer();
saslServer = null;
}
}
private void disposeSaslServer() {
try {
if (saslServer != null)
saslServer.dispose();
} catch (SaslException e) {
log.debug("Exception while disposing SaslServer", e);
} finally {
saslServer = null;
}
}
public Subject getSubject(HotRodOperation operation) {
if (!enabled || !operation.requiresAuthentication()) {
return null;
}
// We haven't yet authenticated don't let them run other commands unless the command is fine
// not being authenticated
if (requireAuthentication && subject == ANONYMOUS) {
throw log.unauthorizedOperation(operation.name());
}
return subject;
}
}
| 5,959
| 40.103448
| 134
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/TimeUnitValue.java
|
package org.infinispan.server.hotrod;
import java.util.concurrent.TimeUnit;
import org.infinispan.util.KeyValuePair;
/**
* @author wburns
* @since 9.0
*/
public enum TimeUnitValue {
SECONDS(0x00),
MILLISECONDS(0x01),
NANOSECONDS(0x02),
MICROSECONDS(0x03),
MINUTES(0x04),
HOURS(0x05),
DAYS(0x06),
DEFAULT(0x07),
INFINITE(0x08);
private final byte code;
TimeUnitValue(int code) {
this.code = (byte) code;
}
public byte getCode() {
return code;
}
public TimeUnit toTimeUnit() {
switch (code) {
case 0x00:
return TimeUnit.SECONDS;
case 0x01:
return TimeUnit.MILLISECONDS;
case 0x02:
return TimeUnit.NANOSECONDS;
case 0x03:
return TimeUnit.MICROSECONDS;
case 0x04:
return TimeUnit.MINUTES;
case 0x05:
return TimeUnit.HOURS;
case 0x06:
return TimeUnit.DAYS;
default:
throw new IllegalArgumentException("TimeUnit not supported for: " + code);
}
}
public static TimeUnitValue fromTimeUnit(TimeUnit unit) {
switch (unit) {
case MICROSECONDS:
return TimeUnitValue.MICROSECONDS;
case MILLISECONDS:
return TimeUnitValue.MILLISECONDS;
case SECONDS:
return TimeUnitValue.SECONDS;
case MINUTES:
return TimeUnitValue.MINUTES;
case HOURS:
return TimeUnitValue.HOURS;
case DAYS:
return TimeUnitValue.DAYS;
default:
throw new IllegalArgumentException(unit.name());
}
}
public static TimeUnitValue decode(byte rightBits) {
switch (rightBits) {
case 0x00:
return SECONDS;
case 0x01:
return MILLISECONDS;
case 0x02:
return NANOSECONDS;
case 0x03:
return MICROSECONDS;
case 0x04:
return MINUTES;
case 0x05:
return HOURS;
case 0x06:
return DAYS;
case 0x07:
return DEFAULT;
case 0x08:
return INFINITE;
default:
throw new IllegalArgumentException("Unsupported byte value: " + rightBits);
}
}
public static KeyValuePair<TimeUnitValue, TimeUnitValue> decodePair(byte timeUnitValues) {
return new KeyValuePair<>(decode((byte) ((timeUnitValues & 0xf0) >> 4)), decode((byte) (timeUnitValues & 0x0f)));
}
private static byte encodeDuration(long duration, TimeUnit timeUnit) {
return duration == 0 ? DEFAULT.code : duration < 0 ? INFINITE.code : fromTimeUnit(timeUnit).code;
}
public static byte encodeTimeUnits(long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit) {
byte encodedLifespan = encodeDuration(lifespan, lifespanTimeUnit);
byte encodedMaxIdle = encodeDuration(maxIdle, maxIdleTimeUnit);
return (byte) (encodedLifespan << 4 | encodedMaxIdle);
}
}
| 3,049
| 26.477477
| 121
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/MetadataUtils.java
|
package org.infinispan.server.hotrod;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.container.versioning.EntryVersion;
import org.infinispan.container.versioning.NumericVersion;
import org.infinispan.container.versioning.SimpleClusteredVersion;
import org.infinispan.server.hotrod.transport.ExtendedByteBuf;
import io.netty.buffer.ByteBuf;
/**
* Utility class in hotrod server with methods handling cache entries metadata
*
* @author Katia Aresti, karesti@redhat.com
* @since 9.2
*/
public final class MetadataUtils {
private MetadataUtils() {
}
public static void writeMetadata(int lifespan, int maxIdle, long created, long lastUsed, long dataVersion, ByteBuf buf) {
int flags = (lifespan < 0 ? Constants.INFINITE_LIFESPAN : 0) + (maxIdle < 0 ? Constants.INFINITE_MAXIDLE : 0);
buf.writeByte(flags);
if (lifespan >= 0) {
buf.writeLong(created);
ExtendedByteBuf.writeUnsignedInt(lifespan, buf);
}
if (maxIdle >= 0) {
buf.writeLong(lastUsed);
ExtendedByteBuf.writeUnsignedInt(maxIdle, buf);
}
buf.writeLong(dataVersion);
}
public static long extractVersion(CacheEntry ce) {
if (ce == null) return -1;
EntryVersion entryVersion = ce.getMetadata().version();
long version = 0;
if (entryVersion != null) {
if (entryVersion instanceof NumericVersion) {
version = NumericVersion.class.cast(entryVersion).getVersion();
}
if (entryVersion instanceof SimpleClusteredVersion) {
version = SimpleClusteredVersion.class.cast(entryVersion).getVersion();
}
}
return version;
}
public static long extractCreated(CacheEntry ce) {
if (ce == null) return -1;
return ce.getCreated();
}
public static long extractLastUsed(CacheEntry ce) {
if (ce == null) return -1;
return ce.getLastUsed();
}
public static int extractLifespan(CacheEntry ce) {
if (ce == null) return -1;
return ce.getLifespan() < 0 ? -1 : (int) (ce.getLifespan() / 1000);
}
public static int extractMaxIdle(CacheEntry ce) {
if (ce == null) return -1;
return ce.getMaxIdle() < 0 ? -1 : (int) (ce.getMaxIdle() / 1000);
}
}
| 2,279
| 29
| 124
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/TaskRequestProcessor.java
|
package org.infinispan.server.hotrod;
import java.util.Map;
import java.util.concurrent.Executor;
import javax.security.auth.Subject;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.util.Util;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.tasks.TaskContext;
import org.infinispan.tasks.TaskManager;
import io.netty.channel.Channel;
public class TaskRequestProcessor extends BaseRequestProcessor {
private static final Log log = LogFactory.getLog(TaskRequestProcessor.class, Log.class);
private final HotRodServer server;
private final TaskManager taskManager;
TaskRequestProcessor(Channel channel, Executor executor, HotRodServer server) {
super(channel, executor, server);
this.server = server;
this.taskManager = SecurityActions.getGlobalComponentRegistry(server.getCacheManager()).getComponent(TaskManager.class);
}
public void exec(HotRodHeader header, Subject subject, String taskName, Map<String, byte[]> taskParams) {
TaskContext taskContext = new TaskContext()
.parameters(taskParams)
.subject(subject);
if (!header.cacheName.isEmpty() || server.hasDefaultCache()) {
AdvancedCache<byte[], byte[]> cache = server.cache(server.getCacheInfo(header), header, subject);
taskContext.cache(cache);
}
taskManager.runTask(taskName, taskContext).whenComplete((result, throwable) -> handleExec(header, result, throwable));
}
private void handleExec(HotRodHeader header, Object result, Throwable throwable) {
if (throwable != null) {
writeException(header, throwable);
} else {
if (result != null && !(result instanceof byte[])) {
writeException(header, log.errorSerializingResponse(result));
} else {
writeResponse(header, header.encoder().valueResponse(header, server, channel, OperationStatus.Success,
result == null ? Util.EMPTY_BYTE_ARRAY : (byte[]) result));
}
}
}
}
| 2,136
| 37.854545
| 126
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/MultimapRequestProcessor.java
|
package org.infinispan.server.hotrod;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.Executor;
import java.util.function.BiConsumer;
import javax.security.auth.Subject;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.util.logging.LogFactory;
import io.netty.channel.Channel;
class MultimapRequestProcessor extends BaseRequestProcessor {
private static final Log log = LogFactory.getLog(MultimapRequestProcessor.class, Log.class);
MultimapRequestProcessor(Channel channel, Executor executor, HotRodServer server) {
super(channel, executor, server);
}
void get(HotRodHeader header, Subject subject, byte[] key, boolean supportsDuplicates) {
if (log.isTraceEnabled()) {
log.trace("Call get");
}
server.multimap(header, subject, supportsDuplicates).get(key).whenComplete(
(result, throwable) -> handleGet(header, result, throwable));
}
private void handleGet(HotRodHeader header, Collection<byte[]> result, Throwable throwable) {
if (throwable != null) {
writeException(header, throwable);
} else try {
OperationStatus status = OperationStatus.Success;
if (result.isEmpty()) {
writeNotExist(header);
return;
}
writeResponse(header, header.encoder().multimapCollectionResponse(header, server, channel, status, result));
} catch (Throwable t2) {
writeException(header, t2);
}
}
void getWithMetadata(HotRodHeader header, Subject subject, byte[] key, boolean supportsDuplicates) {
if (log.isTraceEnabled()) {
log.trace("Call getWithMetadata");
}
server.multimap(header, subject, supportsDuplicates).getEntry(key).whenComplete((entry, throwable) -> handleGetWithMetadata(header, entry, throwable));
}
private void handleGetWithMetadata(HotRodHeader header, Optional<CacheEntry<byte[], Collection<byte[]>>> entry, Throwable throwable) {
if (throwable != null) {
writeException(header, throwable);
} else try {
if (!entry.isPresent()) {
writeNotExist(header);
return;
}
OperationStatus status = OperationStatus.Success;
CacheEntry<byte[], Collection<byte[]>> ce = entry.get();
writeResponse(header, header.encoder().multimapEntryResponse(header, server, channel, status, ce));
} catch (Throwable t2) {
writeException(header, t2);
}
}
void put(HotRodHeader header, Subject subject, byte[] key, byte[] value, boolean supportsDuplicates) {
if (log.isTraceEnabled()) {
log.trace("Call put");
}
server.multimap(header, subject, supportsDuplicates).put(key, value).whenComplete((result, throwable) -> {
if (throwable != null) {
writeException(header, throwable);
} else {
writeResponse(header, header.encoder().emptyResponse(header, server, channel, OperationStatus.Success));
}
});
}
void removeKey(HotRodHeader header, Subject subject, byte[] key, boolean supportsDuplicates) {
if (log.isTraceEnabled()) {
log.trace("Call removeKey");
}
server.multimap(header, subject, supportsDuplicates).remove(key).whenComplete(handleBoolean(header));
}
void removeEntry(HotRodHeader header, Subject subject, byte[] key, byte[] value, boolean supportsDuplicates) {
log.trace("Call removeEntry");
server.multimap(header, subject, supportsDuplicates).remove(key, value).whenComplete(handleBoolean(header));
}
void size(HotRodHeader header, Subject subject, boolean supportsDuplicates) {
log.trace("Call size");
server.multimap(header, subject, supportsDuplicates).size().whenComplete((result, throwable) -> {
if (throwable != null) {
writeException(header, throwable);
} else {
writeResponse(header, header.encoder().unsignedLongResponse(header, server, channel, result));
}
});
}
void containsEntry(HotRodHeader header, Subject subject, byte[] key, byte[] value, boolean supportsDuplicates) {
log.trace("Call containsEntry");
server.multimap(header, subject, supportsDuplicates).containsEntry(key, value).whenComplete(handleBoolean(header));
}
void containsKey(HotRodHeader header, Subject subject, byte[] key, boolean supportsDuplicates) {
log.trace("Call containsKey");
server.multimap(header, subject, supportsDuplicates).containsKey(key).whenComplete(handleBoolean(header));
}
void containsValue(HotRodHeader header, Subject subject, byte[] value, boolean supportsDuplicates) {
log.trace("Call containsValue");
server.multimap(header, subject, supportsDuplicates).containsValue(value).whenComplete(handleBoolean(header));
}
private BiConsumer<Boolean, Throwable> handleBoolean(HotRodHeader header) {
return (result, throwable) -> {
if (throwable != null) {
writeException(header, throwable);
} else {
writeResponse(header, header.encoder().booleanResponse(header, server, channel, result));
}
};
}
}
| 5,262
| 39.484615
| 157
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodUtils.java
|
package org.infinispan.server.hotrod;
import java.io.StreamCorruptedException;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.dataconversion.MediaType;
class UnknownVersionException extends StreamCorruptedException {
final byte version;
final long messageId;
public UnknownVersionException(String cause, byte version, long messageId) {
super(cause);
this.version = version;
this.messageId = messageId;
}
public HotRodHeader toHeader() {
return new HotRodHeader(HotRodOperation.ERROR, version, messageId, "", 0, (short) 1, 0, MediaType.MATCH_ALL, MediaType.MATCH_ALL, null);
}
}
class HotRodUnknownOperationException extends UnknownOperationException {
final byte version;
final long messageId;
public HotRodUnknownOperationException(String cause, byte version, long messageId) {
super(cause);
this.version = version;
this.messageId = messageId;
}
public HotRodHeader toHeader() {
return new HotRodHeader(HotRodOperation.ERROR, version, messageId, "", 0, (short) 1, 0, MediaType.MATCH_ALL, MediaType.MATCH_ALL, null);
}
}
class InvalidMagicIdException extends StreamCorruptedException {
public InvalidMagicIdException(String cause) {
super(cause);
}
}
class CacheUnavailableException extends CacheException {
}
class RequestParsingException extends CacheException {
final byte version;
final long messageId;
public RequestParsingException(String reason, byte version, long messageId, Exception cause) {
super(reason, cause);
this.version = version;
this.messageId = messageId;
}
public RequestParsingException(String reason, byte version, long messageId) {
super(reason);
this.version = version;
this.messageId = messageId;
}
public HotRodHeader toHeader() {
return new HotRodHeader(HotRodOperation.ERROR, version, messageId, "", 0, (short) 1, 0, MediaType.MATCH_ALL, MediaType.MATCH_ALL, null);
}
}
class CacheNotFoundException extends RequestParsingException {
public CacheNotFoundException(String reason, byte version, long messageId) {
super(reason, version, messageId);
}
}
class UnknownOperationException extends StreamCorruptedException {
public UnknownOperationException(String reason) {
super(reason);
}
}
| 2,346
| 28.3375
| 142
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/Encoder2x.java
|
package org.infinispan.server.hotrod;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.counter.util.EncodeUtil.encodeConfiguration;
import static org.infinispan.server.core.transport.VInt.write;
import static org.infinispan.server.hotrod.transport.ExtendedByteBuf.writeString;
import static org.infinispan.server.hotrod.transport.ExtendedByteBuf.writeUnsignedInt;
import static org.infinispan.server.hotrod.transport.ExtendedByteBuf.writeUnsignedLong;
import static org.infinispan.server.hotrod.transport.ExtendedByteBuf.writeXid;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.PrivilegedActionException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.CacheSet;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.MediaTypeIds;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.impl.CounterModuleLifecycle;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.jgroups.SuspectException;
import org.infinispan.server.core.transport.NettyTransport;
import org.infinispan.server.core.transport.VInt;
import org.infinispan.server.hotrod.counter.listener.ClientCounterEvent;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.server.hotrod.transport.ExtendedByteBuf;
import org.infinispan.server.iteration.IterableIterationResult;
import org.infinispan.stats.ClusterCacheStats;
import org.infinispan.stats.Stats;
import org.infinispan.topology.CacheTopology;
import org.jgroups.SuspectedException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
/**
* @author Galder Zamarreño
*/
class Encoder2x implements VersionedEncoder {
private static final Log log = LogFactory.getLog(Encoder2x.class, Log.class);
private static final int topologyCheckInterval = Integer.getInteger("infinispan.server.topology-check-interval", 5_000);
private static final Encoder2x INSTANCE = new Encoder2x();
private final ConcurrentMap<ChannelId, LastKnownClientTopologyId> lastKnownTopologyIds = topologyCheckInterval > 0 ? new ConcurrentHashMap<>() : null;
private static class LastKnownClientTopologyId {
private final int topologyId;
private final long timeCaptured;
private LastKnownClientTopologyId(int topologyId, long timeCaptured) {
this.topologyId = topologyId;
this.timeCaptured = timeCaptured;
}
}
protected Encoder2x() {
}
public static Encoder2x instance() {
return INSTANCE;
}
@Override
public void writeEvent(Events.Event e, ByteBuf buf) {
writeHeaderNoTopology(buf, e.messageId, e.op);
ExtendedByteBuf.writeRangedBytes(e.listenerId, buf);
e.writeEvent(buf);
}
@Override
public ByteBuf authResponse(HotRodHeader header, HotRodServer server, Channel channel, byte[] challenge) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
if (challenge != null) {
buf.writeBoolean(false);
ExtendedByteBuf.writeRangedBytes(challenge, buf);
} else {
buf.writeBoolean(true);
ExtendedByteBuf.writeUnsignedInt(0, buf);
}
return buf;
}
@Override
public ByteBuf authMechListResponse(HotRodHeader header, HotRodServer server, Channel channel, Set<String> mechs) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
ExtendedByteBuf.writeUnsignedInt(mechs.size(), buf);
for (String s : mechs) {
ExtendedByteBuf.writeString(s, buf);
}
return buf;
}
@Override
public ByteBuf notExecutedResponse(HotRodHeader header, HotRodServer server, Channel channel, CacheEntry<byte[], byte[]> prev) {
return valueResponse(header, server, channel, OperationStatus.NotExecutedWithPrevious, prev);
}
@Override
public ByteBuf notExistResponse(HotRodHeader header, HotRodServer server, Channel channel) {
return emptyResponse(header, server, channel, OperationStatus.KeyDoesNotExist);
}
@Override
public ByteBuf valueResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status, byte[] prev) {
ByteBuf buf = writeHeader(header, server, channel, status);
if (prev == null) {
ExtendedByteBuf.writeUnsignedInt(0, buf);
} else {
ExtendedByteBuf.writeRangedBytes(prev, buf);
}
if (log.isTraceEnabled()) {
log.tracef("Write response to %s messageId=%d status=%s prev=%s", header.op, header.messageId, status, Util.printArray(prev));
}
return buf;
}
@Override
public ByteBuf valueResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status, CacheEntry<byte[], byte[]> prev) {
return valueResponse(header, server, channel, status, prev != null ? prev.getValue() : null);
}
@Override
public ByteBuf successResponse(HotRodHeader header, HotRodServer server, Channel channel, CacheEntry<byte[], byte[]> result) {
return valueResponse(header, server, channel, OperationStatus.SuccessWithPrevious, result);
}
@Override
public ByteBuf errorResponse(HotRodHeader header, HotRodServer server, Channel channel, String message, OperationStatus status) {
ByteBuf buf = writeHeader(header, server, channel, status);
ExtendedByteBuf.writeString(message, buf);
return buf;
}
@Override
public ByteBuf bulkGetResponse(HotRodHeader header, HotRodServer server, Channel channel, int size, CacheSet<Map.Entry<byte[], byte[]>> entries) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
try (CloseableIterator<Map.Entry<byte[], byte[]>> iterator = entries.iterator()) {
int max = Integer.MAX_VALUE;
if (size != 0) {
if (log.isTraceEnabled()) log.tracef("About to write (max) %d messages to the client", size);
max = size;
}
int count = 0;
while (iterator.hasNext() && count < max) {
Map.Entry<byte[], byte[]> entry = iterator.next();
buf.writeByte(1); // Not done
ExtendedByteBuf.writeRangedBytes(entry.getKey(), buf);
ExtendedByteBuf.writeRangedBytes(entry.getValue(), buf);
count++;
}
buf.writeByte(0); // Done
}
return buf;
}
@Override
public ByteBuf emptyResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status) {
return writeHeader(header, server, channel, status);
}
@Override
public ByteBuf pingResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status) {
if (HotRodVersion.HOTROD_30.isAtLeast(header.version)) {
ByteBuf buf = writeHeader(header, server, channel, status, true);
buf.writeByte(HotRodVersion.LATEST.getVersion());
ExtendedByteBuf.writeUnsignedInt(HotRodOperation.REQUEST_COUNT, buf);
for (HotRodOperation op : HotRodOperation.VALUES) {
// We only include request ops
if (op.getRequestOpCode() > 0) {
buf.writeShort(op.getRequestOpCode());
}
}
return buf;
} else {
return writeHeader(header, server, channel, status, true);
}
}
@Override
public ByteBuf statsResponse(HotRodHeader header, HotRodServer server, Channel channel, Stats stats,
NettyTransport transport, ClusterCacheStats clusterCacheStats) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
int numStats = 10;
if (transport != null) {
numStats += 2;
}
if (HotRodVersion.HOTROD_24.isAtLeast(header.version)) {
if (clusterCacheStats != null) {
numStats += 9;
}
} else {
// Ignore the cluster stats
clusterCacheStats = null;
}
ExtendedByteBuf.writeUnsignedInt(numStats, buf);
writePair(buf, "timeSinceStart", String.valueOf(stats.getTimeSinceStart()));
writePair(buf, "currentNumberOfEntries", String.valueOf(stats.getCurrentNumberOfEntries()));
writePair(buf, "stores", String.valueOf(stats.getStores()));
writePair(buf, "retrievals", String.valueOf(stats.getRetrievals()));
writePair(buf, "hits", String.valueOf(stats.getHits()));
writePair(buf, "misses", String.valueOf(stats.getMisses()));
writePair(buf, "removeHits", String.valueOf(stats.getRemoveHits()));
writePair(buf, "removeMisses", String.valueOf(stats.getRemoveMisses()));
writePair(buf, "approximateEntries", String.valueOf(stats.getApproximateEntries()));
writePair(buf, "approximateEntriesUnique", String.valueOf(stats.getApproximateEntriesUnique()));
if (transport != null) {
writePair(buf, "totalBytesRead", String.valueOf(transport.getTotalBytesRead()));
writePair(buf, "totalBytesWritten", String.valueOf(transport.getTotalBytesWritten()));
}
if (clusterCacheStats != null) {
writePair(buf, "globalCurrentNumberOfEntries", String.valueOf(clusterCacheStats.getCurrentNumberOfEntries()));
writePair(buf, "globalStores", String.valueOf(clusterCacheStats.getStores()));
writePair(buf, "globalRetrievals", String.valueOf(clusterCacheStats.getRetrievals()));
writePair(buf, "globalHits", String.valueOf(clusterCacheStats.getHits()));
writePair(buf, "globalMisses", String.valueOf(clusterCacheStats.getMisses()));
writePair(buf, "globalRemoveHits", String.valueOf(clusterCacheStats.getRemoveHits()));
writePair(buf, "globalRemoveMisses", String.valueOf(clusterCacheStats.getRemoveMisses()));
writePair(buf, "globalApproximateEntries", String.valueOf(clusterCacheStats.getApproximateEntries()));
writePair(buf, "globalApproximateEntriesUnique", String.valueOf(clusterCacheStats.getApproximateEntriesUnique()));
}
return buf;
}
private void writePair(ByteBuf buf, String key, String value) {
ExtendedByteBuf.writeString(key, buf);
ExtendedByteBuf.writeString(value, buf);
}
@Override
public ByteBuf valueWithVersionResponse(HotRodHeader header, HotRodServer server, Channel channel, byte[] value, long version) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
buf.writeLong(version);
ExtendedByteBuf.writeRangedBytes(value, buf);
return buf;
}
@Override
public ByteBuf getWithMetadataResponse(HotRodHeader header, HotRodServer server, Channel channel, CacheEntry<byte[], byte[]> entry) {
return writeMetadataResponse(header, server, channel, OperationStatus.Success, entry);
}
protected ByteBuf writeMetadataResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status, CacheEntry<byte[], byte[]> entry) {
ByteBuf buf = writeHeader(header, server, channel, status);
MetadataUtils.writeMetadata(MetadataUtils.extractLifespan(entry), MetadataUtils.extractMaxIdle(entry),
MetadataUtils.extractCreated(entry), MetadataUtils.extractLastUsed(entry), MetadataUtils.extractVersion(entry), buf);
ExtendedByteBuf.writeRangedBytes(entry != null ? entry.getValue() : Util.EMPTY_BYTE_ARRAY, buf);
return buf;
}
@Override
public ByteBuf getStreamResponse(HotRodHeader header, HotRodServer server, Channel channel, int offset, CacheEntry<byte[], byte[]> entry) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
MetadataUtils.writeMetadata(MetadataUtils.extractLifespan(entry), MetadataUtils.extractMaxIdle(entry),
MetadataUtils.extractCreated(entry), MetadataUtils.extractLastUsed(entry), MetadataUtils.extractVersion(entry), buf);
ExtendedByteBuf.writeRangedBytes(entry.getValue(), offset, buf);
return buf;
}
@Override
public ByteBuf getAllResponse(HotRodHeader header, HotRodServer server, Channel channel, Map<byte[], byte[]> entries) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
ExtendedByteBuf.writeUnsignedInt(entries.size(), buf);
for (Map.Entry<byte[], byte[]> entry : entries.entrySet()) {
ExtendedByteBuf.writeRangedBytes(entry.getKey(), buf);
ExtendedByteBuf.writeRangedBytes(entry.getValue(), buf);
}
return buf;
}
@Override
public ByteBuf bulkGetKeysResponse(HotRodHeader header, HotRodServer server, Channel channel, CloseableIterator<byte[]> iterator) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
while (iterator.hasNext()) {
buf.writeByte(1);
ExtendedByteBuf.writeRangedBytes(iterator.next(), buf);
}
buf.writeByte(0);
return buf;
}
@Override
public ByteBuf iterationStartResponse(HotRodHeader header, HotRodServer server, Channel channel, String iterationId) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
ExtendedByteBuf.writeString(iterationId, buf);
return buf;
}
@Override
public ByteBuf iterationNextResponse(HotRodHeader header, HotRodServer server, Channel channel, IterableIterationResult iterationResult) {
OperationStatus status;
switch (iterationResult.getStatusCode()) {
case Success:
case Finished:
status = OperationStatus.Success;
break;
case InvalidIteration:
status = OperationStatus.InvalidIteration;
break;
default:
throw new IllegalStateException("Unknown iteration result status " + iterationResult.getStatusCode());
}
ByteBuf buf = writeHeader(header, server, channel, status);
ExtendedByteBuf.writeRangedBytes(iterationResult.segmentsToBytes(), buf);
List<CacheEntry> entries = iterationResult.getEntries();
ExtendedByteBuf.writeUnsignedInt(entries.size(), buf);
Optional<Integer> projectionLength = projectionInfo(entries, header.version);
projectionLength.ifPresent(i -> ExtendedByteBuf.writeUnsignedInt(i, buf));
for (CacheEntry cacheEntry : entries) {
if (HotRodVersion.HOTROD_25.isAtLeast(header.version)) {
if (iterationResult.isMetadata()) {
buf.writeByte(1);
InternalCacheEntry ice = (InternalCacheEntry) cacheEntry;
int lifespan = ice.getLifespan() < 0 ? -1 : (int) (ice.getLifespan() / 1000);
int maxIdle = ice.getMaxIdle() < 0 ? -1 : (int) (ice.getMaxIdle() / 1000);
long lastUsed = ice.getLastUsed();
long created = ice.getCreated();
long dataVersion = MetadataUtils.extractVersion(ice);
MetadataUtils.writeMetadata(lifespan, maxIdle, created, lastUsed, dataVersion, buf);
} else {
buf.writeByte(0);
}
}
Object key = iterationResult.getResultFunction().apply(cacheEntry.getKey());
Object value = cacheEntry.getValue();
ExtendedByteBuf.writeRangedBytes((byte[]) key, buf);
if (value instanceof Object[]) {
for (Object o : (Object[]) value) {
ExtendedByteBuf.writeRangedBytes((byte[]) o, buf);
}
} else if (value instanceof byte[]) {
ExtendedByteBuf.writeRangedBytes((byte[]) value, buf);
} else {
throw new IllegalArgumentException("Unsupported type passed: " + value.getClass());
}
}
return buf;
}
@Override
public ByteBuf counterConfigurationResponse(HotRodHeader header, HotRodServer server, Channel channel, CounterConfiguration configuration) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
encodeConfiguration(configuration, buf::writeByte, buf::writeLong,
value -> ExtendedByteBuf.writeUnsignedInt(value, buf));
return buf;
}
@Override
public ByteBuf counterNamesResponse(HotRodHeader header, HotRodServer server, Channel channel, Collection<String> counterNames) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
write(buf, counterNames.size());
for (String s : counterNames) {
writeString(s, buf);
}
return buf;
}
@Override
public ByteBuf multimapCollectionResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status, Collection<byte[]> values) {
ByteBuf buf = writeHeader(header, server, channel, status);
ExtendedByteBuf.writeUnsignedInt(values.size(), buf);
for (byte[] v : values) {
ExtendedByteBuf.writeRangedBytes(v, buf);
}
return buf;
}
@Override
public ByteBuf multimapEntryResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status, CacheEntry<byte[], Collection<byte[]>> entry) {
ByteBuf buf = writeHeader(header, server, channel, status);
MetadataUtils.writeMetadata(MetadataUtils.extractLifespan(entry), MetadataUtils.extractMaxIdle(entry),
MetadataUtils.extractCreated(entry), MetadataUtils.extractLastUsed(entry), MetadataUtils.extractVersion(entry), buf);
Collection<byte[]> values = entry.getValue();
if (values == null) {
buf.writeByte(0);
} else {
ExtendedByteBuf.writeUnsignedInt(values.size(), buf);
for (byte[] v : values) {
ExtendedByteBuf.writeRangedBytes(v, buf);
}
}
return buf;
}
@Override
public ByteBuf booleanResponse(HotRodHeader header, HotRodServer server, Channel channel, boolean result) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
buf.writeByte(result ? 1 : 0);
return buf;
}
@Override
public ByteBuf unsignedLongResponse(HotRodHeader header, HotRodServer server, Channel channel, long value) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
ExtendedByteBuf.writeUnsignedLong(value, buf);
return buf;
}
@Override
public ByteBuf longResponse(HotRodHeader header, HotRodServer server, Channel channel, long value) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
buf.writeLong(value);
return buf;
}
@Override
public ByteBuf transactionResponse(HotRodHeader header, HotRodServer server, Channel channel, int xaReturnCode) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
buf.writeInt(xaReturnCode);
return buf;
}
@Override
public ByteBuf recoveryResponse(HotRodHeader header, HotRodServer server, Channel channel, Collection<XidImpl> xids) {
ByteBuf buf = writeHeader(header, server, channel, OperationStatus.Success);
writeUnsignedInt(xids.size(), buf);
for (XidImpl xid : xids) {
writeXid(xid, buf);
}
return buf;
}
@Override
public OperationStatus errorStatus(Throwable t) {
if (t instanceof SuspectException) {
return OperationStatus.NodeSuspected;
} else if (t instanceof IllegalLifecycleStateException) {
return OperationStatus.IllegalLifecycleState;
} else if (t instanceof CacheException) {
// JGroups and remote exceptions (inside RemoteException) can come wrapped up
Throwable cause = t.getCause() == null ? t : t.getCause();
if (cause instanceof SuspectedException) {
return OperationStatus.NodeSuspected;
} else if (cause instanceof IllegalLifecycleStateException) {
return OperationStatus.IllegalLifecycleState;
} else if (cause instanceof InterruptedException) {
return OperationStatus.IllegalLifecycleState;
} else {
return OperationStatus.ServerError;
}
} else if (t instanceof InterruptedException) {
return OperationStatus.IllegalLifecycleState;
} else if (t instanceof PrivilegedActionException) {
return errorStatus(t.getCause());
} else if (t instanceof SuspectedException) {
return OperationStatus.NodeSuspected;
} else {
return OperationStatus.ServerError;
}
}
protected ByteBuf writeHeader(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status) {
return writeHeader(header, server, channel, status, false);
}
private ByteBuf writeHeader(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status, boolean sendMediaType) {
ByteBuf buf = channel.alloc().ioBuffer();
Cache<Address, ServerAddress> addressCache = HotRodVersion.forVersion(header.version) != HotRodVersion.UNKNOWN ?
server.getAddressCache() : null;
Optional<AbstractTopologyResponse> newTopology;
MediaType keyMediaType = null;
MediaType valueMediaType = null;
boolean objectStorage = false;
CacheTopology cacheTopology;
if (header.op != HotRodOperation.ERROR) {
if (CounterModuleLifecycle.COUNTER_CACHE_NAME.equals(header.cacheName)) {
cacheTopology = getCounterCacheTopology(server.getCacheManager());
newTopology = getTopologyResponse(header.clientIntel, header.topologyId, addressCache, channel,
server.getTimeService(), CacheMode.DIST_SYNC, cacheTopology);
} else if (header.cacheName.isEmpty() && !server.hasDefaultCache()) {
cacheTopology = null;
newTopology = Optional.empty();
} else {
HotRodServer.ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
Configuration configuration = cacheInfo.configuration;
CacheMode cacheMode = configuration.clustering().cacheMode();
cacheTopology =
cacheMode.isClustered() ? cacheInfo.distributionManager.getCacheTopology() : null;
newTopology = getTopologyResponse(header.clientIntel, header.topologyId, addressCache, channel,
server.getTimeService(), cacheMode, cacheTopology);
keyMediaType = configuration.encoding().keyDataType().mediaType();
valueMediaType = configuration.encoding().valueDataType().mediaType();
objectStorage = APPLICATION_OBJECT.match(keyMediaType);
}
} else {
cacheTopology = null;
newTopology = Optional.empty();
}
buf.writeByte(Constants.MAGIC_RES);
writeUnsignedLong(header.messageId, buf);
buf.writeByte(header.op.getResponseOpCode());
writeStatus(header, buf, server, objectStorage, status);
if (newTopology.isPresent()) {
AbstractTopologyResponse topology = newTopology.get();
if (topology instanceof TopologyAwareResponse) {
writeTopologyUpdate((TopologyAwareResponse) topology, buf, ((InetSocketAddress) channel.localAddress()).getAddress());
if (header.clientIntel == Constants.INTELLIGENCE_HASH_DISTRIBUTION_AWARE)
writeEmptyHashInfo(topology, buf);
} else if (topology instanceof HashDistAware20Response) {
writeHashTopologyUpdate((HashDistAware20Response) topology, cacheTopology, buf, ((InetSocketAddress) channel.localAddress()).getAddress());
} else {
throw new IllegalArgumentException("Unsupported response: " + topology);
}
} else {
if (log.isTraceEnabled()) log.trace("Write topology response header with no change");
buf.writeByte(0);
}
if (sendMediaType && HotRodVersion.HOTROD_29.isAtLeast(header.version)) {
writeMediaType(buf, keyMediaType);
writeMediaType(buf, valueMediaType);
}
return buf;
}
@Override
public void writeCounterEvent(ClientCounterEvent event, ByteBuf buffer) {
writeHeaderNoTopology(buffer, 0, HotRodOperation.COUNTER_EVENT);
event.writeTo(buffer);
}
private CacheTopology getCounterCacheTopology(EmbeddedCacheManager cacheManager) {
AdvancedCache<?, ?> cache = cacheManager.getCache(CounterModuleLifecycle.COUNTER_CACHE_NAME).getAdvancedCache();
return cache.getCacheConfiguration().clustering().cacheMode().isClustered() ?
cache.getComponentRegistry().getDistributionManager().getCacheTopology() :
null; //local cache
}
private void writeHeaderNoTopology(ByteBuf buffer, long messageId, HotRodOperation operation) {
buffer.writeByte(Constants.MAGIC_RES);
writeUnsignedLong(messageId, buffer);
buffer.writeByte(operation.getResponseOpCode());
buffer.writeByte(OperationStatus.Success.getCode());
buffer.writeByte(0); // no topology change
}
private void writeStatus(HotRodHeader header, ByteBuf buf, HotRodServer server, boolean objStorage, OperationStatus status) {
if (server == null || HotRodVersion.HOTROD_24.isOlder(header.version) || HotRodVersion.HOTROD_29.isAtLeast(header.version))
buf.writeByte(status.getCode());
else {
OperationStatus st = OperationStatus.withLegacyStorageHint(status, objStorage);
buf.writeByte(st.getCode());
}
}
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);
VInt.write(buf, id);
} else {
buf.writeByte(2);
ExtendedByteBuf.writeString(mediaType.toString(), buf);
}
Map<String, String> parameters = mediaType.getParameters();
VInt.write(buf, parameters.size());
parameters.forEach((key, value) -> {
ExtendedByteBuf.writeString(key, buf);
ExtendedByteBuf.writeString(value, buf);
});
}
}
private void writeTopologyUpdate(TopologyAwareResponse t, ByteBuf buffer, InetAddress localAddress) {
Map<Address, ServerAddress> topologyMap = t.serverEndpointsMap;
if (topologyMap.isEmpty()) {
log.noMembersInTopology();
buffer.writeByte(0); // Topology not changed
} else {
if (log.isTraceEnabled()) log.tracef("Write topology change response header %s", t);
buffer.writeByte(1); // Topology changed
ExtendedByteBuf.writeUnsignedInt(t.topologyId, buffer);
ExtendedByteBuf.writeUnsignedInt(topologyMap.size(), buffer);
for (ServerAddress address : topologyMap.values()) {
ExtendedByteBuf.writeString(address.getHost(localAddress), buffer);
ExtendedByteBuf.writeUnsignedShort(address.getPort(), buffer);
}
}
}
private void writeEmptyHashInfo(AbstractTopologyResponse t, ByteBuf buffer) {
if (log.isTraceEnabled())
log.tracef("Return limited hash distribution aware header because the client %s doesn't ", t);
buffer.writeByte(0); // Hash Function Version
ExtendedByteBuf.writeUnsignedInt(t.numSegments, buffer);
}
private void writeHashTopologyUpdate(HashDistAware20Response h, CacheTopology cacheTopology, ByteBuf buf, InetAddress localAddress) {
// Calculate members first, in case there are no members
ConsistentHash ch = cacheTopology.getReadConsistentHash();
Map<Address, ServerAddress> members = h.serverEndpointsMap.entrySet().stream().filter(e ->
ch.getMembers().contains(e.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
if (log.isTraceEnabled()) {
log.trace("Topology cache contains: " + h.serverEndpointsMap);
log.trace("After read consistent hash filter, members are: " + members);
}
if (members.isEmpty()) {
log.noMembersInHashTopology(ch, h.serverEndpointsMap.toString());
buf.writeByte(0); // Topology not changed
} else {
if (log.isTraceEnabled()) log.tracef("Write hash distribution change response header %s", h);
buf.writeByte(1); // Topology changed
ExtendedByteBuf.writeUnsignedInt(h.topologyId, buf); // Topology ID
// Write members
AtomicInteger indexCount = new AtomicInteger(-1);
ExtendedByteBuf.writeUnsignedInt(members.size(), buf);
Map<Address, Integer> indexedMembers = new HashMap<>();
members.forEach((addr, serverAddr) -> {
ExtendedByteBuf.writeString(serverAddr.getHost(localAddress), buf);
ExtendedByteBuf.writeUnsignedShort(serverAddr.getPort(), buf);
indexCount.incrementAndGet();
indexedMembers.put(addr, indexCount.get()); // easier indexing
});
// Write segment information
int numSegments = ch.getNumSegments();
buf.writeByte(h.hashFunction); // Hash function
ExtendedByteBuf.writeUnsignedInt(numSegments, buf);
for (int segmentId = 0; segmentId < numSegments; ++segmentId) {
List<Address> owners = ch.locateOwnersForSegment(segmentId).stream().filter(members::containsKey).collect(Collectors.toList());
int ownersSize = owners.size();
if (ownersSize == 0) {
// When sending partial updates, number of owners could be 0,
// in which case just take the first member in the list.
buf.writeByte(1);
ExtendedByteBuf.writeUnsignedInt(0, buf);
} else {
buf.writeByte(ownersSize);
owners.forEach(ownerAddr -> {
Integer index = indexedMembers.get(ownerAddr);
if (index != null) {
ExtendedByteBuf.writeUnsignedInt(index, buf);
}
});
}
}
}
}
private Optional<AbstractTopologyResponse> getTopologyResponse(short clientIntel, int topologyId, Cache<Address, ServerAddress> addressCache,
Channel channel, TimeService timeService, CacheMode cacheMode, CacheTopology cacheTopology) {
// If clustered, set up a cache for topology information
if (addressCache != null) {
switch (clientIntel) {
case Constants.INTELLIGENCE_TOPOLOGY_AWARE:
case Constants.INTELLIGENCE_HASH_DISTRIBUTION_AWARE: {
// Only send a topology update if the cache is clustered
if (cacheMode.isClustered()) {
// Use the request cache's topology id as the HotRod topologyId.
int currentTopologyId = cacheTopology.getReadConsistentHash().hashCode();
// AND if the client's topology id is different from the server's topology id
if (topologyId != currentTopologyId) {
Optional<AbstractTopologyResponse> respOptional =
generateTopologyResponse(clientIntel, topologyId, addressCache, cacheMode, cacheTopology);
if (lastKnownTopologyIds != null && respOptional.isPresent()) {
ChannelId id = channel.id();
LastKnownClientTopologyId lastKnown = lastKnownTopologyIds.get(id);
if (lastKnown != null && lastKnown.topologyId == topologyId && lastKnown.timeCaptured != -1) {
if (timeService.timeDuration(lastKnown.timeCaptured, TimeUnit.MILLISECONDS) > topologyCheckInterval) {
log.clientNotUpdatingTopology(channel.localAddress(), topologyId);
// Update last known topology to the current one to avoid logging a message over and over
lastKnownTopologyIds.replace(id, new LastKnownClientTopologyId(currentTopologyId, -1));
}
} else if (lastKnownTopologyIds.put(id, new LastKnownClientTopologyId(topologyId, timeService.time())) == null) {
channel.closeFuture().addListener(___ -> lastKnownTopologyIds.remove(id));
}
}
return respOptional;
}
}
}
}
}
return Optional.empty();
}
private Optional<AbstractTopologyResponse> generateTopologyResponse(short clientIntel, int responseTopologyId, Cache<Address, ServerAddress> addressCache, CacheMode cacheMode, CacheTopology cacheTopology) {
// If the topology cache is incomplete, we assume that a node has joined but hasn't added his HotRod
// endpoint address to the topology cache yet. We delay the topology update until the next client
// request by returning null here (so the client topology id stays the same).
// If a new client connects while the join is in progress, though, we still have to generate a topology
// response. Same if we have cache manager that is a member of the cluster but doesn't have a HotRod
// endpoint (aka a storage-only node), and a HotRod server shuts down.
// Our workaround is to send a "partial" topology update when the topology cache is incomplete, but the
// difference between the client topology id and the server topology id is 2 or more. The partial update
// will have the topology id of the server - 1, so it won't prevent a regular topology update if/when
// the topology cache is updated.
List<Address> cacheMembers = cacheTopology.getActualMembers();
Map<Address, ServerAddress> serverEndpoints = new HashMap<>();
try {
serverEndpoints.putAll(addressCache);
} catch (IllegalLifecycleStateException e) {
// Address cache has been shut down, ignore the exception and don't send a topology update
return Optional.empty();
}
int clientTopologyId = cacheTopology.getReadConsistentHash().hashCode();
if (log.isTraceEnabled()) {
log.tracef("Check for partial topologies: endpoints=%s, client-topology=%s, server-topology=%s, server-client-topology=%s",
serverEndpoints, responseTopologyId, cacheTopology.getTopologyId(), clientTopologyId);
}
if (!serverEndpoints.keySet().containsAll(cacheMembers)) {
if (log.isTraceEnabled()) log.trace("Postpone topology update");
return Optional.empty(); // Postpone topology update
}
if (log.isTraceEnabled()) log.tracef("Send client topology update with topology id %s", clientTopologyId);
if (clientIntel == Constants.INTELLIGENCE_HASH_DISTRIBUTION_AWARE && !cacheMode.isInvalidation()) {
int numSegments = cacheTopology.getReadConsistentHash().getNumSegments();
return Optional.of(new HashDistAware20Response(clientTopologyId, serverEndpoints, numSegments,
Constants.DEFAULT_CONSISTENT_HASH_VERSION));
} else {
return Optional.of(new TopologyAwareResponse(clientTopologyId, serverEndpoints, 0));
}
}
private static Optional<Integer> projectionInfo(List<CacheEntry> entries, byte version) {
if (!entries.isEmpty()) {
CacheEntry entry = entries.get(0);
if (entry.getValue() instanceof Object[]) {
return Optional.of(((Object[]) entry.getValue()).length);
} else if (HotRodVersion.HOTROD_24.isAtLeast(version)) {
return Optional.of(1);
}
}
return Optional.empty();
}
}
| 36,565
| 46.30401
| 209
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodHeader.java
|
package org.infinispan.server.hotrod;
import java.util.EnumSet;
import java.util.Map;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.context.Flag;
import org.infinispan.server.hotrod.logging.Log;
/**
* @author wburns
* @since 9.0
*/
public class HotRodHeader {
private static final Log log = LogFactory.getLog(HotRodHeader.class, Log.class);
HotRodOperation op;
byte version;
long messageId;
String cacheName;
int flag;
short clientIntel;
int topologyId;
MediaType keyType;
MediaType valueType;
Map<String, byte[]> otherParams;
public HotRodHeader(HotRodHeader header) {
this(header.op, header.version, header.messageId, header.cacheName, header.flag, header.clientIntel, header.topologyId, header.keyType, header.valueType, header.otherParams);
}
public HotRodHeader(HotRodOperation op, byte version, long messageId, String cacheName, int flag, short clientIntel, int topologyId, MediaType keyType, MediaType valueType, Map<String, byte[]> otherParams) {
this.op = op;
this.version = version;
this.messageId = messageId;
this.cacheName = cacheName;
this.flag = flag;
this.clientIntel = clientIntel;
this.topologyId = topologyId;
this.keyType = keyType;
this.valueType = valueType;
this.otherParams = otherParams;
}
public boolean hasFlag(ProtocolFlag f) {
return (flag & f.getValue()) == f.getValue();
}
public HotRodOperation getOp() {
return op;
}
public MediaType getKeyMediaType() {
return keyType == null ? MediaType.APPLICATION_UNKNOWN : keyType;
}
public MediaType getValueMediaType() {
return valueType == null ? MediaType.APPLICATION_UNKNOWN : valueType;
}
public byte getVersion() {
return version;
}
public long getMessageId() {
return messageId;
}
public String getCacheName() {
return cacheName;
}
public int getFlag() {
return flag;
}
public short getClientIntel() {
return clientIntel;
}
public int getTopologyId() {
return topologyId;
}
public VersionedEncoder encoder() {
return HotRodVersion.getEncoder(version);
}
boolean isSkipCacheLoad() {
if (version < 20) {
return false;
} else {
return op.canSkipCacheLoading() && hasFlag(ProtocolFlag.SkipCacheLoader);
}
}
boolean isSkipIndexing() {
if (version < 20) {
return false;
} else {
return op.canSkipIndexing() && hasFlag(ProtocolFlag.SkipIndexing);
}
}
AdvancedCache<byte[], byte[]> getOptimizedCache(AdvancedCache<byte[], byte[]> c,
boolean transactional, boolean clustered) {
EnumSet<Flag> flags = EnumSet.noneOf(Flag.class);
if (hasFlag(ProtocolFlag.SkipListenerNotification)) {
flags.add(Flag.SKIP_LISTENER_NOTIFICATION);
}
if (version < 20) {
if (!hasFlag(ProtocolFlag.ForceReturnPreviousValue)) {
switch (op) {
case PUT:
case PUT_IF_ABSENT:
flags.add(Flag.IGNORE_RETURN_VALUES);
}
}
return c.withFlags(flags);
}
if (clustered && !transactional && op.isConditional()) {
log.warnConditionalOperationNonTransactional(op.toString());
}
if (op.canSkipCacheLoading() && hasFlag(ProtocolFlag.SkipCacheLoader)) {
flags.add(Flag.SKIP_CACHE_LOAD);
}
if (op.canSkipIndexing() && hasFlag(ProtocolFlag.SkipIndexing)) {
flags.add(Flag.SKIP_INDEXING);
}
if (!hasFlag(ProtocolFlag.ForceReturnPreviousValue)) {
if (op.isNotConditionalAndCanReturnPrevious()) {
flags.add(Flag.IGNORE_RETURN_VALUES);
}
} else if (!transactional && op.canReturnPreviousValue()) {
log.warnForceReturnPreviousNonTransactional(op.toString());
}
return c.withFlags(flags);
}
@Override
public String toString() {
return "HotRodHeader{" +
"op=" + op +
", version=" + version +
", messageId=" + messageId +
", cacheName='" + cacheName + '\'' +
", flag=" + flag +
", clientIntel=" + clientIntel +
", topologyId=" + topologyId +
", keyType=" + keyType +
", valueType=" + valueType +
", otherParams=" + otherParams +
'}';
}
}
| 4,597
| 27.382716
| 210
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/Response.java
|
package org.infinispan.server.hotrod;
import java.util.Map;
import org.infinispan.remoting.transport.Address;
abstract class AbstractTopologyResponse {
final int topologyId;
final Map<Address, ServerAddress> serverEndpointsMap;
final int numSegments;
protected AbstractTopologyResponse(int topologyId, Map<Address, ServerAddress> serverEndpointsMap, int numSegments) {
this.topologyId = topologyId;
this.serverEndpointsMap = serverEndpointsMap;
this.numSegments = numSegments;
}
}
abstract class AbstractHashDistAwareResponse extends AbstractTopologyResponse {
final int numOwners;
final byte hashFunction;
final int hashSpace;
protected AbstractHashDistAwareResponse(int topologyId, Map<Address, ServerAddress> serverEndpointsMap,
int numSegments, int numOwners, byte hashFunction, int hashSpace) {
super(topologyId, serverEndpointsMap, numSegments);
this.numOwners = numOwners;
this.hashFunction = hashFunction;
this.hashSpace = hashSpace;
}
}
class TopologyAwareResponse extends AbstractTopologyResponse {
protected TopologyAwareResponse(int topologyId, Map<Address, ServerAddress> serverEndpointsMap, int numSegments) {
super(topologyId, serverEndpointsMap, numSegments);
}
@Override
public String toString() {
return "TopologyAwareResponse{" +
"topologyId=" + topologyId +
", numSegments=" + numSegments +
'}';
}
}
class HashDistAware20Response extends AbstractTopologyResponse {
final byte hashFunction;
protected HashDistAware20Response(int topologyId, Map<Address, ServerAddress> serverEndpointsMap, int numSegments,
byte hashFunction) {
super(topologyId, serverEndpointsMap, numSegments);
this.hashFunction = hashFunction;
}
@Override
public String toString() {
return "HashDistAware20Response{" +
"topologyId=" + topologyId +
", numSegments=" + numSegments +
", hashFunction=" + hashFunction +
'}';
}
}
| 2,132
| 30.835821
| 120
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/ServerAddress.java
|
package org.infinispan.server.hotrod;
import java.net.InetAddress;
/**
* A Hot Rod server address
*
* @author Galder Zamarreño
* @since 5.1
*/
public interface ServerAddress {
/**
* Returns the mapping for the
* @param localAddress
* @return
*/
String getHost(InetAddress localAddress);
int getPort();
static ServerAddress forAddress(String host, int port, boolean networkPrefixOverride) {
if ("0.0.0.0".equals(host) || "0:0:0:0:0:0:0:0".equals(host)) {
return new MultiHomedServerAddress(port, networkPrefixOverride);
} else {
return new SingleHomedServerAddress(host, port);
}
}
}
| 661
| 20.354839
| 90
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/BitShift.java
|
package org.infinispan.server.hotrod;
public class BitShift {
public static byte mask(byte value, int mask) {
return (byte) (value & mask);
}
public static byte right(byte value, int num) {
return (byte) ((0xFF & value) >> num);
}
}
| 258
| 22.545455
| 50
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/ServerHotRodBlockHoundIntegration.java
|
package org.infinispan.server.hotrod;
import org.infinispan.commons.util.SaslUtils;
import org.infinispan.server.hotrod.tx.table.GlobalTxTable;
import org.kohsuke.MetaInfServices;
import reactor.blockhound.BlockHound;
import reactor.blockhound.integration.BlockHoundIntegration;
@MetaInfServices
public class ServerHotRodBlockHoundIntegration implements BlockHoundIntegration {
@Override
public void applyTo(BlockHound.Builder builder) {
// Invokes stream method on a cache that is REPL or LOCAL without persistence (won't block)
builder.allowBlockingCallsInside(GlobalTxTable.class.getName(), "getPreparedTransactions");
questionableBlockingMethod(builder);
}
private static void questionableBlockingMethod(BlockHound.Builder builder) {
builder.allowBlockingCallsInside(HotRodServer.class.getName(), "obtainAnonymizedCache");
builder.allowBlockingCallsInside(Encoder2x.class.getName(), "getCounterCacheTopology");
// Stream method is blocking
builder.allowBlockingCallsInside(Encoder2x.class.getName(), "generateTopologyResponse");
// Wildfly open ssl reads a properties file
builder.allowBlockingCallsInside("org.wildfly.openssl.OpenSSLEngine", "unwrap");
builder.allowBlockingCallsInside(SaslUtils.class.getName(), "getFactories");
// Blocks on non blocking method - should return CompletionStage
builder.allowBlockingCallsInside(GlobalTxTable.class.getName(), "update");
// Uses blocking call inside publisher - can be non blocking instead
builder.allowBlockingCallsInside(GlobalTxTable.class.getName(), "forgetTransaction");
builder.allowBlockingCallsInside(CounterRequestProcessor.class.getName(), "counterRemoveInternal");
// Counter creation is blocking - needs to be fixed
builder.allowBlockingCallsInside(CounterRequestProcessor.class.getName(), "applyCounter");
}
}
| 1,904
| 44.357143
| 105
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodVersion.java
|
package org.infinispan.server.hotrod;
import java.util.Arrays;
/**
* The various Hot Rod versions
*
* @author Tristan Tarrant
* @since 9.2
*/
public enum HotRodVersion {
UNKNOWN(0, 0),
HOTROD_20(2, 0), // since 7.0
HOTROD_21(2, 1), // since 7.1
HOTROD_22(2, 2), // since 8.0
HOTROD_23(2, 3), // since 8.0
HOTROD_24(2, 4), // since 8.1
HOTROD_25(2, 5), // since 8.2
HOTROD_26(2, 6), // since 9.0
HOTROD_27(2, 7), // since 9.2
HOTROD_28(2, 8), // since 9.3
HOTROD_29(2, 9), // since 9.4
HOTROD_30(3, 0), // since 10.0
HOTROD_31(3, 1), // since 12.0
HOTROD_40(4, 0), // since 14.0
;
private final int major;
private final int minor;
private final byte version;
private final String text;
HotRodVersion(int major, int minor) {
this.major = major;
this.minor = minor;
this.version = (byte) (major * 10 + minor);
this.text = version > 0 ? String.format("HOTROD/%d.%d", major, minor) : "UNKNOWN";
}
public byte getVersion() {
return version;
}
/**
* Checks whether the supplied version is older than the version represented by this object
* @param version a Hot Rod version in its wire representation
* @return true if version is older than this
*/
public boolean isOlder(byte version) {
return this.version > version;
}
/**
* Checks whether the supplied version is equal or greater than the version represented by this object
* @param version a Hot Rod version in its wire representation
* @return true if version is equal or greater than this
*/
public boolean isAtLeast(byte version) {
return this.version <= version;
}
public String toString() {
return text;
}
public static final HotRodVersion LATEST;
private static final HotRodVersion[] VERSIONS = new HotRodVersion[256];
static {
LATEST = values()[values().length - 1];
Arrays.fill(VERSIONS, UNKNOWN);
for(HotRodVersion version : values()) {
VERSIONS[version.version] = version;
}
}
public static HotRodVersion forVersion(byte version) {
return VERSIONS[version];
}
public static VersionedEncoder getEncoder(byte version) {
if (HotRodVersion.HOTROD_40.isAtLeast(version)) {
return Encoder4x.instance();
}
return Encoder2x.instance();
}
}
| 2,370
| 25.640449
| 105
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/MultiHomedServerAddress.java
|
package org.infinispan.server.hotrod;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.marshall.AbstractExternalizer;
/**
* A Hot Rod server address which encapsulates a multi-homed server. This class enumerates all available addresses on
* all the local interfaces.
*
* @author Tristan Tarrant
* @author Galder Zamarreño
* @since 10.1
*/
public class MultiHomedServerAddress implements ServerAddress {
private final int port;
private final List<InetAddressWithNetMask> addresses;
/**
* @param port
*/
public MultiHomedServerAddress(int port, boolean networkPrefixOverride) {
this.port = port;
addresses = new ArrayList<>();
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (InterfaceAddress address : intf.getInterfaceAddresses()) {
addresses.add(new InetAddressWithNetMask(address.getAddress(), address.getNetworkPrefixLength(), networkPrefixOverride));
}
}
} catch (IOException e) {
throw new CacheConfigurationException(e);
}
}
private MultiHomedServerAddress(List<InetAddressWithNetMask> addresses, int port) {
this.addresses = addresses;
this.port = port;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MultiHomedServerAddress that = (MultiHomedServerAddress) o;
if (port != that.port) return false;
return addresses.equals(that.addresses);
}
@Override
public int hashCode() {
int result = addresses.hashCode();
result = 31 * result + port;
return result;
}
@Override
public String toString() {
return "MultiHomedServerAddress{" +
"port=" + port +
", addresses=" + addresses +
'}';
}
public int getPort() {
return port;
}
/**
* Return the interface address which matches the incoming address
*
* @param localAddress
* @return
*/
@Override
public String getHost(InetAddress localAddress) {
for (InetAddressWithNetMask address : addresses) {
if (inetAddressMatchesInterfaceAddress(localAddress.getAddress(), address.address.getAddress(), address.prefixLength)) {
if (HotRodServer.log.isDebugEnabled()) {
HotRodServer.log.debugf("Matched incoming address '%s' with '%s'", localAddress, address);
}
return address.address.getHostAddress();
}
}
throw new IllegalArgumentException("No interface address matching '" + localAddress + "' in " + this);
}
static byte[] netMaskByPrefix = {(byte) 128, (byte) 192, (byte) 224, (byte) 240, (byte) 248, (byte) 252, (byte) 254};
/**
* Checks whether the supplied network address matches the interfaceAddress. It does this by using the interface's
* prefixLength and comparing the bits in the prefix.
*
* @param inetAddress
* @param interfaceAddress
* @return
*/
public static boolean inetAddressMatchesInterfaceAddress(byte[] inetAddress, byte[] interfaceAddress, int prefixLength) {
if (HotRodServer.log.isDebugEnabled()) {
HotRodServer.log.debugf("Matching incoming address '%s' with '%s'/%d", inetAddress, interfaceAddress, prefixLength);
}
if (inetAddress.length != interfaceAddress.length) {
return false;
}
for (int i = 0; i < inetAddress.length; i++) {
byte a = inetAddress[i];
byte b = interfaceAddress[i];
if (prefixLength >= 8) {
if (a != b) {
return false;
} else {
prefixLength -= 8;
}
} else if (prefixLength > 0) {
byte mask = MultiHomedServerAddress.netMaskByPrefix[prefixLength - 1];
if ((a & mask) != (b & mask)) {
return false;
} else {
prefixLength = 0;
}
}
}
return true;
}
public static class InetAddressWithNetMask {
// RFC 1918 10.0.0.0/8
public static final InetAddressWithNetMask RFC1918_CIDR_10 = new InetAddressWithNetMask(new byte[]{10, 0, 0, 0}, (short) 8);
// RFC 1918 172.16.0.0/12
public static final InetAddressWithNetMask RFC1918_CIDR_172 = new InetAddressWithNetMask(new byte[]{(byte) 172, (byte) 16, 0, 0}, (short) 12);
// RFC 1918 192.168.0.0/16
public static final InetAddressWithNetMask RFC1918_CIDR_192 = new InetAddressWithNetMask(new byte[]{(byte) 192, (byte) 168, 0, 0}, (short) 16);
// RFC 3927 169.254.0.0/16
public static final InetAddressWithNetMask RFC3927_LINK_LOCAL = new InetAddressWithNetMask(new byte[]{(byte) 169, (byte) 254, 0, 0}, (short) 16);
// RFC 1112 240.0.0.0/4
public static final InetAddressWithNetMask RFC1112_RESERVED = new InetAddressWithNetMask(new byte[]{(byte) 240, 0, 0, 0}, (short) 4);
// RFC 6598 100.64.0.0/10
public static final InetAddressWithNetMask RFC6598_SHARED_SPACE = new InetAddressWithNetMask(new byte[]{(byte) 100, (byte) 64, 0, 0}, (short) 10);
// RFC 4193 fc00::/7
public static final InetAddressWithNetMask RFC4193_ULA = new InetAddressWithNetMask(new byte[]{(byte) 0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, (short) 7);
// RFC 4193 fe80::/10
public static final InetAddressWithNetMask RFC4193_LINK_LOCAL = new InetAddressWithNetMask(new byte[]{(byte) 0xfe, (byte) 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, (short) 10);
public static final List<InetAddressWithNetMask> PRIVATE_NETWORKS = Arrays.asList(
RFC1918_CIDR_10,
RFC1918_CIDR_172,
RFC1918_CIDR_192,
RFC3927_LINK_LOCAL,
RFC1112_RESERVED,
RFC6598_SHARED_SPACE,
RFC4193_ULA,
RFC4193_LINK_LOCAL
);
final InetAddress address;
final short prefixLength;
public InetAddressWithNetMask(InetAddress address, short prefixLength, boolean networkPrefixOverride) {
this.address = address;
short prefix = prefixLength;
if (networkPrefixOverride) {
byte[] a = address.getAddress();
for (InetAddressWithNetMask net : PRIVATE_NETWORKS) {
if (inetAddressMatchesInterfaceAddress(a, net.address.getAddress(), net.prefixLength)) {
prefix = net.prefixLength;
break;
}
}
}
this.prefixLength = prefix;
}
private InetAddressWithNetMask(byte[] address, short prefixLength) {
try {
this.address = InetAddress.getByAddress(address);
} catch (UnknownHostException e) {
throw new IllegalArgumentException(e);
}
this.prefixLength = prefixLength;
}
public InetAddressWithNetMask(InetAddress address, short prefixLength) {
this.address = address;
this.prefixLength = prefixLength;
}
@Override
public String toString() {
return address + "/" + prefixLength;
}
}
static class Externalizer extends AbstractExternalizer<MultiHomedServerAddress> {
@Override
public Set<Class<? extends MultiHomedServerAddress>> getTypeClasses() {
return Collections.singleton(MultiHomedServerAddress.class);
}
@Override
public void writeObject(ObjectOutput output, MultiHomedServerAddress object) throws IOException {
output.writeInt(object.addresses.size());
for (InetAddressWithNetMask address : object.addresses) {
output.writeObject(address.address.getHostAddress());
output.writeShort(address.prefixLength);
}
output.writeShort(object.port);
}
@Override
public MultiHomedServerAddress readObject(ObjectInput input) throws IOException, ClassNotFoundException {
int size = input.readInt();
List<InetAddressWithNetMask> addresses = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
String address = (String) input.readObject();
short prefixLength = input.readShort();
addresses.add(new InetAddressWithNetMask(InetAddress.getByName(address), prefixLength));
}
int port = input.readUnsignedShort();
return new MultiHomedServerAddress(addresses, port);
}
}
}
| 8,968
| 36.684874
| 189
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodConstants.java
|
package org.infinispan.server.hotrod;
/**
* Defines constants defined by Hot Rod specifications.
*
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
public interface HotRodConstants {
byte VERSION_20 = HotRodVersion.HOTROD_20.getVersion();
byte VERSION_21 = HotRodVersion.HOTROD_21.getVersion();
byte VERSION_22 = HotRodVersion.HOTROD_22.getVersion();
byte VERSION_24 = HotRodVersion.HOTROD_24.getVersion();
byte VERSION_26 = HotRodVersion.HOTROD_26.getVersion();
byte VERSION_28 = HotRodVersion.HOTROD_28.getVersion();
byte VERSION_30 = HotRodVersion.HOTROD_30.getVersion();
byte VERSION_31 = HotRodVersion.HOTROD_31.getVersion();
byte VERSION_40 = HotRodVersion.HOTROD_40.getVersion();
//requests
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_TX = 0x3B;
byte COMMIT_TX = 0x3D;
byte ROLLBACK_TX = 0x3F;
byte ADD_BLOOM_FILTER_NEAR_CACHE_LISTENER_REQUEST = 0x41;
byte UPDATE_BLOOM_FILTER_REQUEST = 0x43;
byte FORGET_TX = 0x79;
byte FETCH_TX_RECOVERY = 0x7B;
byte PREPARE_TX_2 = 0x7D;
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 GET_MULTIMAP_REQUEST = 0x67;
byte GET_MULTIMAP_WITH_METADATA_REQUEST = 0x69;
byte PUT_MULTIMAP_REQUEST = 0x6B;
byte REMOVE_KEY_MULTIMAP_REQUEST = 0x6D;
byte REMOVE_ENTRY_MULTIMAP_REQUEST = 0x6F;
byte SIZE_MULTIMAP_REQUEST = 0x71;
byte CONTAINS_ENTRY_REQUEST = 0x73;
byte CONTAINS_KEY_MULTIMAP_REQUEST = 0x75;
byte CONTAINS_VALUE_MULTIMAP_REQUEST = 0x77;
byte COUNTER_GET_AND_SET_REQUEST = 0x7F;
//0x79 FORGET_TX
//0x7B FETCH_TX_RECOVERY
//0x7D PREPARE_TX_2
}
| 2,988
| 33.356322
| 60
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/CacheRequestProcessor.java
|
package org.infinispan.server.hotrod;
import java.util.BitSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import javax.security.auth.Subject;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.util.BloomFilter;
import org.infinispan.commons.util.IntSets;
import org.infinispan.commons.util.MurmurHash3BloomFilter;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.container.versioning.NumericVersion;
import org.infinispan.context.Flag;
import org.infinispan.metadata.Metadata;
import org.infinispan.reactive.publisher.impl.DeliveryGuarantee;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.core.transport.ConnectionMetadata;
import org.infinispan.server.hotrod.HotRodServer.ExtendedCacheInfo;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.server.hotrod.tracing.HotRodTelemetryService;
import org.infinispan.server.iteration.IterableIterationResult;
import org.infinispan.server.iteration.IterationState;
import org.infinispan.stats.ClusterCacheStats;
import org.infinispan.stats.Stats;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
class CacheRequestProcessor extends BaseRequestProcessor {
private static final Log log = LogFactory.getLog(CacheRequestProcessor.class, Log.class);
private final ClientListenerRegistry listenerRegistry;
private final HotRodTelemetryService telemetryService;
private final ConcurrentMap<String, BloomFilter<byte[]>> bloomFilters = new ConcurrentHashMap<>();
CacheRequestProcessor(Channel channel, Executor executor, HotRodServer server, HotRodTelemetryService telemetryService) {
super(channel, executor, server);
this.listenerRegistry = server.getClientListenerRegistry();
this.telemetryService = telemetryService;
}
void ping(HotRodHeader header, Subject subject) {
// we need to throw an exception when the cache is inaccessible
// but ignore the default cache, because the client always pings the default cache first
if (!header.cacheName.isEmpty()) {
server.cache(server.getCacheInfo(header), header, subject);
}
ConnectionMetadata metadata = ConnectionMetadata.getInstance(channel);
metadata.protocolVersion(HotRodVersion.forVersion(header.version).toString());
writeResponse(header, header.encoder().pingResponse(header, server, channel, OperationStatus.Success));
}
void stats(HotRodHeader header, Subject subject) {
AdvancedCache<byte[], byte[]> cache = server.cache(server.getCacheInfo(header), header, subject);
executor.execute(() -> blockingStats(header, cache));
}
private void blockingStats(HotRodHeader header, AdvancedCache<byte[], byte[]> cache) {
try {
Stats stats = cache.getStats();
ClusterCacheStats clusterCacheStats =
SecurityActions.getCacheComponentRegistry(cache).getComponent(ClusterCacheStats.class);
ByteBuf buf = header.encoder().statsResponse(header, server, channel, stats, server.getTransport(),
clusterCacheStats);
writeResponse(header, buf);
} catch (Throwable t) {
writeException(header, t);
}
}
void get(HotRodHeader header, Subject subject, byte[] key) {
ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
getInternal(header, cache, key);
}
void updateBloomFilter(HotRodHeader header, Subject subject, byte[] bloomArray) {
try {
BloomFilter<byte[]> filter = bloomFilters.get(header.cacheName);
if (filter != null) {
if (log.isTraceEnabled()) {
log.tracef("Updating bloom filter %s found for cache %s", filter, header.cacheName);
}
filter.setBits(IntSets.from(bloomArray));
if (log.isTraceEnabled()) {
log.tracef("Updated bloom filter %s for cache %s", filter, header.cacheName);
}
writeSuccess(header);
} else {
if (log.isTraceEnabled()) {
log.tracef("There was no bloom filter for cache %s from client", header.cacheName);
}
writeNotExecuted(header);
}
} catch (Throwable t) {
writeException(header, t);
}
}
private void getInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, byte[] key) {
CompletableFuture<CacheEntry<byte[], byte[]>> get = cache.getCacheEntryAsync(key);
if (get.isDone() && !get.isCompletedExceptionally()) {
handleGet(header, get.join(), null);
} else {
get.whenComplete((result, throwable) -> handleGet(header, result, throwable));
}
}
void addToFilter(String cacheName, byte[] key) {
BloomFilter<byte[]> bloomFilter = bloomFilters.get(cacheName);
// TODO: Need to think harder about this because we could have a concurrent write as we are doing our get
// and we could have just have had an invalidation come through that didn't pass the bloom filter
// I believe this has to go at the beginning of the get command before we get a value or exception
// We can fix this by adding a temporary check that if a get is being performed and the listener checks the
// bloom filter for the key to return a bit saying to not cache the returned value
if (bloomFilter != null) {
bloomFilter.addToFilter(key);
}
}
private void handleGet(HotRodHeader header, CacheEntry<byte[], byte[]> result, Throwable throwable) {
if (throwable != null) {
writeException(header, throwable);
} else {
if (result == null) {
writeNotExist(header);
} else {
try {
switch (header.op) {
case GET:
writeResponse(header, header.encoder().valueResponse(header, server, channel, OperationStatus.Success, result.getValue()));
break;
case GET_WITH_VERSION:
NumericVersion numericVersion = (NumericVersion) result.getMetadata().version();
long version;
if (numericVersion != null) {
version = numericVersion.getVersion();
} else {
version = 0;
}
writeResponse(header, header.encoder().valueWithVersionResponse(header, server, channel, result.getValue(), version));
break;
default:
throw new IllegalStateException();
}
} catch (Throwable t2) {
writeException(header, t2);
}
}
}
}
void getWithMetadata(HotRodHeader header, Subject subject, byte[] key, int offset) {
ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
getWithMetadataInternal(header, cache, key, offset);
}
private void getWithMetadataInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, byte[] key, int offset) {
CompletableFuture<CacheEntry<byte[], byte[]>> get = cache.getCacheEntryAsync(key);
if (get.isDone() && !get.isCompletedExceptionally()) {
handleGetWithMetadata(header, offset, key, get.join(), null);
} else {
get.whenComplete((ce, throwable) -> handleGetWithMetadata(header, offset, key, ce, throwable));
}
}
private void handleGetWithMetadata(HotRodHeader header, int offset, byte[] key, CacheEntry<byte[], byte[]> entry, Throwable throwable) {
if (throwable != null) {
writeException(header, throwable);
return;
}
if (entry == null) {
writeNotExist(header);
} else if (header.op == HotRodOperation.GET_WITH_METADATA) {
assert offset == 0;
addToFilter(header.cacheName, key);
writeResponse(header, header.encoder().getWithMetadataResponse(header, server, channel, entry));
} else {
if (entry == null) {
offset = 0;
}
writeResponse(header, header.encoder().getStreamResponse(header, server, channel, offset, entry));
}
}
void containsKey(HotRodHeader header, Subject subject, byte[] key) {
ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
containsKeyInternal(header, cache, key);
}
private void containsKeyInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, byte[] key) {
CompletableFuture<Boolean> contains = cache.containsKeyAsync(key);
if (contains.isDone() && !contains.isCompletedExceptionally()) {
handleContainsKey(header, contains.join(), null);
} else {
contains.whenComplete((result, throwable) -> handleContainsKey(header, result, throwable));
}
}
private void handleContainsKey(HotRodHeader header, Boolean result, Throwable throwable) {
if (throwable != null) {
writeException(header, throwable);
} else if (result) {
writeSuccess(header);
} else {
writeNotExist(header);
}
}
void put(HotRodHeader header, Subject subject, byte[] key, byte[] value, Metadata.Builder metadata) {
Object span = telemetryService.requestStart(HotRodOperation.PUT.name(), header.otherParams);
ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
metadata.version(cacheInfo.versionGenerator.generateNew());
putInternal(header, cache, key, value, metadata.build(), span);
}
private void putInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, byte[] key, byte[] value,
Metadata metadata, Object span) {
cache.putAsyncEntry(key, value, metadata)
.whenComplete((ce, throwable) -> handlePut(header, ce, throwable, span));
}
private void handlePut(HotRodHeader header, CacheEntry<byte[], byte[]> ce, Throwable throwable, Object span) {
if (throwable != null) {
writeException(header, span, throwable);
} else {
writeSuccess(header, ce);
}
telemetryService.requestEnd(span);
}
void replaceIfUnmodified(HotRodHeader header, Subject subject, byte[] key, long version, byte[] value, Metadata.Builder metadata) {
Object span = telemetryService.requestStart(HotRodOperation.REPLACE_IF_UNMODIFIED.name(), header.otherParams);
ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
metadata.version(cacheInfo.versionGenerator.generateNew());
replaceIfUnmodifiedInternal(header, cache, key, version, value, metadata.build(), span);
}
private void replaceIfUnmodifiedInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, byte[] key,
long version, byte[] value, Metadata metadata, Object span) {
cache.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).getCacheEntryAsync(key)
.whenComplete((entry, throwable) -> {
handleGetForReplaceIfUnmodified(header, cache, entry, version, value, metadata, throwable, span);
});
}
private void handleGetForReplaceIfUnmodified(HotRodHeader header, AdvancedCache<byte[], byte[]> cache,
CacheEntry<byte[], byte[]> entry, long version, byte[] value,
Metadata metadata, Throwable throwable, Object span) {
if (throwable != null) {
writeException(header, span, throwable);
telemetryService.requestEnd(span);
} else if (entry != null) {
NumericVersion streamVersion = new NumericVersion(version);
if (streamVersion.equals(entry.getMetadata().version())) {
cache.replaceAsync(entry.getKey(), entry.getValue(), value, metadata)
.whenComplete((replaced, throwable2) -> {
if (throwable2 != null) {
writeException(header, span, throwable2);
} else if (replaced) {
writeSuccess(header, entry);
} else {
writeNotExecuted(header, entry);
}
telemetryService.requestEnd(span);
});
} else {
writeNotExecuted(header, entry);
telemetryService.requestEnd(span);
}
} else {
writeNotExist(header);
telemetryService.requestEnd(span);
}
}
void replace(HotRodHeader header, Subject subject, byte[] key, byte[] value, Metadata.Builder metadata) {
Object span = telemetryService.requestStart(HotRodOperation.REPLACE.name(), header.otherParams);
ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
metadata.version(cacheInfo.versionGenerator.generateNew());
replaceInternal(header, cache, key, value, metadata.build(), span);
}
private void replaceInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, byte[] key, byte[] value,
Metadata metadata, Object span) {
// Avoid listener notification for a simple optimization
// on whether a new version should be calculated or not.
cache.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).getAsync(key)
.whenComplete((prev, throwable) -> {
handleGetForReplace(header, cache, key, prev, value, metadata, throwable, span);
});
}
private void handleGetForReplace(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, byte[] key, byte[] prev,
byte[] value, Metadata metadata, Throwable throwable, Object span) {
if (throwable != null) {
writeException(header, span, throwable);
telemetryService.requestEnd(span);
} else if (prev != null) {
// Generate new version only if key present
cache.replaceAsyncEntry(key, value, metadata)
.whenComplete((ce, throwable1) -> handleReplace(header, ce, throwable1, span));
} else {
writeNotExecuted(header);
telemetryService.requestEnd(span);
}
}
private void handleReplace(HotRodHeader header, CacheEntry<byte[], byte[]> result, Throwable throwable, Object span) {
if (throwable != null) {
writeException(header, span, throwable);
} else if (result != null) {
writeSuccess(header, result);
} else {
writeNotExecuted(header);
}
telemetryService.requestEnd(span);
}
void putIfAbsent(HotRodHeader header, Subject subject, byte[] key, byte[] value, Metadata.Builder metadata) {
Object span = telemetryService.requestStart(HotRodOperation.PUT_IF_ABSENT.name(), header.otherParams);
ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
metadata.version(cacheInfo.versionGenerator.generateNew());
putIfAbsentInternal(header, cache, key, value, metadata.build(), span);
}
private void putIfAbsentInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, byte[] key, byte[] value,
Metadata metadata, Object span) {
cache.putIfAbsentAsyncEntry(key, value, metadata).whenComplete((prev, throwable) -> {
handlePutIfAbsent(header, prev, throwable, span);
});
}
private void handlePutIfAbsent(HotRodHeader header, CacheEntry<byte[], byte[]> result, Throwable throwable, Object span) {
if (throwable != null) {
writeException(header, span, throwable);
telemetryService.requestEnd(span);
} else if (result == null) {
writeSuccess(header);
} else {
writeNotExecuted(header, result);
}
telemetryService.requestEnd(span);
}
void remove(HotRodHeader header, Subject subject, byte[] key) {
Object span = telemetryService.requestStart(HotRodOperation.REMOVE.name(), header.otherParams);
ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
removeInternal(header, cache, key, span);
}
private void removeInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, byte[] key,
Object span) {
cache.removeAsyncEntry(key).whenComplete((ce, throwable) -> handleRemove(header, ce, throwable, span));
}
private void handleRemove(HotRodHeader header, CacheEntry<byte[], byte[]> ce, Throwable throwable, Object span) {
if (throwable != null) {
writeException(header, span, throwable);
} else if (ce != null) {
writeSuccess(header, ce);
} else {
writeNotExist(header);
}
telemetryService.requestEnd(span);
}
void removeIfUnmodified(HotRodHeader header, Subject subject, byte[] key, long version) {
Object span = telemetryService.requestStart(HotRodOperation.REMOVE_IF_UNMODIFIED.name(), header.otherParams);
ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
removeIfUnmodifiedInternal(header, cache, key, version, span);
}
private void removeIfUnmodifiedInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, byte[] key,
long version, Object span) {
cache.getCacheEntryAsync(key)
.whenComplete((entry, throwable) -> {
handleGetForRemoveIfUnmodified(header, cache, entry, key, version, throwable, span);
});
}
private void handleGetForRemoveIfUnmodified(HotRodHeader header, AdvancedCache<byte[], byte[]> cache,
CacheEntry<byte[], byte[]> entry, byte[] key, long version,
Throwable throwable, Object span) {
if (throwable != null) {
writeException(header, span, throwable);
telemetryService.requestEnd(span);
} else if (entry != null) {
byte[] prev = entry.getValue();
NumericVersion streamVersion = new NumericVersion(version);
if (streamVersion.equals(entry.getMetadata().version())) {
cache.removeAsync(key, prev).whenComplete((removed, throwable2) -> {
if (throwable2 != null) {
writeException(header, span, throwable2);
} else if (removed) {
writeSuccess(header, entry);
} else {
writeNotExecuted(header, entry);
}
telemetryService.requestEnd(span);
});
} else {
writeNotExecuted(header, entry);
telemetryService.requestEnd(span);
}
} else {
writeNotExist(header);
telemetryService.requestEnd(span);
}
}
void clear(HotRodHeader header, Subject subject) {
Object span = telemetryService.requestStart(HotRodOperation.CLEAR.name(), header.otherParams);
ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
clearInternal(header, cache, span);
}
private void clearInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, Object span) {
cache.clearAsync().whenComplete((nil, throwable) -> {
if (throwable != null) {
writeException(header, span, throwable);
} else {
writeSuccess(header);
}
telemetryService.requestEnd(span);
});
}
void putAll(HotRodHeader header, Subject subject, Map<byte[], byte[]> entries, Metadata.Builder metadata) {
Object span = telemetryService.requestStart(HotRodOperation.PUT_ALL.name(), header.otherParams);
ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
metadata.version(cacheInfo.versionGenerator.generateNew());
putAllInternal(header, cache, entries, metadata.build(), span);
}
private void putAllInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, Map<byte[], byte[]> entries,
Metadata metadata, Object span) {
cache.putAllAsync(entries, metadata).whenComplete((nil, throwable) -> handlePutAll(header, throwable, span));
}
private void handlePutAll(HotRodHeader header, Throwable throwable, Object span) {
if (throwable != null) {
writeException(header, span, throwable);
} else {
writeSuccess(header);
}
telemetryService.requestEnd(span);
}
void getAll(HotRodHeader header, Subject subject, Set<?> keys) {
ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
getAllInternal(header, cache, keys);
}
private void getAllInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, Set<?> keys) {
cache.getAllAsync(keys)
.whenComplete((map, throwable) -> handleGetAll(header, map, throwable));
}
private void handleGetAll(HotRodHeader header, Map<byte[], byte[]> map, Throwable throwable) {
if (throwable != null) {
writeException(header, throwable);
} else {
writeResponse(header, header.encoder().getAllResponse(header, server, channel, map));
}
}
void size(HotRodHeader header, Subject subject) {
Object span = telemetryService.requestStart(HotRodOperation.SIZE.name(), header.otherParams);
AdvancedCache<byte[], byte[]> cache = server.cache(server.getCacheInfo(header), header, subject);
sizeInternal(header, cache, span);
}
private void sizeInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, Object span) {
cache.sizeAsync()
.whenComplete((size, throwable) -> handleSize(header, size, throwable, span));
}
private void handleSize(HotRodHeader header, Long size, Throwable throwable, Object span) {
if (throwable != null) {
writeException(header, span, throwable);
} else {
writeResponse(header, header.encoder().unsignedLongResponse(header, server, channel, size));
}
telemetryService.requestEnd(span);
}
void bulkGet(HotRodHeader header, Subject subject, int size) {
AdvancedCache<byte[], byte[]> cache = server.cache(server.getCacheInfo(header), header, subject);
executor.execute(() -> bulkGetInternal(header, cache, size));
}
private void bulkGetInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, int size) {
try {
if (log.isTraceEnabled()) {
log.tracef("About to create bulk response count = %d", size);
}
writeResponse(header, header.encoder().bulkGetResponse(header, server, channel, size, cache.entrySet()));
} catch (Throwable t) {
writeException(header, t);
}
}
void bulkGetKeys(HotRodHeader header, Subject subject, int scope) {
AdvancedCache<byte[], byte[]> cache = server.cache(server.getCacheInfo(header), header, subject);
executor.execute(() -> bulkGetKeysInternal(header, cache, scope));
}
private void bulkGetKeysInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, int scope) {
try {
if (log.isTraceEnabled()) {
log.tracef("About to create bulk get keys response scope = %d", scope);
}
writeResponse(header, header.encoder().bulkGetKeysResponse(header, server, channel, cache.keySet().iterator()));
} catch (Throwable t) {
writeException(header, t);
}
}
void query(HotRodHeader header, Subject subject, byte[] queryBytes) {
AdvancedCache<byte[], byte[]> cache = server.cache(server.getCacheInfo(header), header, subject);
executor.execute(() -> queryInternal(header, cache, queryBytes));
}
private void queryInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache, byte[] queryBytes) {
try {
byte[] queryResult = server.query(cache, queryBytes);
writeResponse(header, header.encoder().valueResponse(header, server, channel, OperationStatus.Success, queryResult));
} catch (Throwable t) {
writeException(header, t);
}
}
void addClientListener(HotRodHeader header, Subject subject, byte[] listenerId, boolean includeCurrentState,
String filterFactory, List<byte[]> filterParams, String converterFactory,
List<byte[]> converterParams, boolean useRawData, int listenerInterests, int bloomBits) {
Object span = telemetryService.requestStart(HotRodOperation.ADD_CLIENT_LISTENER.name(), header.otherParams);
AdvancedCache<byte[], byte[]> cache = server.cache(server.getCacheInfo(header), header, subject);
BloomFilter<byte[]> bloomFilter = null;
if (bloomBits > 0) {
bloomFilter = MurmurHash3BloomFilter.createConcurrentFilter(bloomBits);
BloomFilter<byte[]> priorFilter = bloomFilters.putIfAbsent(header.cacheName, bloomFilter);
assert priorFilter == null;
}
CompletionStage<Void> stage = listenerRegistry.addClientListener(channel, header, listenerId, cache,
includeCurrentState, filterFactory, filterParams, converterFactory, converterParams, useRawData,
listenerInterests, bloomFilter);
stage.whenComplete((ignore, cause) -> {
if (cause != null) {
log.trace("Failed to add listener", cause);
if (cause instanceof CompletionException) {
writeException(header, span, cause.getCause());
} else {
writeException(header, span, cause);
}
} else {
writeSuccess(header);
}
telemetryService.requestEnd(span);
});
}
void removeClientListener(HotRodHeader header, Subject subject, byte[] listenerId) {
Object span = telemetryService.requestStart(HotRodOperation.REMOVE_CLIENT_LISTENER.name(), header.otherParams);
AdvancedCache<byte[], byte[]> cache = server.cache(server.getCacheInfo(header), header, subject);
removeClientListenerInternal(header, cache, listenerId, span);
}
private void removeClientListenerInternal(HotRodHeader header, AdvancedCache<byte[], byte[]> cache,
byte[] listenerId, Object span) {
server.getClientListenerRegistry().removeClientListener(listenerId, cache)
.whenComplete((success, throwable) -> {
if (throwable != null) {
writeException(header, span, throwable);
} else {
if (success == Boolean.TRUE) {
writeSuccess(header);
} else {
writeNotExecuted(header);
}
}
telemetryService.requestEnd(span);
});
}
void iterationStart(HotRodHeader header, Subject subject, byte[] segmentMask, String filterConverterFactory,
List<byte[]> filterConverterParams, int batch, boolean includeMetadata) {
AdvancedCache<byte[], byte[]> cache = server.cache(server.getCacheInfo(header), header, subject);
executor.execute(() -> {
try {
IterationState iterationState = server.getIterationManager().start(cache, segmentMask != null ? BitSet.valueOf(segmentMask) : null,
filterConverterFactory, filterConverterParams, header.getValueMediaType(), batch, includeMetadata, DeliveryGuarantee.EXACTLY_ONCE, null);
iterationState.getReaper().registerChannel(channel);
writeResponse(header, header.encoder().iterationStartResponse(header, server, channel, iterationState.getId()));
} catch (Throwable t) {
writeException(header, t);
}
});
}
void iterationNext(HotRodHeader header, Subject subject, String iterationId) {
executor.execute(() -> {
try {
IterableIterationResult iterationResult = server.getIterationManager().next(iterationId, -1);
writeResponse(header, header.encoder().iterationNextResponse(header, server, channel, iterationResult));
} catch (Throwable t) {
writeException(header, t);
}
});
}
void iterationEnd(HotRodHeader header, Subject subject, String iterationId) {
executor.execute(() -> {
try {
IterationState removed = server.getIterationManager().close(iterationId);
writeResponse(header, header.encoder().emptyResponse(header, server, channel, removed != null ? OperationStatus.Success : OperationStatus.InvalidIteration));
} catch (Throwable t) {
writeException(header, t);
}
});
}
void putStream(HotRodHeader header, Subject subject, byte[] key, ByteBuf buf, long version, Metadata.Builder metadata) {
try {
byte[] value = new byte[buf.readableBytes()];
buf.readBytes(value);
if (version == 0) { // Normal put
put(header, subject, key, value, metadata);
} else if (version < 0) { // putIfAbsent
putIfAbsent(header, subject, key, value, metadata);
} else { // versioned replace
replaceIfUnmodified(header, subject, key, version, value, metadata);
}
} finally {
buf.release();
}
}
void writeException(HotRodHeader header, Object span, Throwable cause) {
try {
telemetryService.recordException(span, cause);
} finally {
writeException(header, cause);
}
}
}
| 30,669
| 44.776119
| 169
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/VersionedEncoder.java
|
package org.infinispan.server.hotrod;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import org.infinispan.CacheSet;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.server.core.transport.NettyTransport;
import org.infinispan.server.hotrod.Events.Event;
import org.infinispan.server.hotrod.counter.listener.ClientCounterEvent;
import org.infinispan.server.iteration.IterableIterationResult;
import org.infinispan.stats.ClusterCacheStats;
import org.infinispan.stats.Stats;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
/**
* This class represents the work to be done by an encoder of a particular Hot Rod protocol version.
*
* @author Galder Zamarreño
* @since 5.1
*/
public interface VersionedEncoder {
ByteBuf authResponse(HotRodHeader header, HotRodServer server, Channel channel, byte[] challenge);
ByteBuf authMechListResponse(HotRodHeader header, HotRodServer server, Channel channel, Set<String> mechs);
ByteBuf notExecutedResponse(HotRodHeader header, HotRodServer server, Channel channel, CacheEntry<byte[], byte[]> prev);
ByteBuf notExistResponse(HotRodHeader header, HotRodServer server, Channel channel);
ByteBuf valueResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status, byte[] prev);
ByteBuf valueResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status, CacheEntry<byte[], byte[]> prev);
ByteBuf successResponse(HotRodHeader header, HotRodServer server, Channel channel, CacheEntry<byte[], byte[]> result);
ByteBuf errorResponse(HotRodHeader header, HotRodServer server, Channel channel, String message, OperationStatus status);
ByteBuf bulkGetResponse(HotRodHeader header, HotRodServer server, Channel channel, int size, CacheSet<Map.Entry<byte[], byte[]>> entries);
ByteBuf emptyResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status);
default ByteBuf pingResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status) {
return emptyResponse(header, server, channel, status);
}
ByteBuf statsResponse(HotRodHeader header, HotRodServer server, Channel channel, Stats stats,
NettyTransport transport, ClusterCacheStats clusterCacheStats1);
ByteBuf valueWithVersionResponse(HotRodHeader header, HotRodServer server, Channel channel, byte[] value, long version);
ByteBuf getWithMetadataResponse(HotRodHeader header, HotRodServer server, Channel channel, CacheEntry<byte[], byte[]> entry);
ByteBuf getStreamResponse(HotRodHeader header, HotRodServer server, Channel channel, int offset, CacheEntry<byte[], byte[]> entry);
ByteBuf getAllResponse(HotRodHeader header, HotRodServer server, Channel channel, Map<byte[], byte[]> map);
ByteBuf bulkGetKeysResponse(HotRodHeader header, HotRodServer server, Channel channel, CloseableIterator<byte[]> iterator);
ByteBuf iterationStartResponse(HotRodHeader header, HotRodServer server, Channel channel, String iterationId);
ByteBuf iterationNextResponse(HotRodHeader header, HotRodServer server, Channel channel, IterableIterationResult iterationResult);
ByteBuf counterConfigurationResponse(HotRodHeader header, HotRodServer server, Channel channel, CounterConfiguration configuration);
ByteBuf counterNamesResponse(HotRodHeader header, HotRodServer server, Channel channel, Collection<String> counterNames);
ByteBuf multimapCollectionResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status, Collection<byte[]> values);
ByteBuf multimapEntryResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status, CacheEntry<byte[], Collection<byte[]>> ce);
ByteBuf booleanResponse(HotRodHeader header, HotRodServer server, Channel channel, boolean result);
ByteBuf unsignedLongResponse(HotRodHeader header, HotRodServer server, Channel channel, long value);
ByteBuf longResponse(HotRodHeader header, HotRodServer server, Channel channel, long value);
ByteBuf transactionResponse(HotRodHeader header, HotRodServer server, Channel channel, int xaReturnCode);
OperationStatus errorStatus(Throwable t);
/**
* Write an event, including its header, using the given channel buffer
*/
void writeEvent(Event e, ByteBuf buf);
/**
* Writes a {@link ClientCounterEvent}, including its header, using a giver channel buffer.
*/
void writeCounterEvent(ClientCounterEvent event, ByteBuf buffer);
ByteBuf recoveryResponse(HotRodHeader header, HotRodServer server, Channel channel, Collection<XidImpl> xids);
}
| 4,849
| 47.019802
| 159
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/TransactionWrite.java
|
package org.infinispan.server.hotrod;
import org.infinispan.commons.util.Util;
import org.infinispan.metadata.Metadata;
import org.infinispan.server.hotrod.tx.ControlByte;
class TransactionWrite {
final byte[] key;
final long versionRead;
final Metadata.Builder metadata;
final byte[] value;
private final byte control;
TransactionWrite(byte[] key, long versionRead, byte control, byte[] value, Metadata.Builder metadata) {
this.key = key;
this.versionRead = versionRead;
this.control = control;
this.value = value;
this.metadata = metadata;
}
public boolean isRemove() {
return ControlByte.REMOVE_OP.hasFlag(control);
}
@Override
public String toString() {
return "TransactionWrite{" +
"key=" + Util.printArray(key, true) +
", versionRead=" + versionRead +
", control=" + ControlByte.prettyPrint(control) +
", metadata=" + metadata +
", value=" + Util.printArray(value, true) +
'}';
}
boolean skipRead() {
return ControlByte.NOT_READ.hasFlag(control);
}
boolean wasNonExisting() {
return ControlByte.NON_EXISTING.hasFlag(control);
}
}
| 1,217
| 26.066667
| 106
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/Encoder4x.java
|
package org.infinispan.server.hotrod;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.util.Util;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.server.hotrod.logging.Log;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
public class Encoder4x extends Encoder2x {
private static final Log log = LogFactory.getLog(Encoder2x.class, Log.class);
private static final Encoder4x INSTANCE = new Encoder4x();
public static Encoder4x instance() {
return INSTANCE;
}
@Override
public ByteBuf valueResponse(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status, CacheEntry<byte[], byte[]> prev) {
ByteBuf buf = writeMetadataResponse(header, server, channel, status, prev);
if (log.isTraceEnabled()) {
log.tracef("Write response to %s messageId=%d status=%s prev=%s", header.op, header.messageId, status, Util.printArray(prev != null ? prev.getValue() : null));
}
return buf;
}
}
| 1,035
| 36
| 168
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/Intrinsics.java
|
package org.infinispan.server.hotrod;
import org.infinispan.commons.io.SignedNumeric;
import org.infinispan.server.core.transport.ExtendedByteBufJava;
import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;
public class Intrinsics {
public static int vInt(ByteBuf buf) {
buf.markReaderIndex();
return ExtendedByteBufJava.readMaybeVInt(buf);
}
public static int signedVInt(ByteBuf buf) {
buf.markReaderIndex();
return SignedNumeric.decode(ExtendedByteBufJava.readMaybeVInt(buf));
}
public static long vLong(ByteBuf buf) {
buf.markReaderIndex();
return ExtendedByteBufJava.readMaybeVLong(buf);
}
public static long long_(ByteBuf buf) {
if (buf.readableBytes() >= 8) {
return buf.readLong();
} else return 0;
}
public static byte byte_(ByteBuf buffer) {
if (buffer.isReadable()) {
return buffer.readByte();
} else return 0;
}
public static boolean bool(ByteBuf buffer) {
if (buffer.isReadable()) {
return buffer.readByte() != 0;
}
return false;
}
public static byte[] array(ByteBuf buf) {
buf.markReaderIndex();
return ExtendedByteBufJava.readMaybeRangedBytes(buf);
}
public static byte[] fixedArray(ByteBuf buf, int length) {
buf.markReaderIndex();
return ExtendedByteBufJava.readMaybeRangedBytes(buf, length);
}
public static String string(ByteBuf buf) {
buf.markReaderIndex();
return ExtendedByteBufJava.readString(buf);
}
public static byte[] optionalArray(ByteBuf buf) {
buf.markReaderIndex();
int pos = buf.readerIndex();
int length = ExtendedByteBufJava.readMaybeVInt(buf);
if (pos == buf.readerIndex()) {
return null;
}
length = SignedNumeric.decode(length);
if (length < 0) {
return null;
}
return ExtendedByteBufJava.readMaybeRangedBytes(buf, length);
}
public static String optionalString(ByteBuf buf) {
byte[] bytes = optionalArray(buf);
if (bytes == null) {
return null;
} else if (bytes.length == 0) {
return "";
} else {
return new String(bytes, CharsetUtil.UTF_8);
}
}
public static ByteBuf readable(ByteBuf buf, int length) {
if (buf.readableBytes() >= length) {
buf.readerIndex(buf.readerIndex() + length);
return buf;
} else {
return null;
}
}
}
| 2,473
| 25.602151
| 74
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodDecoderState.java
|
package org.infinispan.server.hotrod;
/**
* Protocol decoding state
*
* @author Galder Zamarreño
* @since 4.2
*/
public enum HotRodDecoderState {
DECODE_HEADER,
DECODE_HEADER_CUSTOM,
DECODE_KEY,
DECODE_KEY_CUSTOM,
DECODE_PARAMETERS,
DECODE_VALUE,
DECODE_VALUE_CUSTOM,
}
| 297
| 15.555556
| 37
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/CrashedMemberDetectorListener.java
|
package org.infinispan.server.hotrod;
import java.util.List;
import java.util.stream.Collectors;
import org.infinispan.Cache;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.context.Flag;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged;
import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent;
import org.infinispan.remoting.transport.Address;
import org.infinispan.server.hotrod.logging.Log;
/**
* Listener that detects crashed or stopped members and removes them from the address cache.
*
* @author Galder Zamarreño
* @since 5.1
*/
@Listener(sync = false)
// Use a separate thread to avoid blocking the view handler thread
class CrashedMemberDetectorListener {
private final Cache<Address, ServerAddress> addressCache;
private static final Log log = LogFactory.getLog(CrashedMemberDetectorListener.class, Log.class);
CrashedMemberDetectorListener(Cache<Address, ServerAddress> cache, HotRodServer server) {
// Let all nodes remove the address from their own cache locally.
// This will exclude the address from their topology updates.
this.addressCache = cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL);
}
@ViewChanged
public void handleViewChange(ViewChangedEvent e) {
detectCrashedMember(e);
}
void detectCrashedMember(ViewChangedEvent e) {
try {
if (addressCache.getStatus().allowInvocations()) {
List<Address> goneMembers = e.getOldMembers().stream().filter(o -> !e.getNewMembers().contains(o)).collect(Collectors.toList());
log.tracef("View change received: %s, removing members %s", e, goneMembers);
// Consider doing removeAsync and then waiting for all removals...
goneMembers.forEach(addressCache::remove);
}
} catch (Throwable t) {
log.errorDetectingCrashedMember(t);
}
}
}
| 1,985
| 36.471698
| 140
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/configuration/package-info.java
|
/**
* HotRod Server Configuration API
*
* @api.public
*/
package org.infinispan.server.hotrod.configuration;
| 113
| 15.285714
| 51
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/configuration/Element.java
|
package org.infinispan.server.hotrod.configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @author Tristan Tarrant
* @since 10.0
*/
public enum Element {
UNKNOWN(null), //must be first
AUTHENTICATION,
ENCRYPTION,
FORWARD_SECRECY,
HOTROD_CONNECTOR,
NO_ACTIVE,
NO_ANONYMOUS,
NO_DICTIONARY,
NO_PLAIN_TEXT,
PASS_CREDENTIALS,
POLICY,
PROPERTIES,
PROPERTY,
SASL,
SNI,
TOPOLOGY_STATE_TRANSFER,
;
private static final Map<String, Element> ELEMENTS;
static {
final Map<String, Element> map = new HashMap<>(8);
for (Element element : values()) {
final String name = element.name;
if (name != null) {
map.put(name, element);
}
}
ELEMENTS = map;
}
private final String name;
Element(final String name) {
this.name = name;
}
Element() {
this.name = name().toLowerCase().replace('_', '-');
}
public static Element forName(final String localName) {
final Element element = ELEMENTS.get(localName);
return element == null ? UNKNOWN : element;
}
@Override
public String toString() {
return name;
}
}
| 1,194
| 17.968254
| 58
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/configuration/HotRodServerChildConfigurationBuilder.java
|
package org.infinispan.server.hotrod.configuration;
import org.infinispan.configuration.cache.LockingConfigurationBuilder;
import org.infinispan.configuration.cache.StateTransferConfigurationBuilder;
import org.infinispan.server.core.configuration.SaslAuthenticationConfigurationBuilder;
/**
* HotRodServerChildConfigurationBuilder.
*
* @author Tristan Tarrant
* @since 7.0
*/
public interface HotRodServerChildConfigurationBuilder {
/**
* Configures authentication for this endpoint
*/
SaslAuthenticationConfigurationBuilder authentication();
/**
* Sets the external address of this node, i.e. the address which clients will connect to
*/
HotRodServerChildConfigurationBuilder proxyHost(String proxyHost);
/**
* Sets the external port of this node, i.e. the port which clients will connect to
*/
HotRodServerChildConfigurationBuilder proxyPort(int proxyPort);
/**
* Configures the lock acquisition timeout for the topology cache. See {@link LockingConfigurationBuilder#lockAcquisitionTimeout(long)}.
* Defaults to 10 seconds
*/
HotRodServerChildConfigurationBuilder topologyLockTimeout(long topologyLockTimeout);
/**
* Configures the replication timeout for the topology cache. See {@link org.infinispan.configuration.cache.ClusteringConfigurationBuilder#remoteTimeout(long)}.
* Defaults to 10 seconds
*/
HotRodServerChildConfigurationBuilder topologyReplTimeout(long topologyReplTimeout);
/**
* Configures whether to enable waiting for initial state transfer for the topology cache. See {@link
* StateTransferConfigurationBuilder#awaitInitialTransfer(boolean)}
*/
HotRodServerChildConfigurationBuilder topologyAwaitInitialTransfer(boolean topologyAwaitInitialTransfer);
/**
* Configures whether to honor or override the network prefix returned for the available interfaces.
* Defaults to override and to use the IANA private address conventions defined in RFC 1918
*/
HotRodServerConfigurationBuilder topologyNetworkPrefixOverride(boolean topologyNetworkPrefixOverride);
/**
* Configures whether to enable state transfer for the topology cache. If disabled, a {@link
* org.infinispan.persistence.cluster.ClusterLoader} will be used to lazily retrieve topology information from the
* other nodes. Defaults to true.
*/
HotRodServerChildConfigurationBuilder topologyStateTransfer(boolean topologyStateTransfer);
}
| 2,465
| 38.774194
| 163
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/configuration/TopologyCacheConfigurationBuilder.java
|
package org.infinispan.server.hotrod.configuration;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
public class TopologyCacheConfigurationBuilder implements Builder<TopologyCacheConfiguration> {
private final AttributeSet attributes;
TopologyCacheConfigurationBuilder() {
this.attributes = TopologyCacheConfiguration.attributeDefinitionSet();
}
@Override
public AttributeSet attributes() {
return attributes;
}
public TopologyCacheConfigurationBuilder lockTimeout(long value) {
attributes.attribute(TopologyCacheConfiguration.TOPOLOGY_LOCK_TIMEOUT).set(value);
return this;
}
public TopologyCacheConfigurationBuilder replicationTimeout(long value) {
attributes.attribute(TopologyCacheConfiguration.TOPOLOGY_REPL_TIMEOUT).set(value);
return this;
}
public TopologyCacheConfigurationBuilder awaitInitialTransfer(boolean await) {
attributes.attribute(TopologyCacheConfiguration.TOPOLOGY_AWAIT_INITIAL_TRANSFER).set(await);
return this;
}
public TopologyCacheConfigurationBuilder lazyRetrieval(boolean lazy) {
attributes.attribute(TopologyCacheConfiguration.LAZY_RETRIEVAL).set(lazy);
return this;
}
public TopologyCacheConfigurationBuilder networkPrefixOverride(boolean networkPrefixOverride) {
attributes.attribute(TopologyCacheConfiguration.NETWORK_PREFIX_OVERRIDE).set(networkPrefixOverride);
return this;
}
@Override
public TopologyCacheConfiguration create() {
return new TopologyCacheConfiguration(attributes.protect());
}
@Override
public TopologyCacheConfigurationBuilder read(TopologyCacheConfiguration template, Combine combine) {
attributes.read(template.attributes(), combine);
return this;
}
}
| 1,899
| 33.545455
| 106
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/configuration/AbstractHotRodServerChildConfigurationBuilder.java
|
package org.infinispan.server.hotrod.configuration;
import org.infinispan.server.core.configuration.SaslAuthenticationConfigurationBuilder;
/**
* AbstractHotRodServerChildConfigurationBuilder.
*
* @author Tristan Tarrant
* @since 7.0
*/
public abstract class AbstractHotRodServerChildConfigurationBuilder implements HotRodServerChildConfigurationBuilder {
private final HotRodServerChildConfigurationBuilder builder;
protected AbstractHotRodServerChildConfigurationBuilder(HotRodServerChildConfigurationBuilder builder) {
this.builder = builder;
}
@Override
public SaslAuthenticationConfigurationBuilder authentication() {
return builder.authentication();
}
@Override
public HotRodServerChildConfigurationBuilder proxyHost(String proxyHost) {
return builder.proxyHost(proxyHost);
}
@Override
public HotRodServerChildConfigurationBuilder proxyPort(int proxyPort) {
return builder.proxyPort(proxyPort);
}
@Override
public HotRodServerChildConfigurationBuilder topologyLockTimeout(long topologyLockTimeout) {
return builder.topologyLockTimeout(topologyLockTimeout);
}
@Override
public HotRodServerChildConfigurationBuilder topologyReplTimeout(long topologyReplTimeout) {
return builder.topologyReplTimeout(topologyReplTimeout);
}
@Override
public HotRodServerChildConfigurationBuilder topologyAwaitInitialTransfer(boolean topologyAwaitInitialTransfer) {
return builder.topologyAwaitInitialTransfer(topologyAwaitInitialTransfer);
}
@Override
public HotRodServerChildConfigurationBuilder topologyStateTransfer(boolean topologyStateTransfer) {
return builder.topologyStateTransfer(topologyStateTransfer);
}
@Override
public HotRodServerConfigurationBuilder topologyNetworkPrefixOverride(boolean topologyNetworkPrefixOverride) {
return builder.topologyNetworkPrefixOverride(topologyNetworkPrefixOverride);
}
}
| 1,954
| 32.706897
| 118
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/configuration/TopologyCacheConfiguration.java
|
package org.infinispan.server.hotrod.configuration;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.configuration.attributes.ConfigurationElement;
/**
* @since 10.0
*/
public class TopologyCacheConfiguration extends ConfigurationElement<TopologyCacheConfiguration> {
public static final AttributeDefinition<Boolean> TOPOLOGY_AWAIT_INITIAL_TRANSFER = AttributeDefinition.builder(Attribute.AWAIT_INITIAL_RETRIEVAL, true).immutable().build();
public static final AttributeDefinition<Long> TOPOLOGY_LOCK_TIMEOUT = AttributeDefinition.builder(Attribute.LOCK_TIMEOUT, 10000L).immutable().build();
public static final AttributeDefinition<Long> TOPOLOGY_REPL_TIMEOUT = AttributeDefinition.builder(Attribute.REPLICATION_TIMEOUT, 10000L).immutable().build();
public static final AttributeDefinition<Boolean> LAZY_RETRIEVAL = AttributeDefinition.builder(Attribute.LAZY_RETRIEVAL, false).immutable().build();
public static final AttributeDefinition<Boolean> NETWORK_PREFIX_OVERRIDE = AttributeDefinition.builder(Attribute.NETWORK_PREFIX_OVERRIDE, true).immutable().build();
public static AttributeSet attributeDefinitionSet() {
return new AttributeSet(TopologyCacheConfiguration.class, TOPOLOGY_AWAIT_INITIAL_TRANSFER, TOPOLOGY_LOCK_TIMEOUT, TOPOLOGY_REPL_TIMEOUT, LAZY_RETRIEVAL, NETWORK_PREFIX_OVERRIDE);
}
TopologyCacheConfiguration(AttributeSet attributes) {
super(Element.TOPOLOGY_STATE_TRANSFER, attributes);
}
public long lockTimeout() {
return attributes.attribute(TOPOLOGY_LOCK_TIMEOUT).get();
}
public long replicationTimeout() {
return attributes.attribute(TOPOLOGY_REPL_TIMEOUT).get();
}
public boolean awaitInitialTransfer() {
return attributes.attribute(TOPOLOGY_AWAIT_INITIAL_TRANSFER).get();
}
public boolean lazyRetrieval() {
return attributes.attribute(LAZY_RETRIEVAL).get();
}
public boolean networkPrefixOverride() {
return attributes.attribute(NETWORK_PREFIX_OVERRIDE).get();
}
}
| 2,126
| 46.266667
| 184
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/configuration/HotRodServerConfiguration.java
|
package org.infinispan.server.hotrod.configuration;
import org.infinispan.commons.configuration.BuiltBy;
import org.infinispan.commons.configuration.ConfigurationFor;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.server.core.configuration.EncryptionConfiguration;
import org.infinispan.server.core.configuration.IpFilterConfiguration;
import org.infinispan.server.core.configuration.ProtocolServerConfiguration;
import org.infinispan.server.core.configuration.SaslAuthenticationConfiguration;
import org.infinispan.server.core.configuration.SslConfiguration;
import org.infinispan.server.hotrod.HotRodServer;
@BuiltBy(HotRodServerConfigurationBuilder.class)
@ConfigurationFor(HotRodServer.class)
public class HotRodServerConfiguration extends ProtocolServerConfiguration<HotRodServerConfiguration, SaslAuthenticationConfiguration> {
public static final String TOPOLOGY_CACHE_NAME_PREFIX = "___hotRodTopologyCache";
public static final AttributeDefinition<String> PROXY_HOST = AttributeDefinition.builder(Attribute.EXTERNAL_HOST, null, String.class).immutable().build();
public static final AttributeDefinition<Integer> PROXY_PORT = AttributeDefinition.builder(Attribute.EXTERNAL_PORT, -1).immutable().build();
// The Hot Rod server has a different default
public static final AttributeDefinition<Integer> WORKER_THREADS = AttributeDefinition.builder("worker-threads", 160).immutable().build();
private final TopologyCacheConfiguration topologyCache;
private final EncryptionConfiguration encryption;
public static AttributeSet attributeDefinitionSet() {
return new AttributeSet(HotRodServerConfiguration.class, ProtocolServerConfiguration.attributeDefinitionSet(),
WORKER_THREADS, PROXY_HOST, PROXY_PORT);
}
HotRodServerConfiguration(AttributeSet attributes,
TopologyCacheConfiguration topologyCache,
SslConfiguration ssl, SaslAuthenticationConfiguration authentication,
EncryptionConfiguration encryption, IpFilterConfiguration ipRules) {
super(Element.HOTROD_CONNECTOR, attributes, authentication, ssl, ipRules);
this.topologyCache = topologyCache;
this.encryption = encryption;
}
public String proxyHost() {
return attributes.attribute(PROXY_HOST).get();
}
public String publicHost() {
return attributes.attribute(PROXY_HOST).orElse(host());
}
public int proxyPort() {
return attributes.attribute(PROXY_PORT).get();
}
public int publicPort() {
return attributes.attribute(PROXY_PORT).orElse(port());
}
public String topologyCacheName() {
String name = name();
return TOPOLOGY_CACHE_NAME_PREFIX + (name.length() > 0 ? "_" + name : name);
}
public long topologyLockTimeout() {
return topologyCache.lockTimeout();
}
public long topologyReplTimeout() {
return topologyCache.replicationTimeout();
}
public boolean topologyAwaitInitialTransfer() {
return topologyCache.awaitInitialTransfer();
}
public boolean networkPrefixOverride() {
return topologyCache.networkPrefixOverride();
}
/**
* @deprecated since 11.0. To be removed in 14.0 ISPN-11864 with no direct replacement.
*/
@Deprecated
public boolean topologyStateTransfer() {
return !topologyCache.lazyRetrieval();
}
@Override
public SaslAuthenticationConfiguration authentication() {
return authentication;
}
public TopologyCacheConfiguration topologyCache() {
return topologyCache;
}
public EncryptionConfiguration encryption() {
return encryption;
}
}
| 3,782
| 37.212121
| 157
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/configuration/Attribute.java
|
package org.infinispan.server.hotrod.configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @author Tristan Tarrant
* @since 10.0
*/
public enum Attribute {
UNKNOWN(null), // must be first
AWAIT_INITIAL_RETRIEVAL,
EXTERNAL_HOST,
EXTERNAL_PORT,
HOST_NAME,
LAZY_RETRIEVAL,
LOCK_TIMEOUT,
MECHANISMS,
NAME,
NETWORK_PREFIX_OVERRIDE,
POLICY,
QOP,
REPLICATION_TIMEOUT,
REQUIRE_SSL_CLIENT_AUTH,
SECURITY_REALM,
SERVER_PRINCIPAL,
SERVER_NAME,
SOCKET_BINDING,
TOPOLOGY_STATE_TRANSFER,
STRENGTH,
VALUE;
private static final Map<String, Attribute> ATTRIBUTES;
static {
final Map<String, Attribute> map = new HashMap<>(64);
for (Attribute attribute : values()) {
final String name = attribute.name;
if (name != null) {
map.put(name, attribute);
}
}
ATTRIBUTES = map;
}
private final String name;
Attribute(final String name) {
this.name = name;
}
Attribute() {
this.name = name().toLowerCase().replace('_', '-');
}
public static Attribute forName(String localName) {
final Attribute attribute = ATTRIBUTES.get(localName);
return attribute == null ? UNKNOWN : attribute;
}
@Override
public String toString() {
return name;
}
}
| 1,335
| 18.940299
| 60
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/configuration/HotRodServerConfigurationBuilder.java
|
package org.infinispan.server.hotrod.configuration;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.HOST;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.NAME;
import static org.infinispan.server.hotrod.configuration.HotRodServerConfiguration.PROXY_HOST;
import static org.infinispan.server.hotrod.configuration.HotRodServerConfiguration.PROXY_PORT;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.configuration.cache.LockingConfigurationBuilder;
import org.infinispan.configuration.cache.StateTransferConfigurationBuilder;
import org.infinispan.server.core.configuration.EncryptionConfigurationBuilder;
import org.infinispan.server.core.configuration.ProtocolServerConfigurationBuilder;
import org.infinispan.server.core.configuration.SaslAuthenticationConfiguration;
import org.infinispan.server.core.configuration.SaslAuthenticationConfigurationBuilder;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.logging.Log;
/**
* HotRodServerConfigurationBuilder.
*
* @author Tristan Tarrant
* @since 5.3
*/
public class HotRodServerConfigurationBuilder extends ProtocolServerConfigurationBuilder<HotRodServerConfiguration, HotRodServerConfigurationBuilder, SaslAuthenticationConfiguration> implements
Builder<HotRodServerConfiguration>, HotRodServerChildConfigurationBuilder {
private final SaslAuthenticationConfigurationBuilder authentication = new SaslAuthenticationConfigurationBuilder(this);
private final TopologyCacheConfigurationBuilder topologyCache = new TopologyCacheConfigurationBuilder();
private final EncryptionConfigurationBuilder encryption = new EncryptionConfigurationBuilder(ssl());
private static final String DEFAULT_NAME = "hotrod";
public HotRodServerConfigurationBuilder() {
super(HotRodServer.DEFAULT_HOTROD_PORT, HotRodServerConfiguration.attributeDefinitionSet());
}
@Override
public AttributeSet attributes() {
return attributes;
}
@Override
public HotRodServerConfigurationBuilder self() {
return this;
}
@Override
public SaslAuthenticationConfigurationBuilder authentication() {
return authentication;
}
public EncryptionConfigurationBuilder encryption() {
return encryption;
}
/**
* Sets the external address of this node, i.e. the address which clients will connect to
*/
@Override
public HotRodServerConfigurationBuilder proxyHost(String proxyHost) {
attributes.attribute(PROXY_HOST).set(proxyHost);
return this;
}
/**
* Sets the external port of this node, i.e. the port which clients will connect to
*/
@Override
public HotRodServerConfigurationBuilder proxyPort(int proxyPort) {
attributes.attribute(PROXY_PORT).set(proxyPort);
return this;
}
/**
* Configures the lock acquisition timeout for the topology cache. See {@link LockingConfigurationBuilder#lockAcquisitionTimeout(long)}.
* Defaults to 10 seconds
*/
@Override
public HotRodServerConfigurationBuilder topologyLockTimeout(long topologyLockTimeout) {
topologyCache.lockTimeout(topologyLockTimeout);
return this;
}
/**
* Configures the replication timeout for the topology cache. See {@link org.infinispan.configuration.cache.ClusteringConfigurationBuilder#remoteTimeout(long)}.
* Defaults to 10 seconds
*/
@Override
public HotRodServerConfigurationBuilder topologyReplTimeout(long topologyReplTimeout) {
topologyCache.replicationTimeout(topologyReplTimeout);
return this;
}
/**
* Configures whether to enable waiting for initial state transfer for the topology cache. See {@link
* StateTransferConfigurationBuilder#awaitInitialTransfer(boolean)}
*/
@Override
public HotRodServerConfigurationBuilder topologyAwaitInitialTransfer(boolean topologyAwaitInitialTransfer) {
topologyCache.awaitInitialTransfer(topologyAwaitInitialTransfer);
return this;
}
@Override
public HotRodServerConfigurationBuilder topologyNetworkPrefixOverride(boolean topologyNetworkPrefixOverride) {
topologyCache.networkPrefixOverride(topologyNetworkPrefixOverride);
return this;
}
/**
* Configures whether to enable state transfer for the topology cache. If disabled, a {@link
* org.infinispan.persistence.cluster.ClusterLoader} will be used to lazily retrieve topology information from the
* other nodes. Defaults to true.
*
* @deprecated since 11.0. To be removed in 14.0 ISPN-11864 with no direct replacement.
*/
@Override
@Deprecated
public HotRodServerConfigurationBuilder topologyStateTransfer(boolean topologyStateTransfer) {
topologyCache.lazyRetrieval(!topologyStateTransfer);
return this;
}
@Override
public HotRodServerConfiguration create() {
if (!attributes.attribute(NAME).isModified()) {
String socketBinding = socketBinding();
name(DEFAULT_NAME + (socketBinding == null ? "" : "-" + socketBinding));
}
return new HotRodServerConfiguration(attributes.protect(), topologyCache.create(), ssl.create(), authentication.create(), encryption.create(), ipFilter.create());
}
@Override
public HotRodServerConfigurationBuilder read(HotRodServerConfiguration template, Combine combine) {
super.read(template, combine);
this.topologyCache.read(template.topologyCache(), combine);
this.encryption.read(template.encryption(), combine);
return this;
}
@Override
public void validate() {
super.validate();
if (attributes.attribute(PROXY_HOST).isNull() && attributes.attribute(HOST).isNull()) {
throw Log.CONFIG.missingHostAddress();
}
topologyCache.validate();
encryption.validate();
}
public HotRodServerConfiguration build(boolean validate) {
if (validate) {
validate();
}
return create();
}
@Override
public HotRodServerConfiguration build() {
return build(true);
}
}
| 6,222
| 36.715152
| 193
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/command/Ids.java
|
package org.infinispan.server.hotrod.command;
import org.infinispan.commands.ReplicableCommand;
/**
* The ids of the {@link ReplicableCommand} used by this module.
* <p>
* range: 140-141
*
* @author Pedro Ruivo
* @since 9.1
*/
public interface Ids {
byte FORWARD_COMMIT = (byte) (140 & 0xFF);
byte FORWARD_ROLLBACK = (byte) (141 & 0xFF);
}
| 356
| 18.833333
| 64
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/command/HotRodModuleCommandExtensions.java
|
package org.infinispan.server.hotrod.command;
import org.infinispan.commands.module.ModuleCommandExtensions;
import org.infinispan.commands.module.ModuleCommandFactory;
import org.infinispan.commands.remote.CacheRpcCommand;
/**
* It register the {@link HotRodCommandFactory} to handle the {@link CacheRpcCommand} used by this module.
*
* @author Pedro Ruivo
* @since 9.1
*/
public final class HotRodModuleCommandExtensions implements ModuleCommandExtensions {
@Override
public ModuleCommandFactory getModuleCommandFactory() {
return new HotRodCommandFactory();
}
}
| 588
| 28.45
| 106
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/command/HotRodCommandFactory.java
|
package org.infinispan.server.hotrod.command;
import static java.lang.String.format;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.module.ModuleCommandFactory;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.server.hotrod.command.tx.ForwardCommitCommand;
import org.infinispan.server.hotrod.command.tx.ForwardRollbackCommand;
import org.infinispan.util.ByteString;
/**
* A {@link ModuleCommandFactory} that builds {@link CacheRpcCommand} used by this module.
*
* @author Pedro Ruivo
* @since 9.1
*/
final class HotRodCommandFactory implements ModuleCommandFactory {
@Override
public Map<Byte, Class<? extends ReplicableCommand>> getModuleCommands() {
Map<Byte, Class<? extends ReplicableCommand>> moduleCommands = new HashMap<>(2);
moduleCommands.put(Ids.FORWARD_COMMIT, ForwardCommitCommand.class);
moduleCommands.put(Ids.FORWARD_ROLLBACK, ForwardRollbackCommand.class);
return moduleCommands;
}
@Override
public ReplicableCommand fromStream(byte commandId) {
return null;
}
@Override
public CacheRpcCommand fromStream(byte commandId, ByteString cacheName) {
switch (commandId) {
case Ids.FORWARD_COMMIT:
return new ForwardCommitCommand(cacheName);
case Ids.FORWARD_ROLLBACK:
return new ForwardRollbackCommand(cacheName);
default:
throw new IllegalArgumentException(format("Not registered to handle command id %s", commandId));
}
}
}
| 1,591
| 32.166667
| 108
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/command/tx/AbstractForwardTxCommand.java
|
package org.infinispan.server.hotrod.command.tx;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.util.ByteString;
/**
* Abstract class that provides common methods for {@link ForwardCommitCommand} and {@link ForwardRollbackCommand}.
*
* @author Ryan Emerson
* @since 10.0
*/
abstract class AbstractForwardTxCommand extends BaseRpcCommand {
protected XidImpl xid;
protected long timeout;
AbstractForwardTxCommand(ByteString cacheName) {
super(cacheName);
}
AbstractForwardTxCommand(ByteString cacheName, XidImpl xid, long timeout) {
super(cacheName);
this.xid = xid;
this.timeout = timeout;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public boolean canBlock() {
return true;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
XidImpl.writeTo(output, xid);
output.writeLong(timeout);
}
@Override
public void readFrom(ObjectInput input) throws IOException {
xid = XidImpl.readFrom(input);
timeout = input.readLong();
}
}
| 1,261
| 22.37037
| 115
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/command/tx/ForwardRollbackCommand.java
|
package org.infinispan.server.hotrod.command.tx;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.server.hotrod.command.Ids;
import org.infinispan.server.hotrod.tx.operation.Util;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* A {@link CacheRpcCommand} implementation to forward the rollback request from a client to the member that run the
* transaction.
*
* @author Pedro Ruivo
* @since 9.1
*/
public class ForwardRollbackCommand extends AbstractForwardTxCommand {
public ForwardRollbackCommand(ByteString cacheName) {
super(cacheName);
}
public ForwardRollbackCommand(ByteString cacheName, XidImpl xid, long timeout) {
super(cacheName, xid, timeout);
}
@Override
public byte getCommandId() {
return Ids.FORWARD_ROLLBACK;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable {
Util.rollbackLocalTransaction(componentRegistry.getCache().wired(), xid, timeout);
return CompletableFutures.completedNull();
}
@Override
public String toString() {
return "ForwardRollbackCommand{" +
"cacheName=" + cacheName +
", xid=" + xid +
'}';
}
}
| 1,439
| 27.8
| 116
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/command/tx/ForwardCommitCommand.java
|
package org.infinispan.server.hotrod.command.tx;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.server.hotrod.command.Ids;
import org.infinispan.server.hotrod.tx.operation.Util;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* A {@link CacheRpcCommand} implementation to forward the commit request from a client to the member that run the
* transaction.
*
* @author Pedro Ruivo
* @since 9.1
*/
public class ForwardCommitCommand extends AbstractForwardTxCommand {
public ForwardCommitCommand(ByteString cacheName) {
super(cacheName);
}
public ForwardCommitCommand(ByteString cacheName, XidImpl xid, long timeout) {
super(cacheName, xid, timeout);
}
@Override
public byte getCommandId() {
return Ids.FORWARD_COMMIT;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable {
Util.commitLocalTransaction(componentRegistry.getCache().wired(), xid, timeout);
return CompletableFutures.completedNull();
}
@Override
public String toString() {
return "ForwardCommitCommand{" +
"cacheName=" + cacheName +
", xid=" + xid +
'}';
}
}
| 1,424
| 28.081633
| 114
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/logging/Log.java
|
package org.infinispan.server.hotrod.logging;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.WARN;
import java.net.SocketAddress;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.dataconversion.EncodingException;
import org.infinispan.counter.exception.CounterException;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.notifications.cachelistener.event.Event;
import org.infinispan.server.hotrod.MissingFactoryException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.logging.annotations.Once;
/**
* Log abstraction for the Hot Rod server module. For this module, message ids ranging from 6001 to 7000 inclusively
* have been reserved.
*
* @author Galder Zamarreño
* @since 5.0
*/
@MessageLogger(projectCode = "ISPN")
public interface Log extends BasicLogger {
Log CONFIG = Logger.getMessageLogger(Log.class, "org.infinispan.CONFIG");
@LogMessage(level = ERROR)
@Message(value = "Exception reported", id = 5003)
void exceptionReported(@Cause Throwable t);
@LogMessage(level = WARN)
@Message(value = "No members for new topology after applying consistent hash %s filtering into base topology %s", id = 5019)
void noMembersInHashTopology(ConsistentHash ch, String topologyMap);
@LogMessage(level = WARN)
@Message(value = "No members in new topology", id = 5020)
void noMembersInTopology();
@LogMessage(level = ERROR)
@Message(value = "Error detecting crashed member", id = 6002)
void errorDetectingCrashedMember(@Cause Throwable t);
@Message(value = "The requested operation is invalid", id = 6007)
UnsupportedOperationException invalidOperation();
@Message(value = "Event not handled by current Hot Rod event implementation: '%s'", id = 6009)
IllegalStateException unexpectedEvent(Event e);
@LogMessage(level = WARN)
@Message(value = "Conditional operation '%s' should be used with transactional caches, otherwise data inconsistency issues could arise under failure situations", id = 6010)
@Once
void warnConditionalOperationNonTransactional(String op);
@LogMessage(level = WARN)
@Message(value = "Operation '%s' forced to return previous value should be used on transactional caches, otherwise data inconsistency issues could arise under failure situations", id = 6011)
@Once
void warnForceReturnPreviousNonTransactional(String op);
@Message(value = "Listener %s factory '%s' not found in server", id = 6013)
MissingFactoryException missingCacheEventFactory(String factoryType, String name);
@Message(value = "Trying to add a filter and converter factory with name '%s' but it does not extend CacheEventFilterConverterFactory", id = 6014)
IllegalStateException illegalFilterConverterEventFactory(String name);
/*
Moved to server-core
@Message(value = "Factory '%s' not found in server", id = 6016)
IllegalStateException missingKeyValueFilterConverterFactory(String name);
*/
@Message(value = "Operation '%s' requires authentication", id = 6017)
SecurityException unauthorizedOperation(String op);
@Message(value = "A host or proxyHost address has not been specified", id = 6019)
CacheConfigurationException missingHostAddress();
@Message(value = "Cache '%s' is not transactional to execute a client transaction", id = 6020)
IllegalStateException expectedTransactionalCache(String cacheName);
@Message(value = "Cache '%s' must have REPEATABLE_READ isolation level", id = 6021)
IllegalStateException unexpectedIsolationLevel(String cacheName);
@Message(value = "Expects a STRONG counter for '%s'", id = 28023)
CounterException invalidWeakCounter(String name);
@LogMessage(level = WARN)
@Message(value = "Not wrapping custom marshaller with media type '%s' since the format is already supported by the server", id = 28024)
@Once
void skippingMarshallerWrapping(String mediaType);
@Message(value = "Error serializing script response '%s'", id = 28025)
EncodingException errorSerializingResponse(Object o);
/* Moved to server-core
@LogMessage(level = WARN)
@Message(value = "Removed unclosed iterator '%s'", id = 28026)
void removedUnclosedIterator(String iteratorId);
*/
@Message(value = "Invalid credentials", id = 28027)
SecurityException authenticationException(@Cause Throwable cause);
@Message(value = "Invalid mech '%s'", id = 28028)
IllegalArgumentException invalidMech(String mech);
@LogMessage(level = WARN)
@Message(value = "Client %s keeps providing outdated topology %s", id = 28029)
void clientNotUpdatingTopology(SocketAddress socketAddress, int topologyId);
}
| 4,941
| 41.603448
| 193
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/logging/HotRodAccessLogging.java
|
package org.infinispan.server.hotrod.logging;
import java.net.InetSocketAddress;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import org.infinispan.commons.util.Util;
import org.infinispan.server.hotrod.AccessLoggingHeader;
import org.infinispan.server.hotrod.HotRodVersion;
import org.infinispan.util.logging.LogFactory;
import org.jboss.logging.Logger;
import org.jboss.logging.MDC;
import io.netty.channel.ChannelFuture;
/**
* Logging handler for Hot Rod to log what requests have come into the server
*
* @author wburns
* @since 9.0
*/
public class HotRodAccessLogging {
private final static Logger log = LogFactory.getLogger("HOTROD_ACCESS_LOG");
public static boolean isEnabled() {
return log.isTraceEnabled();
}
public void logOK(ChannelFuture future, AccessLoggingHeader header, int responseBytes) {
logAfterComplete(future, header, responseBytes, "OK");
}
public void logException(ChannelFuture future, AccessLoggingHeader header, String exception, int responseBytes) {
logAfterComplete(future, header, responseBytes, exception);
}
private void logAfterComplete(ChannelFuture future, AccessLoggingHeader header, int responseBytes, String status) {
String remoteAddress = ((InetSocketAddress)future.channel().remoteAddress()).getHostString();
future.addListener(f -> {
// Duration
long duration;
if (header.requestStart == null) {
duration = -1;
} else {
duration = ChronoUnit.MILLIS.between(header.requestStart, Instant.now());
}
MDC.clear();
MDC.put("address", remoteAddress);
MDC.put("user", checkForNull(header.principalName));
MDC.put("method", checkForNull(header.getOp()));
MDC.put("protocol", checkForNull(HotRodVersion.forVersion(header.getVersion())));
MDC.put("status", checkForNull(status));
MDC.put("responseSize", responseBytes);
MDC.put("requestSize", header.requestBytes);
MDC.put("duration", duration);
log.tracef("/%s/%s", checkForNull(header.getCacheName()), checkForNull(header.key));
});
}
String checkForNull(Object obj) {
if (obj == null || obj instanceof String && ((String) obj).isEmpty()) {
return "-";
} else if (obj instanceof byte[]) {
return Util.printArray((byte[]) obj);
} else {
return obj.toString();
}
}
}
| 2,461
| 34.171429
| 118
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/ServerTransactionOriginatorChecker.java
|
package org.infinispan.server.hotrod.tx;
import java.util.Collection;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.server.hotrod.tx.table.ClientAddress;
import org.infinispan.transaction.impl.TransactionOriginatorChecker;
import org.infinispan.transaction.xa.GlobalTransaction;
/**
* A {@link TransactionOriginatorChecker} implementation that is aware of client transactions.
* <p>
* The transaction originator in this case is the Hot Rod client.
*
* @author Pedro Ruivo
* @since 9.1
*/
@Scope(Scopes.NAMED_CACHE)
public class ServerTransactionOriginatorChecker implements TransactionOriginatorChecker {
@Inject RpcManager rpcManager;
@Override
public boolean isOriginatorMissing(GlobalTransaction gtx) {
return isOriginatorMissing(gtx, rpcManager.getMembers());
}
@Override
public boolean isOriginatorMissing(GlobalTransaction gtx, Collection<Address> liveMembers) {
return !liveMembers.contains(gtx.getAddress()) && isNonClientTransaction(gtx);
}
private boolean isNonClientTransaction(GlobalTransaction gtx) {
return !(gtx.getAddress() instanceof ClientAddress);
}
}
| 1,347
| 32.7
| 95
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/PrepareCoordinator.java
|
package org.infinispan.server.hotrod.tx;
import static org.infinispan.remoting.transport.impl.VoidResponseCollector.validOnly;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionStage;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import org.infinispan.AdvancedCache;
import org.infinispan.cache.impl.CacheImpl;
import org.infinispan.cache.impl.DecoratedCache;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.commons.util.Util;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.context.impl.LocalTxInvocationContext;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.server.hotrod.tx.table.CacheXid;
import org.infinispan.server.hotrod.tx.table.GlobalTxTable;
import org.infinispan.server.hotrod.tx.table.PerCacheTxTable;
import org.infinispan.server.hotrod.tx.table.Status;
import org.infinispan.server.hotrod.tx.table.TxState;
import org.infinispan.server.hotrod.tx.table.functions.CreateStateFunction;
import org.infinispan.server.hotrod.tx.table.functions.PreparingDecisionFunction;
import org.infinispan.server.hotrod.tx.table.functions.SetCompletedTransactionFunction;
import org.infinispan.server.hotrod.tx.table.functions.SetDecisionFunction;
import org.infinispan.server.hotrod.tx.table.functions.SetPreparedFunction;
import org.infinispan.server.hotrod.tx.table.functions.TxFunction;
import org.infinispan.transaction.impl.LocalTransaction;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.transaction.xa.TransactionFactory;
import org.infinispan.util.ByteString;
/**
* A class that handles the prepare request from the Hot Rod clients.
*
* @author Pedro Ruivo
* @since 9.4
*/
public class PrepareCoordinator {
private final AdvancedCache<?, ?> cache;
private final XidImpl xid;
private final PerCacheTxTable perCacheTxTable;
private final TransactionTable transactionTable;
private final CacheXid cacheXid;
private final GlobalTxTable globalTxTable;
private final long transactionTimeout;
private EmbeddedTransaction tx;
private LocalTxInvocationContext localTxInvocationContext;
private final boolean recoverable;
public PrepareCoordinator(AdvancedCache<byte[], byte[]> cache, XidImpl xid, boolean recoverable,
long transactionTimeout) {
this.xid = xid;
this.recoverable = recoverable;
this.transactionTimeout = transactionTimeout;
this.cache = cache;
ComponentRegistry registry = cache.getComponentRegistry();
this.transactionTable = registry.getComponent(TransactionTable.class);
this.perCacheTxTable = registry.getComponent(PerCacheTxTable.class);
this.globalTxTable = registry.getGlobalComponentRegistry().getComponent(GlobalTxTable.class);
this.cacheXid = new CacheXid(ByteString.fromString(cache.getName()), xid);
}
/**
* @return The current {@link TxState} associated to the transaction.
*/
public final TxState getTxState() {
return globalTxTable.getState(cacheXid);
}
/**
* @return {@code true} if the {@code address} is still in the cluster.
*/
public final boolean isAlive(Address address) {
RpcManager rpcManager = cache.getRpcManager();
return rpcManager == null || rpcManager.getMembers().contains(address);
}
/**
* Rollbacks a transaction that is remove in all the cluster members.
*/
public final void rollbackRemoteTransaction(GlobalTransaction gtx) {
RpcManager rpcManager = cache.getRpcManager();
ComponentRegistry componentRegistry = cache.getComponentRegistry();
CommandsFactory factory = componentRegistry.getCommandsFactory();
try {
RollbackCommand rollbackCommand = factory.buildRollbackCommand(gtx);
rollbackCommand.setTopologyId(rpcManager.getTopologyId());
CompletionStage<Void> cs = rpcManager
.invokeCommandOnAll(rollbackCommand, validOnly(), rpcManager.getSyncRpcOptions());
rollbackCommand.invokeAsync(componentRegistry).toCompletableFuture().join();
cs.toCompletableFuture().join();
} catch (Throwable throwable) {
throw Util.rewrapAsCacheException(throwable);
} finally {
forgetTransaction(gtx, rpcManager, factory);
}
}
/**
* Starts a transaction.
*
* @return {@code true} if the transaction can be started, {@code false} otherwise.
*/
public boolean startTransaction() {
EmbeddedTransaction tx = new EmbeddedTransaction(EmbeddedTransactionManager.getInstance());
tx.setXid(xid);
LocalTransaction localTransaction = transactionTable
.getOrCreateLocalTransaction(tx, false, this::newGlobalTransaction);
if (createGlobalState(localTransaction.getGlobalTransaction()) != Status.OK) {
//no need to rollback. nothing is enlisted in the transaction.
transactionTable.removeLocalTransaction(localTransaction);
return false;
} else {
this.tx = tx;
this.localTxInvocationContext = new LocalTxInvocationContext(localTransaction);
perCacheTxTable.createLocalTx(xid, tx);
transactionTable.enlistClientTransaction(tx, localTransaction);
return true;
}
}
/**
* Rollbacks the transaction if an exception happens during the transaction execution.
*/
public int rollback() {
//log rolling back
loggingDecision(false);
//perform rollback
try {
tx.rollback();
} catch (SystemException e) {
//ignore exception (heuristic exceptions)
//TODO logging
} finally {
perCacheTxTable.removeLocalTx(xid);
}
//log rolled back
loggingCompleted(false);
return XAException.XA_RBROLLBACK;
}
/**
* Marks the transaction as rollback-only.
*/
public void setRollbackOnly() {
tx.setRollbackOnly();
}
/**
* Prepares the transaction.
*
* @param onePhaseCommit {@code true} if one phase commit.
* @return the {@link javax.transaction.xa.XAResource#XA_OK} if successful prepared, otherwise one of the {@link
* javax.transaction.xa.XAException} error codes.
*/
public int prepare(boolean onePhaseCommit) {
Status status = loggingPreparing();
if (status != Status.OK) {
//error, marked_*, no_transaction code (other node changed the state). we simply reply with rollback
return XAException.XA_RBROLLBACK;
}
boolean prepared = tx.runPrepare();
if (prepared) {
if (onePhaseCommit) {
return onePhaseCommitTransaction();
} else {
status = loggingPrepared();
return status == Status.OK ? XAResource.XA_OK : XAException.XA_RBROLLBACK;
}
} else {
//Infinispan automatically rollbacks the transaction
//we try to update the state and we don't care about the response.
loggingCompleted(false);
perCacheTxTable.removeLocalTx(xid);
return XAException.XA_RBROLLBACK;
}
}
/**
* Decorates the cache with the transaction created.
*/
public <K, V> AdvancedCache<K, V> decorateCache(AdvancedCache<K, V> cache) {
return cache.transform(this::transform);
}
/**
* Commits a remote 1PC transaction that is already in MARK_COMMIT state
*/
public int onePhaseCommitRemoteTransaction(GlobalTransaction gtx, List<WriteCommand> modifications) {
RpcManager rpcManager = cache.getRpcManager();
ComponentRegistry componentRegistry = cache.getComponentRegistry();
CommandsFactory factory = componentRegistry.getCommandsFactory();
try {
//only pessimistic tx are committed in 1PC and it doesn't use versions.
PrepareCommand command = factory.buildPrepareCommand(gtx, modifications, true);
CompletionStage<Void> cs = rpcManager.invokeCommandOnAll(command, validOnly(), rpcManager.getSyncRpcOptions());
command.invokeAsync(componentRegistry).toCompletableFuture().join();
cs.toCompletableFuture().join();
forgetTransaction(gtx, rpcManager, factory);
return loggingCompleted(true) == Status.OK ?
XAResource.XA_OK :
XAException.XAER_RMERR;
} catch (Throwable throwable) {
//transaction should commit but we still can have exceptions (timeouts or similar)
return XAException.XAER_RMERR;
}
}
/**
* Forgets the transaction cluster-wise and from global and local transaction tables.
*/
private void forgetTransaction(GlobalTransaction gtx, RpcManager rpcManager, CommandsFactory factory) {
TxCompletionNotificationCommand cmd = factory.buildTxCompletionNotificationCommand(xid, gtx);
rpcManager.sendToAll(cmd, DeliverOrder.NONE);
perCacheTxTable.removeLocalTx(xid);
globalTxTable.remove(cacheXid);
}
private Status loggingDecision(boolean commit) {
TxFunction function = new SetDecisionFunction(commit);
return globalTxTable.update(cacheXid, function, transactionTimeout);
}
private Status loggingCompleted(boolean committed) {
TxFunction function = new SetCompletedTransactionFunction(committed);
return globalTxTable.update(cacheXid, function, transactionTimeout);
}
private <K, V> AdvancedCache<K, V> transform(AdvancedCache<K, V> cache) {
if (cache instanceof CacheImpl) {
return withTransaction((CacheImpl<K, V>) cache);
} else {
return cache;
}
}
private <K, V> AdvancedCache<K, V> withTransaction(CacheImpl<K, V> cache) {
return new DecoratedCache<K, V>(cache, FlagBitSets.FORCE_WRITE_LOCK) {
@Override
protected InvocationContext readContext(int size) {
return localTxInvocationContext;
}
@Override
protected InvocationContext writeContext(int size) {
return localTxInvocationContext;
}
};
}
private int onePhaseCommitTransaction() {
if (loggingDecision(true) != Status.OK) {
//we failed to update the global cache
return XAException.XAER_RMERR;
}
try {
tx.runCommit(false);
return loggingCompleted(true) == Status.OK ?
XAResource.XA_OK :
XAException.XAER_RMERR; //we failed to update the global cache.
} catch (HeuristicMixedException | HeuristicRollbackException | RollbackException e) {
//Infinispan automatically rollbacks it
loggingCompleted(false);
return XAException.XA_RBROLLBACK;
}
}
private Status loggingPrepared() {
SetPreparedFunction function = new SetPreparedFunction();
return globalTxTable.update(cacheXid, function, transactionTimeout);
}
private Status createGlobalState(GlobalTransaction globalTransaction) {
CreateStateFunction function = new CreateStateFunction(globalTransaction, recoverable, transactionTimeout);
return globalTxTable.update(cacheXid, function, transactionTimeout);
}
private Status loggingPreparing() {
TxFunction function = new PreparingDecisionFunction(copyModifications());
return globalTxTable.update(cacheXid, function, transactionTimeout);
}
private List<WriteCommand> copyModifications() {
List<WriteCommand> modifications = getLocalTransaction().getModifications();
return new ArrayList<>(modifications);
}
private LocalTransaction getLocalTransaction() {
return transactionTable.getLocalTransaction(tx);
}
private GlobalTransaction newGlobalTransaction() {
TransactionFactory factory = cache.getComponentRegistry().getComponent(TransactionFactory.class);
return factory.newGlobalTransaction(perCacheTxTable.getClientAddress(), false);
}
}
| 12,728
| 38.654206
| 120
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/ControlByte.java
|
package org.infinispan.server.hotrod.tx;
/**
* A control byte used by each write operation to flag if the key was read or not, or if the write operation is a remove
* operation
*
* @author Pedro Ruivo
* @since 9.1
*/
public enum ControlByte {
NOT_READ(0x1),
NON_EXISTING(0x2),
REMOVE_OP(0x4);
private final byte bit;
ControlByte(int bit) {
this.bit = (byte) bit;
}
public static String prettyPrint(byte bitSet) {
StringBuilder builder = new StringBuilder("[");
if (NOT_READ.hasFlag(bitSet)) {
builder.append("NOT_READ");
} else if (NON_EXISTING.hasFlag(bitSet)) {
builder.append("NON_EXISTING");
} else {
builder.append("READ");
}
if (REMOVE_OP.hasFlag(bitSet)) {
builder.append(", REMOVED");
}
return builder.append("]").toString();
}
/**
* Sets {@code this} flag to the {@code bitSet}.
*
* @return The new bit set.
*/
public byte set(byte bitSet) {
return (byte) (bitSet | bit);
}
/**
* @return {@code true} if {@code this} flag is set in the {@code bitSet}, {@code false} otherwise.
*/
public boolean hasFlag(byte bitSet) {
return (bitSet & bit) == bit;
}
/**
* @return The bit corresponding to {@code this} flag.
*/
public byte bit() {
return bit;
}
}
| 1,360
| 22.067797
| 120
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/CacheNameCollector.java
|
package org.infinispan.server.hotrod.tx.table;
import org.infinispan.server.hotrod.tx.table.functions.SetDecisionFunction;
import org.infinispan.util.ByteString;
/**
* Used by {@link GlobalTxTable}, it collects all the involved cache name when setting a decision for a transaction.
* <p>
* Initially, {@link #expectedSize(int)} is invoked with the number of caches found. For all cache, it {@link TxState}
* is updated with the decision (via {@link SetDecisionFunction}) and {@link #addCache(ByteString, Status)} is invoked
* with the cache name and the function return value.
* <p>
* If no transaction is found, only {@link #noTransactionFound()} is invoked.
*
* @author Pedro Ruivo
* @since 9.4
*/
public interface CacheNameCollector {
/**
* Sets the expected number of caches involved in the transaction.
*/
void expectedSize(int size);
/**
* Adds the cache name and the {@link SetDecisionFunction} return value.
*/
void addCache(ByteString cacheName, Status status);
/**
* Notifies that no transaction is found.
*/
void noTransactionFound();
}
| 1,107
| 29.777778
| 118
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/Status.java
|
package org.infinispan.server.hotrod.tx.table;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import jakarta.transaction.TransactionManager;
import org.infinispan.server.hotrod.tx.table.functions.TxFunction;
/**
* Internal server status for the client's transactions.
* <p>
* The first 3 values are used as return value for the {@link TxFunction}.
*
* @author Pedro Ruivo
* @since 9.4
*/
public enum Status {
//used as return values
OK(0),
ERROR(1),
NO_TRANSACTION(2),
//real status
/**
* The client transaction is being replayed.
*/
ACTIVE(3),
/**
* The client transaction was replayed successful (versions read are validated) and the transactions is preparing.
*/
PREPARING(4),
/**
* The transaction is successful prepared and it waits for the client {@link TransactionManager} decision to commit
* or rollback
*/
PREPARED(5),
/**
* The client {@link TransactionManager} decided to commit. It can't rollback anymore.
*/
MARK_COMMIT(6),
/**
* The client transaction is committed. No other work can be done.
*/
COMMITTED(7),
/**
* The client {@link TransactionManager} decided to rollback of we fail to replay/prepare the transaction. It can't
* commit anymore.
*/
MARK_ROLLBACK(8),
/**
* The client transaction is rolled back. No other work can be done.
*/
ROLLED_BACK(9);
private static final Status[] CACHE;
static {
Status[] values = Status.values();
CACHE = new Status[values.length];
for (Status s : values) {
CACHE[s.value] = s;
}
}
public final byte value;
Status(int value) {
this.value = (byte) value;
}
public static void writeTo(ObjectOutput output, Status status) throws IOException {
output.writeByte(status.value);
}
public static Status readFrom(ObjectInput input) throws IOException {
return valueOf(input.readByte());
}
public static Status valueOf(byte b) {
return CACHE[b];
}
}
| 2,069
| 23.352941
| 118
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/TxState.java
|
package org.infinispan.server.hotrod.tx.table;
import static org.infinispan.commons.marshall.MarshallUtil.marshallCollection;
import static org.infinispan.commons.marshall.MarshallUtil.unmarshallCollection;
import static org.infinispan.server.hotrod.tx.table.Status.ACTIVE;
import static org.infinispan.server.hotrod.tx.table.Status.PREPARING;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.remoting.transport.Address;
import org.infinispan.server.core.ExternalizerIds;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.commons.time.TimeService;
import net.jcip.annotations.Immutable;
/**
* A transaction state stored globally in all the cluster members.
*
* @author Pedro Ruivo
* @since 9.4
*/
@Immutable
public class TxState {
public static final AdvancedExternalizer<TxState> EXTERNALIZER = new Externalizer();
private final GlobalTransaction globalTransaction;
private final Status status;
private final List<WriteCommand> modifications;
private final boolean recoverable;
private final long timeout; //ms
private final long lastAccessTimeNs; //ns
public TxState(GlobalTransaction globalTransaction, boolean recoverable, long timeout, TimeService timeService) {
this(globalTransaction, ACTIVE, null, recoverable, timeout, timeService.time());
}
private TxState(GlobalTransaction globalTransaction, Status status, List<WriteCommand> modifications,
boolean recoverable, long timeout, long accessTime) {
this.globalTransaction = Objects.requireNonNull(globalTransaction);
this.status = Objects.requireNonNull(status);
this.modifications = modifications == null ? null : Collections.unmodifiableList(modifications);
this.recoverable = recoverable;
this.timeout = timeout;
this.lastAccessTimeNs = accessTime;
}
public long getTimeout() {
return timeout;
}
public TxState markPreparing(List<WriteCommand> modifications, TimeService timeService) {
return new TxState(globalTransaction, PREPARING, modifications, recoverable, timeout,
timeService.time());
}
public Address getOriginator() {
return ((ClientAddress) globalTransaction.getAddress()).getLocalAddress();
}
public TxState setStatus(Status newStatus, boolean cleanupModification, TimeService timeService) {
return new TxState(globalTransaction, newStatus, cleanupModification ? null : modifications, recoverable, timeout,
timeService.time());
}
public Status getStatus() {
return status;
}
public GlobalTransaction getGlobalTransaction() {
return globalTransaction;
}
public List<WriteCommand> getModifications() {
return modifications;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TxState txState = (TxState) o;
return Objects.equals(status, txState.status) &&
Objects.equals(globalTransaction, txState.globalTransaction);
}
@Override
public int hashCode() {
int result = Objects.hashCode(globalTransaction);
result = 31 * result + Objects.hashCode(status);
return result;
}
public boolean hasTimedOut(long currentTimeNs) {
long timeoutNs = TimeUnit.MILLISECONDS.toNanos(timeout);
return lastAccessTimeNs + timeoutNs < currentTimeNs;
}
public boolean isRecoverable() {
return recoverable;
}
@Override
public String toString() {
return "TxState{" +
"globalTransaction=" + globalTransaction +
", status=" + status +
", modifications=" + modifications +
", recoverable=" + recoverable +
", timeout=" + timeout +
", lastAccessTime=" + lastAccessTimeNs +
'}';
}
private static class Externalizer implements AdvancedExternalizer<TxState> {
@Override
public Set<Class<? extends TxState>> getTypeClasses() {
return Collections.singleton(TxState.class);
}
@Override
public Integer getId() {
return ExternalizerIds.TX_STATE;
}
@Override
public void writeObject(ObjectOutput output, TxState object) throws IOException {
output.writeObject(object.globalTransaction);
Status.writeTo(output, object.status);
marshallCollection(object.modifications, output);
output.writeBoolean(object.recoverable);
output.writeLong(object.timeout);
output.writeLong(object.lastAccessTimeNs);
}
@Override
public TxState readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new TxState((GlobalTransaction) input.readObject(),
Status.readFrom(input),
unmarshallCollection(input, ArrayList::new),
input.readBoolean(), input.readLong(), input.readLong());
}
}
}
| 5,346
| 31.406061
| 120
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/ClientAddress.java
|
package org.infinispan.server.hotrod.tx.table;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.remoting.transport.Address;
import org.infinispan.server.core.ExternalizerIds;
/**
* A {@link Address} implementation for a client transaction.
* <p>
* The {@code localAddress} is the address of the node in which the transaction was replayed.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class ClientAddress implements Address {
public static final AdvancedExternalizer<ClientAddress> EXTERNALIZER = new Externalizer();
private final Address localAddress;
public ClientAddress(Address localAddress) {
this.localAddress = localAddress;
}
@Override
public int compareTo(Address o) {
if (o instanceof ClientAddress) {
return localAddress == null ?
(((ClientAddress) o).localAddress == null ? 0 : -1) :
localAddress.compareTo(((ClientAddress) o).localAddress);
}
return -1;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClientAddress that = (ClientAddress) o;
return Objects.equals(localAddress, that.localAddress);
}
@Override
public int hashCode() {
return localAddress == null ? 0 : localAddress.hashCode();
}
@Override
public String toString() {
return "ClientAddress{" +
"localAddress=" + localAddress +
'}';
}
Address getLocalAddress() {
return localAddress;
}
private static class Externalizer implements AdvancedExternalizer<ClientAddress> {
@Override
public Set<Class<? extends ClientAddress>> getTypeClasses() {
return Collections.singleton(ClientAddress.class);
}
@Override
public Integer getId() {
return ExternalizerIds.CLIENT_ADDRESS;
}
@Override
public void writeObject(ObjectOutput output, ClientAddress object) throws IOException {
output.writeObject(object.localAddress);
}
@Override
public ClientAddress readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new ClientAddress((Address) input.readObject());
}
}
}
| 2,496
| 25.849462
| 101
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/PerCacheTxTable.java
|
package org.infinispan.server.hotrod.tx.table;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import jakarta.transaction.Transaction;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.remoting.transport.Address;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.transaction.tm.EmbeddedTransaction;
/**
* A Transaction Table for client transaction.
* <p>
* It stores the global state of a transaction and the map between the {@link XidImpl} and {@link Transaction}'s run
* locally.
*
* @author Pedro Ruivo
* @since 9.4
*/
//TODO merge with org.infinispan.server.hotrod.tx.table.GlobalTxTable
public class PerCacheTxTable {
private static final Log log = LogFactory.getLog(PerCacheTxTable.class, Log.class);
private final Map<XidImpl, EmbeddedTransaction> localTxTable = new ConcurrentHashMap<>();
private final ClientAddress clientAddress;
public PerCacheTxTable(Address address) {
this.clientAddress = new ClientAddress(address);
}
public ClientAddress getClientAddress() {
return clientAddress;
}
/**
* @return The local {@link EmbeddedTransaction} associated to the {@code xid}.
*/
public EmbeddedTransaction getLocalTx(XidImpl xid) {
return localTxTable.get(xid);
}
/**
* Removes the local {@link EmbeddedTransaction} associated to {@code xid}.
*/
public void removeLocalTx(XidImpl xid) {
EmbeddedTransaction tx = localTxTable.remove(xid);
if (log.isTraceEnabled()) {
log.tracef("[%s] Removed tx=%s", xid, tx);
}
}
/**
* Adds the {@link EmbeddedTransaction} in the local transaction table.
*/
public void createLocalTx(XidImpl xid, EmbeddedTransaction tx) {
localTxTable.put(xid, tx);
if (log.isTraceEnabled()) {
log.tracef("[%s] New tx=%s", xid, tx);
}
}
/**
* testing only
*/
public boolean isEmpty() {
if (log.isTraceEnabled()) {
log.tracef("Active Transactions: %s", localTxTable.keySet());
}
return localTxTable.isEmpty();
}
}
| 2,150
| 27.302632
| 116
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/CacheXid.java
|
package org.infinispan.server.hotrod.tx.table;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.server.core.ExternalizerIds;
import org.infinispan.util.ByteString;
/**
* A key used in the global transaction table.
* <p>
* The global transaction table is a replicated cache. This key contains the cache name and the transactions' {@link
* XidImpl}.
*
* @author Pedro Ruivo
* @since 9.1
*/
public class CacheXid {
public static final AdvancedExternalizer<CacheXid> EXTERNALIZER = new Externalizer();
private final ByteString cacheName;
private final XidImpl xid;
public CacheXid(ByteString cacheName, XidImpl xid) {
this.cacheName = cacheName;
this.xid = xid;
}
public boolean sameXid(XidImpl other) {
return xid.equals(other);
}
public static void writeTo(ObjectOutput output, CacheXid object) throws IOException {
ByteString.writeObject(output, object.cacheName);
XidImpl.writeTo(output, object.xid);
}
public static CacheXid readFrom(ObjectInput input) throws IOException {
return new CacheXid(ByteString.readObject(input), XidImpl.readFrom(input));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CacheXid cacheXid = (CacheXid) o;
return cacheName.equals(cacheXid.cacheName) && xid.equals(cacheXid.xid);
}
@Override
public int hashCode() {
int result = cacheName.hashCode();
result = 31 * result + xid.hashCode();
return result;
}
@Override
public String toString() {
return "CacheXid{" +
"cacheName=" + cacheName +
", xid=" + xid +
'}';
}
public ByteString getCacheName() {
return cacheName;
}
public XidImpl getXid() {
return xid;
}
private static class Externalizer implements AdvancedExternalizer<CacheXid> {
@Override
public Set<Class<? extends CacheXid>> getTypeClasses() {
return Collections.singleton(CacheXid.class);
}
@Override
public Integer getId() {
return ExternalizerIds.CACHE_XID;
}
@Override
public void writeObject(ObjectOutput output, CacheXid object) throws IOException {
writeTo(output, object);
}
@Override
public CacheXid readObject(ObjectInput input) throws IOException {
return readFrom(input);
}
}
}
| 2,710
| 24.336449
| 116
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/GlobalTxTable.java
|
package org.infinispan.server.hotrod.tx.table;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import org.infinispan.Cache;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.tx.TransactionBoundaryCommand;
import org.infinispan.commons.api.BasicCache;
import org.infinispan.commons.api.Lifecycle;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.annotations.ComponentName;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.functional.FunctionalMap;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.impl.VoidResponseCollector;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.server.hotrod.tx.table.functions.ConditionalMarkAsRollbackFunction;
import org.infinispan.server.hotrod.tx.table.functions.SetCompletedTransactionFunction;
import org.infinispan.server.hotrod.tx.table.functions.SetDecisionFunction;
import org.infinispan.server.hotrod.tx.table.functions.TxFunction;
import org.infinispan.server.hotrod.tx.table.functions.XidPredicate;
import org.infinispan.stream.CacheCollectors;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.logging.LogFactory;
import net.jcip.annotations.GuardedBy;
/**
* It is a transaction log that registers all the transaction decisions before changing the cache.
* <p>
* The transaction state is stored in {@link TxState}, and that is stored in a replicated cache. The {@link TxState}
* must be updated before performing any action in the transaction (prepare, commit, etc.).
* <p>
* In addition, since we don't have a client crash notification, it performs a reaper work, periodically, that cleanups
* idle transactions. The transaction is considered idle based on the timeout sent by the client. If no decision is made,
* it rollbacks the transaction. If the transaction is completed (committed or rolled-back), it is removed from the
* cache. If the transaction is decided (i.e. marked for commit or rollback), it completes the transaction.
* <p>
* Note that, recoverable transactions (transactions originated from FULL_XA support caches) aren't touched by the
* reaper. The recovery process is responsible to handle them.
*
* @author Pedro Ruivo
* @since 9.4
*/
@Scope(value = Scopes.GLOBAL)
public class GlobalTxTable implements Runnable, Lifecycle {
//TODO think about the possibility of using JGroups RAFT instead of replicated cache?
private static final Log log = LogFactory.getLog(GlobalTxTable.class, Log.class);
private final Cache<CacheXid, TxState> storage;
private final FunctionalMap.ReadWriteMap<CacheXid, TxState> rwMap;
private final GlobalComponentRegistry gcr;
@GuardedBy("this")
private ScheduledFuture<?> scheduledFuture;
@Inject TimeService timeService;
@Inject BlockingManager blockingManager;
@Inject @ComponentName(KnownComponentNames.EXPIRATION_SCHEDULED_EXECUTOR)
ScheduledExecutorService scheduledExecutor;
public GlobalTxTable(Cache<CacheXid, TxState> storage, GlobalComponentRegistry gcr) {
this.storage = storage;
this.rwMap = ReadWriteMapImpl.create(FunctionalMapImpl.create(storage.getAdvancedCache()));
this.gcr = gcr;
}
@Start
public synchronized void start() {
//TODO where to configure it?
//TODO can we avoid to start it here? and only when HT tx is used?
if (scheduledFuture == null) {
scheduledFuture = scheduledExecutor.scheduleWithFixedDelay(this, 60000, 60000, TimeUnit.MILLISECONDS);
}
}
@Stop
public synchronized void stop() {
if (scheduledFuture != null) {
scheduledFuture.cancel(true);
scheduledFuture = null;
}
}
public Status update(CacheXid key, TxFunction function, long timeoutMillis) {
if (log.isTraceEnabled()) {
log.tracef("[%s] Updating with function: %s", key, function);
}
try {
CompletableFuture<Byte> cf = rwMap.eval(key, function);
Status status = Status.valueOf(cf.get(timeoutMillis, TimeUnit.MILLISECONDS));
if (log.isTraceEnabled()) {
log.tracef("[%s] Return value is %s", key, status);
}
return status;
} catch (InterruptedException e) {
if (log.isTraceEnabled()) {
log.tracef("[%s] Interrupted!", key);
}
Thread.currentThread().interrupt();
return Status.ERROR;
} catch (ExecutionException | TimeoutException e) {
if (log.isTraceEnabled()) {
log.tracef(e, "[%s] Error!", key);
}
return Status.ERROR;
}
}
public void markToCommit(XidImpl xid, CacheNameCollector collector) {
markTx(xid, true, collector);
}
public void markToRollback(XidImpl xid, CacheNameCollector collector) {
markTx(xid, false, collector);
}
public TxState getState(CacheXid xid) {
TxState state = storage.get(xid);
if (log.isTraceEnabled()) {
log.tracef("[%s] Get TxState = %s", xid, state);
}
return state;
}
public void remove(CacheXid cacheXid) {
if (log.isTraceEnabled()) {
log.tracef("[%s] Removed!", cacheXid);
}
storage.remove(cacheXid);
}
public void forgetTransaction(XidImpl xid) {
if (log.isTraceEnabled()) {
log.tracef("[%s] Forgetting transaction.", xid);
}
storage.keySet().parallelStream()
.filter(new XidPredicate(xid))
.forEach(BasicCache::remove);
}
/**
* periodically checks for idle transactions and rollbacks them.
*/
@Override
public void run() {
long currentTimestamp = timeService.time();
for (Map.Entry<CacheXid, TxState> entry : storage.entrySet()) {
TxState state = entry.getValue();
CacheXid cacheXid = entry.getKey();
if (!state.hasTimedOut(currentTimestamp) || skipReaper(state.getOriginator(), cacheXid.getCacheName())) {
continue;
}
switch (state.getStatus()) {
case ACTIVE:
case PREPARING:
case PREPARED:
onOngoingTransaction(cacheXid, state);
break;
case MARK_ROLLBACK:
onTransactionDecision(cacheXid, state, false);
break;
case MARK_COMMIT:
onTransactionDecision(cacheXid, state, true);
break;
case COMMITTED:
case ROLLED_BACK:
onTransactionCompleted(cacheXid);
break;
case ERROR:
case NO_TRANSACTION:
case OK:
default:
//not valid status
}
}
}
public Collection<XidImpl> getPreparedTransactions() {
long currentTimestamp = timeService.time();
Collection<XidImpl> preparedTx = new HashSet<>(); //remove duplicates!
for (Map.Entry<CacheXid, TxState> entry : storage.entrySet()) {
XidImpl xid = entry.getKey().getXid();
TxState state = entry.getValue();
if (log.isTraceEnabled()) {
log.tracef("Checking transaction xid=%s for recovery. TimedOut?=%s, Recoverable?=%s, Status=%s",
xid, state.hasTimedOut(currentTimestamp), state.isRecoverable(), state.getStatus());
}
if (state.hasTimedOut(currentTimestamp) && state.isRecoverable() && state.getStatus() == Status.PREPARED) {
preparedTx.add(xid);
}
}
return preparedTx;
}
public boolean isEmpty() {
return storage.isEmpty();
}
private void onOngoingTransaction(CacheXid cacheXid, TxState state) {
if (state.getStatus() == Status.PREPARED && state.isRecoverable()) {
return; //recovery will handle prepared transactions
}
ComponentRegistry cr = gcr.getNamedComponentRegistry(cacheXid.getCacheName());
if (cr == null) {
//we don't have the cache locally
return;
}
RpcManager rpcManager = cr.getComponent(RpcManager.class);
if (isRemote(rpcManager, state.getOriginator())) {
//remotely originated transaction
//this is a weird state. the originator may crashed or it may be in another partition and communication with the client
//in any case, we can rollback the tx
//if we are in the minority partition, updating the global tx table will fail and we do nothing
//if we are in the majority partition, the originator can't commit/rollback since it would fail to update the global tx table
rollbackOldTransaction(cacheXid, state, () -> rollbackRemote(cr, cacheXid, state));
} else {
//local transaction prepared.
PerCacheTxTable txTable = cr.getComponent(PerCacheTxTable.class);
EmbeddedTransaction tx = txTable.getLocalTx(cacheXid.getXid());
if (tx == null) {
//local transaction doesn't exists.
onTransactionCompleted(cacheXid);
} else {
blockingManager.runBlocking(
() -> rollbackOldTransaction(cacheXid, state, () -> completeLocal(txTable, cacheXid, tx, false)),
cacheXid);
}
}
}
private void rollbackOldTransaction(CacheXid cacheXid, TxState state, Runnable onSuccessAction) {
TxFunction txFunction = new ConditionalMarkAsRollbackFunction(state.getStatus());
rwMap.eval(cacheXid, txFunction).thenAccept(aByte -> {
if (aByte == Status.OK.value) {
onSuccessAction.run();
}
});
}
private void rollbackRemote(ComponentRegistry cr, CacheXid cacheXid, TxState state) {
RollbackCommand rpcCommand = cr.getCommandsFactory().buildRollbackCommand(state.getGlobalTransaction());
RpcManager rpcManager = cr.getComponent(RpcManager.class);
rpcCommand.setTopologyId(rpcManager.getTopologyId());
rpcManager.invokeCommandOnAll(rpcCommand, VoidResponseCollector.validOnly(), rpcManager.getSyncRpcOptions())
.thenRun(() -> {
//ignore exception so the rollback can be retried.
//if a node doesn't find the remote transaction, it returns null.
TxFunction function = new SetCompletedTransactionFunction(false);
rwMap.eval(cacheXid, function);
});
}
private void onTransactionDecision(CacheXid cacheXid, TxState state, boolean commit) {
ComponentRegistry cr = gcr.getNamedComponentRegistry(cacheXid.getCacheName());
if (cr == null) {
//we don't have the cache locally
return;
}
RpcManager rpcManager = cr.getComponent(RpcManager.class);
if (rpcManager == null || state.getOriginator().equals(rpcManager.getAddress())) {
//local
PerCacheTxTable txTable = cr.getComponent(PerCacheTxTable.class);
EmbeddedTransaction tx = txTable.getLocalTx(cacheXid.getXid());
if (tx == null) {
//transaction completed
onTransactionCompleted(cacheXid);
} else {
blockingManager.runBlocking(() -> completeLocal(txTable, cacheXid, tx, commit), cacheXid);
}
} else {
if (commit) {
TransactionBoundaryCommand rpcCommand;
if (cr.getComponent(Configuration.class).transaction().lockingMode() == LockingMode.PESSIMISTIC) {
rpcCommand = cr.getCommandsFactory()
.buildPrepareCommand(state.getGlobalTransaction(), state.getModifications(), true);
} else {
rpcCommand = cr.getCommandsFactory().buildCommitCommand(state.getGlobalTransaction());
}
rpcCommand.setTopologyId(rpcManager.getTopologyId());
rpcManager.invokeCommandOnAll(rpcCommand, VoidResponseCollector.validOnly(), rpcManager.getSyncRpcOptions())
.handle((aVoid, throwable) -> {
//TODO?
TxFunction function = new SetCompletedTransactionFunction(true);
rwMap.eval(cacheXid, function);
return null;
});
} else {
rollbackRemote(cr, cacheXid, state);
}
}
}
private void completeLocal(PerCacheTxTable txTable, CacheXid cacheXid, EmbeddedTransaction tx,
boolean commit) {
try {
tx.runCommit(!commit);
} catch (HeuristicMixedException | HeuristicRollbackException | RollbackException e) {
//embedded tx cleanups everything
//TODO log
} finally {
txTable.removeLocalTx(cacheXid.getXid());
}
onTransactionCompleted(cacheXid);
}
private void onTransactionCompleted(CacheXid cacheXid) {
storage.removeAsync(cacheXid);
}
private boolean skipReaper(Address originator, ByteString cacheName) {
ComponentRegistry cr = gcr.getNamedComponentRegistry(cacheName);
if (cr == null) {
//cache is stopped? doesn't exist? we need to handle it
return false;
}
RpcManager rpcManager = cr.getComponent(RpcManager.class);
return isRemote(rpcManager, originator) && //we are not the originator. I
rpcManager.getMembers().contains(originator); //originator is still in the view.
}
private boolean isRemote(RpcManager rpcManager, Address originator) {
return rpcManager != null && !originator.equals(rpcManager.getAddress());
}
private List<CacheXid> getKeys(XidImpl xid) {
return storage.keySet().stream()
.filter(new XidPredicate(xid))
.collect(CacheCollectors.serializableCollector(Collectors::toList));
}
private void markTx(XidImpl xid, boolean commit, CacheNameCollector collector) {
if (log.isTraceEnabled()) {
log.tracef("[%s] Set Transaction Decision to %s", xid, commit ? "Commit" : "Rollback");
}
final List<CacheXid> cacheXids = getKeys(xid);
if (log.isTraceEnabled()) {
log.tracef("[%s] Fetched CacheXids=%s", xid, cacheXids);
}
final int size = cacheXids.size();
if (size == 0) {
collector.noTransactionFound();
return;
}
collector.expectedSize(size);
SetDecisionFunction function = new SetDecisionFunction(commit);
for (CacheXid cacheXid : cacheXids) {
rwMap.eval(cacheXid, function).handle((statusValue, throwable) -> {
Status status;
if (throwable == null) {
status = Status.valueOf(statusValue);
} else {
status = Status.ERROR;
}
collector.addCache(cacheXid.getCacheName(), status);
return null;
});
}
}
}
| 15,983
| 39.77551
| 134
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/functions/TxFunction.java
|
package org.infinispan.server.hotrod.tx.table.functions;
import java.util.function.Function;
import org.infinispan.Cache;
import org.infinispan.commands.functional.functions.InjectableComponent;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView;
import org.infinispan.server.hotrod.tx.table.CacheXid;
import org.infinispan.server.hotrod.tx.table.TxState;
import org.infinispan.commons.time.TimeService;
/**
* A base {@link Function} implementation to update the {@link TxState} stored in {@link Cache}.
* <p>
* It injects the {@link TimeService} to use.
*
* @author Pedro Ruivo
* @since 9.4
*/
public abstract class TxFunction implements Function<EntryView.ReadWriteEntryView<CacheXid, TxState>, Byte>,
InjectableComponent {
protected TimeService timeService;
@Override
public void inject(ComponentRegistry registry) {
timeService = registry.getTimeService();
}
}
| 944
| 29.483871
| 108
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/functions/ConditionalMarkAsRollbackFunction.java
|
package org.infinispan.server.hotrod.tx.table.functions;
import static org.infinispan.server.hotrod.tx.table.Status.ERROR;
import static org.infinispan.server.hotrod.tx.table.Status.MARK_ROLLBACK;
import static org.infinispan.server.hotrod.tx.table.Status.NO_TRANSACTION;
import static org.infinispan.server.hotrod.tx.table.Status.OK;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.functional.EntryView;
import org.infinispan.server.core.ExternalizerIds;
import org.infinispan.server.hotrod.tx.table.CacheXid;
import org.infinispan.server.hotrod.tx.table.Status;
import org.infinispan.server.hotrod.tx.table.TxState;
/**
* It updates the {@link TxState}'s status to {@link Status#MARK_ROLLBACK} if the current status is the expected.
* <p>
* It returns {@link Status#ERROR} if it fails to update the status and {@link Status#NO_TRANSACTION} if the {@link
* TxState} isn't found.
*
* @author Pedro Ruivo
* @since 9.4
*/
public class ConditionalMarkAsRollbackFunction extends TxFunction {
public static final AdvancedExternalizer<ConditionalMarkAsRollbackFunction> EXTERNALIZER = new Externalizer();
private final byte expectStatus;
public ConditionalMarkAsRollbackFunction(Status expected) {
this(expected.value);
}
private ConditionalMarkAsRollbackFunction(byte expectStatus) {
this.expectStatus = expectStatus;
}
@Override
public Byte apply(EntryView.ReadWriteEntryView<CacheXid, TxState> view) {
if (view.find().isPresent()) {
TxState state = view.get();
if (state.getStatus().value == expectStatus) {
view.set(state.setStatus(MARK_ROLLBACK, true, timeService));
return OK.value;
} else {
return ERROR.value;
}
} else {
return NO_TRANSACTION.value;
}
}
private static class Externalizer implements AdvancedExternalizer<ConditionalMarkAsRollbackFunction> {
@Override
public Set<Class<? extends ConditionalMarkAsRollbackFunction>> getTypeClasses() {
return Collections.singleton(ConditionalMarkAsRollbackFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.CONDITIONAL_MARK_ROLLBACK_FUNCTION;
}
@Override
public void writeObject(ObjectOutput output, ConditionalMarkAsRollbackFunction object) throws IOException {
output.writeByte(object.expectStatus);
}
@Override
public ConditionalMarkAsRollbackFunction readObject(ObjectInput input) throws IOException {
return new ConditionalMarkAsRollbackFunction(input.readByte());
}
}
}
| 2,799
| 32.333333
| 115
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/functions/CreateStateFunction.java
|
package org.infinispan.server.hotrod.tx.table.functions;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.functional.EntryView;
import org.infinispan.server.core.ExternalizerIds;
import org.infinispan.server.hotrod.tx.table.CacheXid;
import org.infinispan.server.hotrod.tx.table.Status;
import org.infinispan.server.hotrod.tx.table.TxState;
import org.infinispan.transaction.xa.GlobalTransaction;
/**
* It creates a new {@link TxState}.
* <p>
* It returns {@link Status#ERROR} if the {@link TxState} already exists.
*
* @author Pedro Ruivo
* @since 9.4
*/
public class CreateStateFunction extends TxFunction {
public static final AdvancedExternalizer<CreateStateFunction> EXTERNALIZER = new Externalizer();
private final GlobalTransaction globalTransaction;
private final long timeout;
private final boolean recoverable;
public CreateStateFunction(GlobalTransaction globalTransaction, boolean recoverable, long timeout) {
this.globalTransaction = globalTransaction;
this.recoverable = recoverable;
this.timeout = timeout;
}
@Override
public Byte apply(EntryView.ReadWriteEntryView<CacheXid, TxState> view) {
if (view.find().isPresent()) {
return Status.ERROR.value;
}
view.set(new TxState(globalTransaction, recoverable, timeout, timeService));
return Status.OK.value;
}
private static class Externalizer implements AdvancedExternalizer<CreateStateFunction> {
@Override
public Set<Class<? extends CreateStateFunction>> getTypeClasses() {
return Collections.singleton(CreateStateFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.CREATE_STATE_FUNCTION;
}
@Override
public void writeObject(ObjectOutput output, CreateStateFunction object) throws IOException {
output.writeObject(object.globalTransaction);
output.writeBoolean(object.recoverable);
output.writeLong(object.timeout);
}
@Override
public CreateStateFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new CreateStateFunction((GlobalTransaction) input.readObject(), input.readBoolean(), input.readLong());
}
}
}
| 2,436
| 32.383562
| 119
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/functions/SetDecisionFunction.java
|
package org.infinispan.server.hotrod.tx.table.functions;
import static org.infinispan.server.hotrod.tx.table.Status.MARK_COMMIT;
import static org.infinispan.server.hotrod.tx.table.Status.MARK_ROLLBACK;
import static org.infinispan.server.hotrod.tx.table.Status.NO_TRANSACTION;
import static org.infinispan.server.hotrod.tx.table.Status.OK;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.functional.EntryView;
import org.infinispan.server.core.ExternalizerIds;
import org.infinispan.server.hotrod.tx.table.CacheXid;
import org.infinispan.server.hotrod.tx.table.Status;
import org.infinispan.server.hotrod.tx.table.TxState;
/**
* It sets the transaction decision in {@link TxState}.
* <p>
* The decision can be {@link Status#MARK_ROLLBACK} or {@link Status#MARK_COMMIT} and the {@link TxState} status must be
* valid. If not, it returns the current {@link TxState} status.
* <p>
* If the {@link TxState} doesn't exists, it returns {@link Status#NO_TRANSACTION}.
*
* @author Pedro Ruivo
* @since 9.4
*/
public class SetDecisionFunction extends TxFunction {
public static final AdvancedExternalizer<SetDecisionFunction> EXTERNALIZER = new Externalizer();
private final boolean commit;
public SetDecisionFunction(boolean commit) {
this.commit = commit;
}
@Override
public Byte apply(EntryView.ReadWriteEntryView<CacheXid, TxState> view) {
if (view.find().isPresent()) {
return commit ?
advanceToCommit(view) :
advanceToRollback(view);
} else {
return NO_TRANSACTION.value;
}
}
private byte advanceToRollback(EntryView.ReadWriteEntryView<CacheXid, TxState> view) {
TxState state = view.get();
Status prevState = state.getStatus();
//we can rollback if the transaction is running or prepared
switch (prevState) {
case ACTIVE:
case PREPARED:
case PREPARING:
view.set(state.setStatus(MARK_ROLLBACK, true, timeService));
case MARK_ROLLBACK:
return OK.value;
default:
//any other status, we return it to the caller to decide what to do.
return prevState.value;
}
}
private byte advanceToCommit(EntryView.ReadWriteEntryView<CacheXid, TxState> view) {
TxState state = view.get();
Status prevState = state.getStatus();
//we can advance to commit decision if it is prepared or the commit decision is already set
switch (prevState) {
case PREPARED: //two-phase-commit
case PREPARING: //one-phase-commit
view.set(state.setStatus(MARK_COMMIT, false, timeService));
case MARK_COMMIT:
return OK.value;
default:
//any other status, we return it to the caller to decide what to do.
return prevState.value;
}
}
private static class Externalizer implements AdvancedExternalizer<SetDecisionFunction> {
@Override
public Set<Class<? extends SetDecisionFunction>> getTypeClasses() {
return Collections.singleton(SetDecisionFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.DECISION_FUNCTION;
}
@Override
public void writeObject(ObjectOutput output, SetDecisionFunction object) throws IOException {
output.writeBoolean(object.commit);
}
@Override
public SetDecisionFunction readObject(ObjectInput input) throws IOException {
return new SetDecisionFunction(input.readBoolean());
}
}
}
| 3,740
| 32.702703
| 120
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/functions/SetPreparedFunction.java
|
package org.infinispan.server.hotrod.tx.table.functions;
import static org.infinispan.server.hotrod.tx.table.Status.NO_TRANSACTION;
import static org.infinispan.server.hotrod.tx.table.Status.OK;
import static org.infinispan.server.hotrod.tx.table.Status.PREPARED;
import static org.infinispan.server.hotrod.tx.table.Status.PREPARING;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import jakarta.transaction.TransactionManager;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.functional.EntryView;
import org.infinispan.server.hotrod.tx.table.CacheXid;
import org.infinispan.server.hotrod.tx.table.Status;
import org.infinispan.server.hotrod.tx.table.TxState;
/**
* It sets the transaction as successful prepared.
* <p>
* The {@link TxState} status must be {@link Status#PREPARING}. If not, it returns the current status.
* <p>
* If the {@link TxState} doesn't exist, it returns {@link Status#NO_TRANSACTION}.
* <p>
* Note that the {@link Status#PREPARED} doesn't mean the transaction can commit or not. The decision is made by the
* client {@link TransactionManager}.
*
* @author Pedro Ruivo
* @since 9.4
*/
//TODO: create singleton!
public class SetPreparedFunction extends TxFunction {
public static final AdvancedExternalizer<SetPreparedFunction> EXTERNALIZER = new Externalizer();
@Override
public Byte apply(EntryView.ReadWriteEntryView<CacheXid, TxState> view) {
if (view.find().isPresent()) {
TxState state = view.get();
if (state.getStatus() != PREPARING) {
return state.getStatus().value;
}
view.set(state.setStatus(PREPARED, false, timeService));
return OK.value;
} else {
return NO_TRANSACTION.value;
}
}
private static class Externalizer implements AdvancedExternalizer<SetPreparedFunction> {
@Override
public Set<Class<? extends SetPreparedFunction>> getTypeClasses() {
return Collections.singleton(SetPreparedFunction.class);
}
@Override
public Integer getId() {
return null; // TODO: Customise this generated block
}
@Override
public void writeObject(ObjectOutput output, SetPreparedFunction object) {
//no-op
}
@Override
public SetPreparedFunction readObject(ObjectInput input) {
return new SetPreparedFunction();
}
}
}
| 2,471
| 30.692308
| 116
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/functions/PreparingDecisionFunction.java
|
package org.infinispan.server.hotrod.tx.table.functions;
import static org.infinispan.server.hotrod.tx.table.Status.NO_TRANSACTION;
import static org.infinispan.server.hotrod.tx.table.Status.OK;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.functional.EntryView;
import org.infinispan.server.core.ExternalizerIds;
import org.infinispan.server.hotrod.tx.table.CacheXid;
import org.infinispan.server.hotrod.tx.table.Status;
import org.infinispan.server.hotrod.tx.table.TxState;
/**
* It changes the {@link TxState} status to {@link Status#PREPARING} and stores the transaction modifications.
* <p>
* It returns {@link Status#NO_TRANSACTION} if the {@link TxState} isn't found and the {@link TxState#getStatus()} if
* the current status isn't {@link Status#ACTIVE} or {@link Status#PREPARING}.
*
* @author Pedro Ruivo
* @since 9.4
*/
public class PreparingDecisionFunction extends TxFunction {
public static final AdvancedExternalizer<PreparingDecisionFunction> EXTERNALIZER = new Externalizer();
private final List<WriteCommand> modifications;
public PreparingDecisionFunction(List<WriteCommand> modifications) {
this.modifications = modifications;
}
@Override
public Byte apply(EntryView.ReadWriteEntryView<CacheXid, TxState> view) {
if (view.find().isPresent()) {
TxState state = view.get();
switch (state.getStatus()) {
case ACTIVE:
view.set(state.markPreparing(modifications, timeService));
case PREPARING:
return OK.value;
default:
return state.getStatus().value;
}
} else {
return NO_TRANSACTION.value;
}
}
private static class Externalizer implements AdvancedExternalizer<PreparingDecisionFunction> {
@Override
public Set<Class<? extends PreparingDecisionFunction>> getTypeClasses() {
return Collections.singleton(PreparingDecisionFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.PREPARING_FUNCTION;
}
@Override
public void writeObject(ObjectOutput output, PreparingDecisionFunction object) throws IOException {
MarshallUtil.marshallCollection(object.modifications, output);
}
@Override
public PreparingDecisionFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new PreparingDecisionFunction(MarshallUtil.unmarshallCollection(input, ArrayList::new));
}
}
}
| 2,858
| 33.035714
| 117
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/functions/SetCompletedTransactionFunction.java
|
package org.infinispan.server.hotrod.tx.table.functions;
import static org.infinispan.server.hotrod.tx.table.Status.COMMITTED;
import static org.infinispan.server.hotrod.tx.table.Status.NO_TRANSACTION;
import static org.infinispan.server.hotrod.tx.table.Status.OK;
import static org.infinispan.server.hotrod.tx.table.Status.ROLLED_BACK;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.functional.EntryView;
import org.infinispan.server.core.ExternalizerIds;
import org.infinispan.server.hotrod.tx.table.CacheXid;
import org.infinispan.server.hotrod.tx.table.Status;
import org.infinispan.server.hotrod.tx.table.TxState;
/**
* It marks the transaction as completed in {@link TxState} by setting its status to {@link Status#COMMITTED} or {@link
* Status#ROLLED_BACK}.
* <p>
* It doesn't check the {@link TxState} current status since it should be only invoked when the transaction completes.
* And it returns {@link Status#NO_TRANSACTION} if the {@link TxState} doesn't exist.
*
* @author Pedro Ruivo
* @since 9.4
*/
public class SetCompletedTransactionFunction extends TxFunction {
public static final AdvancedExternalizer<SetCompletedTransactionFunction> EXTERNALIZER = new Externalizer();
private final boolean committed;
public SetCompletedTransactionFunction(boolean committed) {
this.committed = committed;
}
@Override
public Byte apply(EntryView.ReadWriteEntryView<CacheXid, TxState> view) {
if (view.find().isPresent()) {
TxState state = view.get();
view.set(state.setStatus(committed ? COMMITTED : ROLLED_BACK, true, timeService));
return OK.value;
} else {
return NO_TRANSACTION.value;
}
}
private static class Externalizer implements AdvancedExternalizer<SetCompletedTransactionFunction> {
@Override
public Set<Class<? extends SetCompletedTransactionFunction>> getTypeClasses() {
return Collections.singleton(SetCompletedTransactionFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.COMPLETE_FUNCTION;
}
@Override
public void writeObject(ObjectOutput output, SetCompletedTransactionFunction object) throws IOException {
output.writeBoolean(object.committed);
}
@Override
public SetCompletedTransactionFunction readObject(ObjectInput input) throws IOException {
return new SetCompletedTransactionFunction(input.readBoolean());
}
}
}
| 2,658
| 33.532468
| 119
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/table/functions/XidPredicate.java
|
package org.infinispan.server.hotrod.tx.table.functions;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import java.util.function.Predicate;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.server.core.ExternalizerIds;
import org.infinispan.server.hotrod.tx.table.CacheXid;
/**
* A {@link Predicate} to filter the {@link CacheXid} by its {@link XidImpl}.
*
* @author Pedro Ruivo
* @since 9.4
*/
public class XidPredicate implements Predicate<CacheXid> {
public static final AdvancedExternalizer<XidPredicate> EXTERNALIZER = new Externalizer();
private final XidImpl xid;
public XidPredicate(XidImpl xid) {
this.xid = xid;
}
@Override
public boolean test(CacheXid cacheXid) {
return cacheXid.sameXid(xid);
}
private static class Externalizer implements AdvancedExternalizer<XidPredicate> {
@Override
public Set<Class<? extends XidPredicate>> getTypeClasses() {
return Collections.singleton(XidPredicate.class);
}
@Override
public Integer getId() {
return ExternalizerIds.XID_PREDICATE;
}
@Override
public void writeObject(ObjectOutput output, XidPredicate object) throws IOException {
XidImpl.writeTo(output, object.xid);
}
@Override
public XidPredicate readObject(ObjectInput input) throws IOException {
return new XidPredicate(XidImpl.readFrom(input));
}
}
}
| 1,591
| 25.533333
| 92
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/operation/RollbackTransactionOperation.java
|
package org.infinispan.server.hotrod.tx.operation;
import static org.infinispan.server.hotrod.tx.operation.Util.rollbackLocalTransaction;
import java.util.concurrent.CompletionStage;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import javax.security.auth.Subject;
import jakarta.transaction.HeuristicCommitException;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import org.infinispan.AdvancedCache;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.server.hotrod.HotRodHeader;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.command.tx.ForwardRollbackCommand;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.server.hotrod.tx.table.Status;
import org.infinispan.server.hotrod.tx.table.TxState;
import org.infinispan.util.ByteString;
import org.infinispan.util.logging.LogFactory;
/**
* It rollbacks a transaction in all involved caches.
*
* @author Pedro Ruivo
* @since 9.4
*/
public class RollbackTransactionOperation extends BaseCompleteTransactionOperation {
private static final Log log = LogFactory.getLog(RollbackTransactionOperation.class, Log.class);
//TODO check if this class can implement the BiFunction interface!
private final BiFunction<?, Throwable, Void> handler = (ignored, throwable) -> {
if (throwable != null) {
while (throwable != null) {
if (throwable instanceof HeuristicRollbackException || throwable instanceof RollbackException) {
hasRollbacks = true;
return null;
} else if (throwable instanceof HeuristicCommitException) {
hasCommits = true;
} else if (throwable instanceof HeuristicMixedException) {
hasCommits = true;
hasRollbacks = true;
return null;
}
throwable = throwable.getCause();
}
//any other exception will fit here.
//note: we don't have to handle suspect/outdated topology exceptions. The reaper will rollback the tx later.
hasErrors = true;
} else {
hasRollbacks = true;
}
return null;
};
public RollbackTransactionOperation(HotRodHeader header, HotRodServer server, Subject subject, XidImpl xid,
BiConsumer<HotRodHeader, Integer> reply) {
super(header, server, subject, xid, reply);
}
@Override
public void run() {
globalTxTable.markToRollback(xid, this);
}
@Override
public void addCache(ByteString cacheName, Status status) {
if (log.isTraceEnabled()) {
log.tracef("[%s] Collected cache %s status %s", xid, cacheName, status);
}
switch (status) {
case ROLLED_BACK:
break;
case MARK_COMMIT:
case COMMITTED:
hasCommits = true; //this cache decided to commit?
break;
case ERROR:
hasErrors = true; //we failed to update this cache
break;
case PREPARED:
case ACTIVE:
case PREPARING:
case NO_TRANSACTION:
//this should happen!
hasErrors = true;
break;
case OK:
case MARK_ROLLBACK:
default:
cacheNames.add(cacheName); //ready to rollback.
break;
}
notifyCacheCollected();
}
@Override
<T> BiFunction<T, Throwable, Void> handler() {
//noinspection unchecked
return (BiFunction<T, Throwable, Void>) handler;
}
@Override
void sendReply() {
int xaCode = XAResource.XA_OK;
if (hasErrors) {
//exceptions...
xaCode = XAException.XAER_RMERR;
} else if (hasRollbacks && hasCommits) {
//some caches decide to commit and others decide to rollback.
xaCode = XAException.XA_HEURMIX;
} else if (hasCommits) {
//all caches involved decided to commit
xaCode = XAException.XA_HEURCOM;
}
if (log.isTraceEnabled()) {
log.tracef("[%s] Sending reply %s", xid, xaCode);
}
reply.accept(header, xaCode);
}
@Override
CacheRpcCommand buildRemoteCommand(Configuration configuration, CommandsFactory commandsFactory, TxState state) {
return commandsFactory.buildRollbackCommand(state.getGlobalTransaction());
}
@Override
CacheRpcCommand buildForwardCommand(ByteString cacheName, long timeout) {
return new ForwardRollbackCommand(cacheName, xid, timeout);
}
@Override
CompletionStage<Void> asyncCompleteLocalTransaction(AdvancedCache<?, ?> cache, long timeout) {
return blockingManager.runBlocking(() -> {
try {
rollbackLocalTransaction(cache, xid, timeout);
} catch (HeuristicMixedException e) {
hasCommits = true;
hasRollbacks = true;
} catch (Throwable t) {
hasErrors = true;
}
}, this);
}
}
| 5,299
| 32.544304
| 117
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/operation/CommitTransactionOperation.java
|
package org.infinispan.server.hotrod.tx.operation;
import static org.infinispan.server.hotrod.tx.operation.Util.commitLocalTransaction;
import java.util.concurrent.CompletionStage;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import javax.security.auth.Subject;
import jakarta.transaction.HeuristicCommitException;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import org.infinispan.AdvancedCache;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.Configurations;
import org.infinispan.server.hotrod.HotRodHeader;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.command.tx.ForwardCommitCommand;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.server.hotrod.tx.table.Status;
import org.infinispan.server.hotrod.tx.table.TxState;
import org.infinispan.transaction.LockingMode;
import org.infinispan.util.ByteString;
import org.infinispan.util.logging.LogFactory;
/**
* It commits a transaction in all involved caches.
*
* @author Pedro Ruivo
* @since 9.4
*/
public class CommitTransactionOperation extends BaseCompleteTransactionOperation {
private static final Log log = LogFactory.getLog(CommitTransactionOperation.class, Log.class);
//TODO check if this class can implement the BiFunction interface!
private final BiFunction<?, Throwable, Void> handler = (ignored, throwable) -> {
if (throwable != null) {
while (throwable != null) {
if (throwable instanceof HeuristicCommitException) {
hasCommits = true;
return null;
} else if (throwable instanceof HeuristicMixedException) {
hasCommits = true;
hasRollbacks = true;
return null;
} else if (throwable instanceof HeuristicRollbackException || throwable instanceof RollbackException) {
hasRollbacks = true;
return null;
}
throwable = throwable.getCause();
//TODO handle suspect/outdated topology exceptions
}
hasErrors = true;
} else {
hasCommits = true;
}
return null;
};
public CommitTransactionOperation(HotRodHeader header, HotRodServer server, Subject subject, XidImpl xid,
BiConsumer<HotRodHeader, Integer> reply) {
super(header, server, subject, xid, reply);
}
@Override
public void run() {
globalTxTable.markToCommit(xid, this);
}
@Override
public void addCache(ByteString cacheName, Status status) {
if (log.isTraceEnabled()) {
log.tracef("[%s] Collected cache %s status %s", xid, cacheName, status);
}
switch (status) {
case MARK_ROLLBACK:
case ROLLED_BACK:
hasRollbacks = true; //this cache decided to rollback. we can't change its state.
break;
case COMMITTED:
hasCommits = true; //this cache is already committed.
break;
case ERROR:
hasErrors = true; //we failed to update this cache
break;
case NO_TRANSACTION:
case PREPARING:
case ACTIVE:
case PREPARED:
//this shouldn't happen!
hasErrors = true;
break;
case MARK_COMMIT:
case OK:
default:
cacheNames.add(cacheName); //this cache is ready to commit!
break;
}
notifyCacheCollected();
}
<T> BiFunction<T, Throwable, Void> handler() {
//noinspection unchecked
return (BiFunction<T, Throwable, Void>) handler;
}
void sendReply() {
int xaCode = XAResource.XA_OK;
if (hasErrors) {
xaCode = XAException.XAER_RMERR;
} else if (hasCommits && hasRollbacks) {
xaCode = XAException.XA_HEURMIX;
} else if (hasRollbacks) {
//only rollbacks
xaCode = XAException.XA_HEURRB;
}
if (log.isTraceEnabled()) {
log.tracef("[%s] Sending reply %s", xid, xaCode);
}
reply.accept(header, xaCode);
}
@Override
CacheRpcCommand buildRemoteCommand(Configuration configuration, CommandsFactory commandsFactory, TxState state) {
if (configuration.transaction().lockingMode() == LockingMode.PESSIMISTIC) {
//pessimistic locking commits in 1PC
return commandsFactory.buildPrepareCommand(state.getGlobalTransaction(), state.getModifications(), true);
} else if (Configurations.isTxVersioned(configuration)) {
//TODO we don't support versioning yet (only used for optimistic tx). When we do, we need to store the versions in TxState.
return commandsFactory.buildVersionedCommitCommand(state.getGlobalTransaction());
} else {
return commandsFactory.buildCommitCommand(state.getGlobalTransaction());
}
}
@Override
CacheRpcCommand buildForwardCommand(ByteString cacheName, long timeout) {
return new ForwardCommitCommand(cacheName, xid, timeout);
}
@Override
CompletionStage<Void> asyncCompleteLocalTransaction(AdvancedCache<?, ?> cache, long timeout) {
return blockingManager.runBlocking(() -> {
try {
commitLocalTransaction(cache, xid, timeout);
} catch (HeuristicMixedException e) {
hasCommits = true;
hasRollbacks = true;
} catch (RollbackException | HeuristicRollbackException e) {
hasRollbacks = true;
} catch (Throwable t) {
hasErrors = true;
}
}, this);
}
}
| 5,937
| 34.556886
| 132
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/operation/BaseCompleteTransactionOperation.java
|
package org.infinispan.server.hotrod.tx.operation;
import static org.infinispan.remoting.transport.impl.VoidResponseCollector.validOnly;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import javax.security.auth.Subject;
import javax.transaction.xa.XAException;
import org.infinispan.AdvancedCache;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.hotrod.HotRodHeader;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.logging.Log;
import org.infinispan.server.hotrod.tx.table.CacheNameCollector;
import org.infinispan.server.hotrod.tx.table.CacheXid;
import org.infinispan.server.hotrod.tx.table.GlobalTxTable;
import org.infinispan.server.hotrod.tx.table.TxState;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.AggregateCompletionStage;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.LogFactory;
/**
* A base class to complete a transaction (commit or rollback).
* <p>
* This class implements {@link Runnable} in order to be executed in a {@link ExecutorService}.
* <p>
* A transaction completion occurs in the following steps:
*
* <ul>
* <li>Search and collects all the cache involved in the transaction</li>
* <li>Finds the transaction originator (i.e. the node that replayed the transaction)</li>
* <li>If it is an originator of one or more caches, it completes the transaction in another thread</li>
* <li>If the originator is not in the topology, it completes the transaction by broadcasting the respective command</li>
* <li>If the originator is in the topology, it forwards the completion request</li>
* </ul>
*
* @author Pedro Ruivo
* @since 9.4
*/
abstract class BaseCompleteTransactionOperation implements CacheNameCollector, Runnable {
private static final Log log = LogFactory.getLog(BaseCompleteTransactionOperation.class, Log.class);
final XidImpl xid;
final GlobalTxTable globalTxTable;
final HotRodHeader header;
final BiConsumer<HotRodHeader, Integer> reply;
private final HotRodServer server;
private final Subject subject;
final Collection<ByteString> cacheNames = new ConcurrentLinkedQueue<>();
final BlockingManager blockingManager;
private final AtomicInteger expectedCaches = new AtomicInteger();
volatile boolean hasErrors = false;
volatile boolean hasCommits = false;
volatile boolean hasRollbacks = false;
BaseCompleteTransactionOperation(HotRodHeader header, HotRodServer server, Subject subject, XidImpl xid,
BiConsumer<HotRodHeader, Integer> reply) {
GlobalComponentRegistry gcr = SecurityActions.getGlobalComponentRegistry(server.getCacheManager());
this.globalTxTable = gcr.getComponent(GlobalTxTable.class);
this.blockingManager = gcr.getComponent(BlockingManager.class);
this.header = header;
this.server = server;
this.subject = subject;
this.xid = xid;
this.reply = reply;
}
@Override
public final void expectedSize(int size) {
this.expectedCaches.set(size);
}
@Override
public final void noTransactionFound() {
if (log.isTraceEnabled()) {
log.tracef("[%s] No caches found.", xid);
}
//no transactions
reply.accept(header, XAException.XAER_NOTA);
}
/**
* It returns the handler to handle the replies from remote nodes or from a forward request.
* <p>
* It is invoked when this node isn't the originator for a cache. If the originator isn't in the view, it handles the
* replies from the broadcast commit or rollback command. If the originator is in the view, it handles the reply from
* the forward command.
*
* @return The {@link BiFunction} to handle the remote replies.
*/
abstract <T> BiFunction<T, Throwable, Void> handler();
/**
* When all caches are completed, this method is invoked to reply to the Hot Rod client.
*/
abstract void sendReply();
/**
* When the originator is not in the cache topology, this method builds the command to broadcast to all the nodes.
*
* @return The completion command to broadcast to nodes in the cluster.
*/
abstract CacheRpcCommand buildRemoteCommand(Configuration configuration, CommandsFactory commandsFactory,
TxState state);
/**
* When this node isn't the originator, it builds the forward command to send to the originator.
*
* @return The forward command to send to the originator.
*/
abstract CacheRpcCommand buildForwardCommand(ByteString cacheName, long timeout);
/**
* When this node is the originator, this method is invoked to complete the transaction in the specific cache.
*/
abstract CompletionStage<Void> asyncCompleteLocalTransaction(AdvancedCache<?, ?> cache, long timeout);
/**
* Invoked every time a cache is found to be involved in a transaction.
*/
void notifyCacheCollected() {
int result = expectedCaches.decrementAndGet();
if (log.isTraceEnabled()) {
log.tracef("[%s] Cache collected. Missing=%s.", xid, result);
}
if (result == 0) {
onCachesCollected();
}
}
/**
* Invoked when all caches are ready to complete the transaction.
*/
private void onCachesCollected() {
if (log.isTraceEnabled()) {
log.tracef("[%s] All caches collected: %s", xid, cacheNames);
}
int size = cacheNames.size();
if (size == 0) {
//it can happen if all caches either commit or thrown an exception
sendReply();
return;
}
AggregateCompletionStage<Void> aggregateCompletionStage = CompletionStages.aggregateCompletionStage();
for (ByteString cacheName : cacheNames) {
try {
aggregateCompletionStage.dependsOn(completeCache(cacheName));
} catch (Throwable t) {
hasErrors = true;
}
}
aggregateCompletionStage.freeze().thenRun(this::sendReply);
}
/**
* Completes the transaction for a specific cache.
*/
private CompletionStage<Void> completeCache(ByteString cacheName) throws Throwable {
TxState state = globalTxTable.getState(new CacheXid(cacheName, xid));
HotRodServer.ExtendedCacheInfo cacheInfo =
server.getCacheInfo(cacheName.toString(), header.getVersion(), header.getMessageId(), true);
AdvancedCache<?, ?> cache = server.cache(cacheInfo, header, subject);
RpcManager rpcManager = cache.getRpcManager();
if (rpcManager == null || rpcManager.getAddress().equals(state.getOriginator())) {
if (log.isTraceEnabled()) {
log.tracef("[%s] Completing local executed transaction.", xid);
}
return asyncCompleteLocalTransaction(cache, state.getTimeout());
} else if (rpcManager.getMembers().contains(state.getOriginator())) {
if (log.isTraceEnabled()) {
log.tracef("[%s] Forward remotely executed transaction to %s.", xid, state.getOriginator());
}
return forwardCompleteCommand(cacheName, rpcManager, state);
} else {
if (log.isTraceEnabled()) {
log.tracef("[%s] Originator, %s, left the cluster.", xid, state.getOriginator());
}
return completeWithRemoteCommand(cache, rpcManager, state);
}
}
/**
* Completes the transaction in the cache when the originator no longer belongs to the cache topology.
*/
private CompletableFuture<Void> completeWithRemoteCommand(AdvancedCache<?, ?> cache, RpcManager rpcManager,
TxState state)
throws Throwable {
CommandsFactory commandsFactory = SecurityActions.getCacheComponentRegistry(cache).getCommandsFactory();
CacheRpcCommand command = buildRemoteCommand(cache.getCacheConfiguration(), commandsFactory, state);
CompletableFuture<Void> remote = rpcManager
.invokeCommandOnAll(command, validOnly(), rpcManager.getSyncRpcOptions())
.handle(handler())
.toCompletableFuture();
CompletableFuture<Void> local = command.invokeAsync(cache.getComponentRegistry()).handle(handler()).toCompletableFuture();
return CompletableFuture.allOf(remote, local);
}
/**
* Completes the transaction in the cache when the originator is still in the cache topology.
*/
private CompletableFuture<Void> forwardCompleteCommand(ByteString cacheName, RpcManager rpcManager,
TxState state) {
//TODO what if the originator crashes in the meanwhile?
//actually, the reaper would rollback the transaction later...
Address originator = state.getOriginator();
CacheRpcCommand command = buildForwardCommand(cacheName, state.getTimeout());
return rpcManager.invokeCommand(originator, command, validOnly(), rpcManager.getSyncRpcOptions())
.handle(handler())
.toCompletableFuture();
}
}
| 9,624
| 40.487069
| 128
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/operation/Util.java
|
package org.infinispan.server.hotrod.tx.operation;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.server.hotrod.tx.table.CacheXid;
import org.infinispan.server.hotrod.tx.table.GlobalTxTable;
import org.infinispan.server.hotrod.tx.table.PerCacheTxTable;
import org.infinispan.server.hotrod.tx.table.functions.SetCompletedTransactionFunction;
import org.infinispan.server.hotrod.tx.table.functions.TxFunction;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.util.ByteString;
/**
* Util operations to handle client transactions in Hot Rod server.
*
* @author Pedro Ruivo
* @since 9.4
*/
public class Util {
public static void rollbackLocalTransaction(AdvancedCache<?, ?> cache, XidImpl xid, long timeout)
throws HeuristicRollbackException, HeuristicMixedException {
try {
completeLocalTransaction(cache, xid, timeout, false);
} catch (RollbackException e) {
//ignored since it is always thrown.
}
}
public static void commitLocalTransaction(AdvancedCache<?, ?> cache, XidImpl xid, long timeout)
throws HeuristicRollbackException, HeuristicMixedException, RollbackException {
completeLocalTransaction(cache, xid, timeout, true);
}
private static void completeLocalTransaction(AdvancedCache<?, ?> cache, XidImpl xid, long timeout, boolean commit)
throws HeuristicRollbackException, HeuristicMixedException, RollbackException {
PerCacheTxTable perCacheTxTable = cache.getComponentRegistry().getComponent(PerCacheTxTable.class);
GlobalTxTable globalTxTable = cache.getComponentRegistry().getGlobalComponentRegistry()
.getComponent(GlobalTxTable.class);
try {
//local transaction
EmbeddedTransaction tx = perCacheTxTable.getLocalTx(xid);
tx.runCommit(!commit);
CacheXid cacheXid = new CacheXid(ByteString.fromString(cache.getName()), xid);
TxFunction function = new SetCompletedTransactionFunction(commit);
globalTxTable.update(cacheXid, function, timeout);
} finally {
perCacheTxTable.removeLocalTx(xid);
}
}
}
| 2,347
| 40.192982
| 117
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/event/KeyValueWithPreviousEventConverterExternalizer.java
|
package org.infinispan.server.hotrod.event;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Set;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.commons.util.Util;
/**
* Externalizer for KeyValueWithPreviousEventConverter
*
* @author gustavonalle
* @since 7.2
*/
public class KeyValueWithPreviousEventConverterExternalizer extends AbstractExternalizer<KeyValueWithPreviousEventConverter> {
@Override
public Set<Class<? extends KeyValueWithPreviousEventConverter>> getTypeClasses() {
return Util.asSet(KeyValueWithPreviousEventConverter.class);
}
@Override
public void writeObject(ObjectOutput output, KeyValueWithPreviousEventConverter object) throws IOException {
}
@Override
public KeyValueWithPreviousEventConverter readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new KeyValueWithPreviousEventConverter();
}
}
| 985
| 29.8125
| 126
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/event/KeyValueWithPreviousEventConverter.java
|
package org.infinispan.server.hotrod.event;
import org.infinispan.commons.util.KeyValueWithPrevious;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.EventType;
public class KeyValueWithPreviousEventConverter<K, V> implements CacheEventConverter<K, V, KeyValueWithPrevious<K, V>> {
@Override
public KeyValueWithPrevious<K, V> convert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) {
return new KeyValueWithPrevious<K, V>(key, newValue, oldValue);
}
}
| 644
| 45.071429
| 142
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/event/KeyValueWithPreviousEventConverterFactory.java
|
package org.infinispan.server.hotrod.event;
import org.infinispan.commons.util.KeyValueWithPrevious;
import org.infinispan.filter.NamedFactory;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory;
@NamedFactory(name = "key-value-with-previous-converter-factory")
public class KeyValueWithPreviousEventConverterFactory<K, V> implements CacheEventConverterFactory {
private final KeyValueWithPreviousEventConverter<K, V> converter = new KeyValueWithPreviousEventConverter<K, V>();
@Override
public CacheEventConverter<K, V, KeyValueWithPrevious<K, V>> getConverter(Object[] params) {
return converter;
}
}
| 735
| 42.294118
| 117
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/tracing/HotRodTelemetryService.java
|
package org.infinispan.server.hotrod.tracing;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.infinispan.server.core.telemetry.TelemetryService;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.context.propagation.TextMapGetter;
public class HotRodTelemetryService {
private static final TextMapGetter<Map<String, byte[]>> MAP_TEXT_MAP_GETTER =
new TextMapGetter<>() {
@Override
public String get(Map<String, byte[]> carrier, String key) {
byte[] bytes = carrier.get(key);
if (bytes == null) {
return null;
}
return new String(bytes, StandardCharsets.UTF_8);
}
@Override
public Iterable<String> keys(Map<String, byte[]> carrier) {
return carrier.keySet();
}
};
private final TelemetryService telemetryService;
public HotRodTelemetryService(TelemetryService telemetryService) {
this.telemetryService = telemetryService;
}
public Span requestStart(String operationName, Map<String, byte[]> otherParams) {
return telemetryService.requestStart(operationName, MAP_TEXT_MAP_GETTER, otherParams);
}
public void requestEnd(Object span) {
telemetryService.requestEnd(span);
}
public void recordException(Object span, Throwable throwable) {
telemetryService.recordException(span, throwable);
}
}
| 1,477
| 29.163265
| 92
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/transport/ExtendedByteBuf.java
|
package org.infinispan.server.hotrod.transport;
import java.nio.ByteBuffer;
import java.util.Optional;
import org.infinispan.commons.io.SignedNumeric;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.commons.util.Util;
import org.infinispan.server.core.transport.VInt;
import org.infinispan.server.core.transport.VLong;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
public class ExtendedByteBuf {
public static ByteBuf wrappedBuffer(byte[]... arrays) {
return Unpooled.wrappedBuffer(arrays);
}
public static ByteBuf buffer(int capacity) {
return Unpooled.buffer(capacity);
}
public static ByteBuf dynamicBuffer() {
return Unpooled.buffer();
}
public static int readUnsignedShort(ByteBuf bf) {
return bf.readUnsignedShort();
}
public static int readUnsignedInt(ByteBuf bf) {
return VInt.read(bf);
}
public static long readUnsignedLong(ByteBuf bf) {
return VLong.read(bf);
}
public static byte[] readRangedBytes(ByteBuf bf) {
int length = readUnsignedInt(bf);
return readRangedBytes(bf, length);
}
public static byte[] readRangedBytes(ByteBuf bf, int length) {
if (length > 0) {
byte[] array = new byte[length];
bf.readBytes(array);
return array;
} else {
return Util.EMPTY_BYTE_ARRAY;
}
}
/**
* Reads optional range of bytes. Negative lengths are translated to None, 0 length represents empty Array
*/
public static Optional<byte[]> readOptRangedBytes(ByteBuf bf) {
int length = SignedNumeric.decode(readUnsignedInt(bf));
return length < 0 ? Optional.empty() : Optional.of(readRangedBytes(bf, length));
}
/**
* Reads an optional String. 0 length is an empty string, negative length is translated to None.
*/
public static Optional<String> readOptString(ByteBuf bf) {
Optional<byte[]> bytes = readOptRangedBytes(bf);
return bytes.map(b -> new String(b, CharsetUtil.UTF_8));
}
/**
* Reads length of String and then returns an UTF-8 formatted String of such length. If the length is 0, an empty
* String is returned.
*/
public static String readString(ByteBuf bf) {
byte[] bytes = readRangedBytes(bf);
return bytes.length > 0 ? new String(bytes, CharsetUtil.UTF_8) : "";
}
/**
* Reads a byte if possible. If not present the reader index is reset to the last mark.
*
* @param bf
* @return
*/
public static Optional<Byte> readMaybeByte(ByteBuf bf) {
if (bf.readableBytes() >= 1) {
return Optional.of(bf.readByte());
} else {
bf.resetReaderIndex();
return Optional.empty();
}
}
public static Optional<Long> readMaybeLong(ByteBuf bf) {
if (bf.readableBytes() < 8) {
bf.resetReaderIndex();
return Optional.empty();
} else {
return Optional.of(bf.readLong());
}
}
/**
* Reads a variable long if possible. If not present the reader index is reset to the last mark.
*
* @param bf
* @return
*/
public static Optional<Long> readMaybeVLong(ByteBuf bf) {
if (bf.readableBytes() >= 1) {
byte b = bf.readByte();
return read(bf, b, 7, (long) b & 0x7F, 1);
} else {
bf.resetReaderIndex();
return Optional.empty();
}
}
private static Optional<Long> read(ByteBuf buf, byte b, int shift, long i, int count) {
if ((b & 0x80) == 0) return Optional.of(i);
else {
if (count > 9)
throw new IllegalStateException(
"Stream corrupted. A variable length long cannot be longer than 9 bytes.");
if (buf.readableBytes() >= 1) {
byte bb = buf.readByte();
return read(buf, bb, shift + 7, i | (bb & 0x7FL) << shift, count + 1);
} else {
buf.resetReaderIndex();
return Optional.empty();
}
}
}
/**
* Reads a variable size int if possible. If not present the reader index is reset to the last mark.
*
* @param bf
* @return
*/
public static Optional<Integer> readMaybeVInt(ByteBuf bf) {
if (bf.readableBytes() >= 1) {
byte b = bf.readByte();
return read(bf, b, 7, b & 0x7F, 1);
} else {
bf.resetReaderIndex();
return Optional.empty();
}
}
private static Optional<Integer> read(ByteBuf buf, byte b, int shift, int i, int count) {
if ((b & 0x80) == 0) return Optional.of(i);
else {
if (count > 5)
throw new IllegalStateException(
"Stream corrupted. A variable length integer cannot be longer than 5 bytes.");
if (buf.readableBytes() >= 1) {
byte bb = buf.readByte();
return read(buf, bb, shift + 7, i | (int) ((bb & 0x7FL) << shift), count + 1);
} else {
buf.resetReaderIndex();
return Optional.empty();
}
}
}
/**
* Reads a range of bytes if possible. If not present the reader index is reset to the last mark.
*
* @param bf
* @return
*/
public static Optional<byte[]> readMaybeRangedBytes(ByteBuf bf) {
Optional<Integer> length = readMaybeVInt(bf);
if (length.isPresent()) {
int l = length.get();
if (bf.readableBytes() >= l) {
if (l > 0) {
byte[] array = new byte[l];
bf.readBytes(array);
return Optional.of(array);
} else {
return Optional.of(Util.EMPTY_BYTE_ARRAY);
}
} else {
bf.resetReaderIndex();
return Optional.empty();
}
} else return Optional.empty();
}
public static Optional<byte[]> readMaybeRangedBytes(ByteBuf bf, int length) {
if (bf.readableBytes() < length) {
bf.resetReaderIndex();
return Optional.empty();
} else {
byte[] bytes = new byte[length];
bf.readBytes(bytes);
return Optional.of(bytes);
}
}
public static Optional<Integer> readMaybeSignedInt(ByteBuf bf) {
return readMaybeVInt(bf).map(SignedNumeric::decode);
}
/**
* Read a range of bytes prefixed by its length (encoded as a signed VInt).
*
* @return {@code Optional(Optional(byte[])} if it could read the range,
* {@code Optional(Optional.empty())} if the length was negative,
* or {@code Optional.empty()} if the input buffer didn't contain the entire range.
*/
public static Optional<Optional<byte[]>> readMaybeOptRangedBytes(ByteBuf bf) {
Optional<Integer> l = readMaybeSignedInt(bf);
if (l.isPresent()) {
int length = l.get();
if (length < 0) {
return Optional.of(Optional.empty());
} else {
Optional<byte[]> rb = readMaybeRangedBytes(bf, length);
if (rb.isPresent()) {
return Optional.of(rb);
} else {
return Optional.empty();
}
}
} else {
return Optional.empty();
}
}
/**
* Reads a string if possible. If not present the reader index is reset to the last mark.
*
* @param bf
* @return
*/
public static Optional<String> readMaybeString(ByteBuf bf) {
Optional<byte[]> bytes = readMaybeRangedBytes(bf);
return bytes.map(b -> {
if (b.length == 0) return "";
else return new String(b, CharsetUtil.UTF_8);
});
}
public static Optional<Optional<String>> readMaybeOptString(ByteBuf bf) {
return readMaybeOptRangedBytes(bf).map(optionalBytes -> optionalBytes.map(
bytes -> {
if (bytes.length == 0) return "";
else return new String(bytes, CharsetUtil.UTF_8);
}));
}
public static void writeUnsignedShort(int i, ByteBuf bf) {
bf.writeShort(i);
}
public static void writeUnsignedInt(int i, ByteBuf bf) {
VInt.write(bf, i);
}
public static void writeUnsignedLong(long l, ByteBuf bf) {
VLong.write(bf, l);
}
public static void writeRangedBytes(byte[] src, ByteBuf bf) {
writeUnsignedInt(src.length, bf);
if (src.length > 0)
bf.writeBytes(src);
}
public static void writeRangedBytes(byte[] src, int offset, ByteBuf bf) {
int l = src.length - offset;
writeUnsignedInt(l, bf);
if (l > 0)
bf.writeBytes(src);
}
public static void writeRangedBytes(ByteBuffer src, ByteBuf bf) {
writeUnsignedInt(src.remaining(), bf);
bf.writeBytes(src);
}
public static void writeString(String msg, ByteBuf bf) {
writeRangedBytes(msg.getBytes(CharsetUtil.UTF_8), bf);
}
public static void writeString(Optional<String> msg, ByteBuf bf) {
writeRangedBytes(msg.map(m -> m.getBytes(CharsetUtil.UTF_8)).orElse(Util.EMPTY_BYTE_ARRAY), bf);
}
public static void writeXid(XidImpl xid, ByteBuf buffer) {
VInt.write(buffer, SignedNumeric.encode(xid.getFormatId()));
//avoid allocating/copying arrays
writeRangedBytes(xid.getGlobalTransactionIdAsByteBuffer(), buffer);
writeRangedBytes(xid.getBranchQualifierAsByteBuffer(), buffer);
}
}
| 9,330
| 29.593443
| 116
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/transport/TimeoutEnabledChannelInitializer.java
|
package org.infinispan.server.hotrod.transport;
import org.infinispan.server.core.ProtocolServer;
import org.infinispan.server.core.configuration.ProtocolServerConfiguration;
import org.infinispan.server.core.transport.IdleStateHandlerProvider;
import org.infinispan.server.core.transport.NettyInitializer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.IdleStateHandler;
/**
* A channel pipeline factory for environments where idle timeout is enabled. This is a trait, useful to extend by an
* implementation channel initializer.
*
* @author Galder Zamarreño
* @author William Burns
* @since 5.1
*/
public class TimeoutEnabledChannelInitializer<C extends ProtocolServerConfiguration> implements NettyInitializer {
private final ProtocolServer<C> hotRodServer;
public TimeoutEnabledChannelInitializer(ProtocolServer<C> hotRodServer) {
this.hotRodServer = hotRodServer;
}
@Override
public void initializeChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("idleHandler", new IdleStateHandler(hotRodServer.getConfiguration().idleTimeout(), 0, 0));
pipeline.addLast("idleHandlerProvider", new IdleStateHandlerProvider());
}
}
| 1,283
| 36.764706
| 118
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/counter/listener/ListenerOperationStatus.java
|
package org.infinispan.server.hotrod.counter.listener;
/**
* The listener operation (add/remove) return status.
*
* @author Pedro Ruivo
* @since 9.2
*/
public enum ListenerOperationStatus {
/**
* The operation is completed and it will use (or remove) the channel.
*/
OK_AND_CHANNEL_IN_USE,
/**
* The counter wasn't found.
*/
COUNTER_NOT_FOUND,
/**
* The operation is completed but it won't use the channel used in the request.
*/
OK
}
| 483
| 20.043478
| 82
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/counter/listener/ClientCounterManagerNotificationManager.java
|
package org.infinispan.server.hotrod.counter.listener;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.infinispan.commons.marshall.WrappedByteArray;
import org.infinispan.commons.util.ByRef;
import org.infinispan.counter.api.CounterManager;
import org.infinispan.server.hotrod.VersionedEncoder;
import io.netty.channel.Channel;
/**
* The {@link CounterManager} notification manager.
* <p>
* For each client, it associates a {@link ClientNotificationManager} to handle that particular client requests.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class ClientCounterManagerNotificationManager {
private final CounterManager counterManager;
private final Map<WrappedByteArray, ClientNotificationManager> clientManagers;
public ClientCounterManagerNotificationManager(CounterManager counterManager) {
this.counterManager = counterManager;
clientManagers = new ConcurrentHashMap<>();
}
private static WrappedByteArray wrapId(byte[] id) {
return new WrappedByteArray(id);
}
public void stop() {
clientManagers.values().forEach(ClientNotificationManager::removeAll);
clientManagers.clear();
}
public ListenerOperationStatus addCounterListener(byte[] listenerId, byte version,
String counterName, Channel channel, VersionedEncoder encoder) {
ByRef<ListenerOperationStatus> status = new ByRef<>(ListenerOperationStatus.COUNTER_NOT_FOUND);
clientManagers
.compute(wrapId(listenerId), (id, manager) -> add(id, manager, version, counterName, channel, encoder, status));
return status.get();
}
public ListenerOperationStatus removeCounterListener(byte[] listenerId, String counterName) {
ByRef<ListenerOperationStatus> status = new ByRef<>(ListenerOperationStatus.COUNTER_NOT_FOUND);
clientManagers.computeIfPresent(wrapId(listenerId), (id, manager) -> rm(manager, counterName, status));
return status.get();
}
public void channelActive(Channel channel) {
channel.eventLoop().execute(() -> clientManagers.values().forEach(manager -> manager.channelActive(channel)));
}
private ClientNotificationManager add(WrappedByteArray id, ClientNotificationManager manager, byte version,
String counterName, Channel channel, VersionedEncoder encoder, ByRef<ListenerOperationStatus> status) {
boolean useChannel = false;
if (manager == null) {
manager = new ClientNotificationManager(id.getBytes(), counterManager, channel, encoder);
useChannel = true;
}
if (manager.addCounterListener(version, counterName)) {
status.set(useChannel ? ListenerOperationStatus.OK_AND_CHANNEL_IN_USE : ListenerOperationStatus.OK);
return manager;
} else {
status.set(ListenerOperationStatus.COUNTER_NOT_FOUND);
return null;
}
}
private ClientNotificationManager rm(ClientNotificationManager manager, String counterName,
ByRef<ListenerOperationStatus> status) {
if (counterName.isEmpty()) {
manager.removeAll();
} else {
manager.removeCounterListener(counterName);
}
if (manager.isEmpty()) {
status.set(ListenerOperationStatus.OK_AND_CHANNEL_IN_USE);
return null;
} else {
status.set(ListenerOperationStatus.OK);
return manager;
}
}
}
| 3,466
| 37.522222
| 144
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/counter/listener/ClientNotificationManager.java
|
package org.infinispan.server.hotrod.counter.listener;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.util.ByRef;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterEvent;
import org.infinispan.counter.api.CounterListener;
import org.infinispan.counter.api.CounterManager;
import org.infinispan.counter.api.CounterType;
import org.infinispan.counter.api.Handle;
import org.infinispan.server.hotrod.VersionedEncoder;
import org.infinispan.server.hotrod.logging.Log;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
/**
* A client notification manager.
* <p>
* A client is identified by its {@code listener-id} and it uses the same channel to send all the counter related
* events. The client can use the same {@code listener-id} for all its requests.
* <p>
* It only register a single listener for each counter. So, if multiple requests are received for the same counter, only
* one will succeed.
*
* @author Pedro Ruivo
* @since 9.2
*/
class ClientNotificationManager {
private static final Log log = LogFactory.getLog(ClientNotificationManager.class, Log.class);
private final Map<String, Handle<Listener>> counterListener;
private final CounterManager counterManager;
private final Channel channel;
private final VersionedEncoder encoder;
private final Queue<ClientCounterEvent> eventQueue;
private final byte[] listenerId;
ClientNotificationManager(byte[] listenerId, CounterManager counterManager, Channel channel, VersionedEncoder encoder) {
this.listenerId = listenerId;
this.counterManager = counterManager;
this.channel = channel;
this.encoder = encoder;
counterListener = new ConcurrentHashMap<>();
eventQueue = new ConcurrentLinkedQueue<>();
}
boolean addCounterListener(byte version, String counterName) {
if (log.isTraceEnabled()) {
log.tracef("Add listener for counter '%s'", counterName);
}
ByRef<Boolean> status = new ByRef<>(true);
counterListener.computeIfAbsent(counterName, name -> createListener(version, name, status));
return status.get();
}
void removeCounterListener(String counterName) {
if (log.isTraceEnabled()) {
log.tracef("Remove listener for counter '%s'", counterName);
}
counterListener.computeIfPresent(counterName, (name, handle) -> {
handle.remove();
return null;
});
}
boolean isEmpty() {
return counterListener.isEmpty();
}
void removeAll() {
if (log.isTraceEnabled()) {
log.trace("Remove all listeners");
}
counterListener.values().forEach(Handle::remove);
counterListener.clear();
}
void channelActive(Channel otherChannel) {
boolean sameChannel = this.channel == otherChannel;
if (log.isTraceEnabled()) {
log.tracef("Channel active! is same channel? %s", sameChannel);
}
if (sameChannel) {
sendEvents();
}
}
private void sendEvents() {
if (log.isTraceEnabled()) {
log.tracef("Send events! is writable? %s", channel.isWritable());
}
ClientCounterEvent event;
boolean written = false;
while (channel.isWritable() && (event = eventQueue.poll()) != null) {
if (log.isTraceEnabled()) {
log.tracef("Sending event %s", event);
}
ByteBuf buf = channel.alloc().ioBuffer();
encoder.writeCounterEvent(event, buf);
channel.write(buf);
written = true;
}
if (written) {
channel.flush();
}
}
private Handle<Listener> createListener(byte version, String counterName, ByRef<Boolean> status) {
CounterConfiguration configuration = counterManager.getConfiguration(counterName);
if (configuration == null) {
status.set(false);
return null;
}
Handle<Listener> handle;
if (configuration.type() == CounterType.WEAK) {
handle = counterManager.getWeakCounter(counterName).addListener(new Listener(counterName, version));
} else {
handle = counterManager.getStrongCounter(counterName).addListener(new Listener(counterName, version));
}
status.set(true);
return handle;
}
private void trySendEvents() {
boolean writable = channel.isWritable();
if (log.isTraceEnabled()) {
log.tracef("Try to send events after notification. is writable? %s", writable);
}
if (channel.isWritable()) {
channel.eventLoop().execute(this::sendEvents);
}
}
private class Listener implements CounterListener {
private final String counterName;
private final byte version;
private Listener(String counterName, byte version) {
this.counterName = counterName;
this.version = version;
}
@Override
public void onUpdate(CounterEvent entry) {
if (log.isTraceEnabled()) {
log.tracef("Event received! %s", entry);
}
eventQueue.add(new ClientCounterEvent(listenerId, version, counterName, entry));
trySendEvents();
}
}
}
| 5,341
| 32.180124
| 123
|
java
|
null |
infinispan-main/server/hotrod/src/main/java/org/infinispan/server/hotrod/counter/listener/ClientCounterEvent.java
|
package org.infinispan.server.hotrod.counter.listener;
import org.infinispan.commons.util.Util;
import org.infinispan.counter.api.CounterEvent;
import org.infinispan.counter.api.CounterState;
import org.infinispan.server.hotrod.transport.ExtendedByteBuf;
import io.netty.buffer.ByteBuf;
/**
* A counter event to send to a client.
*
* @author Pedro Ruivo
* @since 9.2
*/
public final class ClientCounterEvent {
private final String counterName;
private final CounterEvent event;
private final byte version;
private final byte[] listenerId;
ClientCounterEvent(byte[] listenerId, byte version, String counterName, CounterEvent event) {
this.version = version;
this.counterName = counterName;
this.event = event;
this.listenerId = listenerId;
}
public static CounterState decodeOldState(byte 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();
}
}
public static CounterState decodeNewState(byte 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();
}
}
public byte getVersion() {
return version;
}
public void writeTo(ByteBuf buffer) {
ExtendedByteBuf.writeString(counterName, buffer);
ExtendedByteBuf.writeRangedBytes(listenerId, buffer);
buffer.writeByte(encodeCounterStates());
buffer.writeLong(event.getOldValue());
buffer.writeLong(event.getNewValue());
}
@Override
public String toString() {
return "ClientCounterEvent{" +
"counterName='" + counterName + '\'' +
", event=" + event +
", version=" + version +
", listenerId=" + Util.printArray(listenerId) +
'}';
}
/*
----|00|00
| ^ old state: 0 = valid, 1 = lower, 2 = upper
^----new state: 0 = valid, 4 = lower, 8 = upper
*/
private int encodeCounterStates() {
byte encoded = 0;
switch (event.getOldState()) {
case LOWER_BOUND_REACHED:
encoded = 0x01;
break;
case UPPER_BOUND_REACHED:
encoded = 0x02;
break;
case VALID:
default:
break;
}
switch (event.getNewState()) {
case LOWER_BOUND_REACHED:
encoded |= 0x04;
break;
case UPPER_BOUND_REACHED:
encoded |= 0x08;
break;
case VALID:
default:
break;
}
return encoded;
}
}
| 2,968
| 25.990909
| 96
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.