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/core/src/main/java/org/infinispan/remoting/responses/ExceptionResponse.java
|
package org.infinispan.remoting.responses;
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;
import org.infinispan.marshall.core.Ids;
/**
* A response that encapsulates an exception
*
* @author Manik Surtani
* @since 4.0
*/
public class ExceptionResponse extends InvalidResponse {
private Exception exception;
public ExceptionResponse() {
}
public ExceptionResponse(Exception exception) {
this.exception = exception;
}
public Exception getException() {
return exception;
}
public void setException(Exception exception) {
this.exception = exception;
}
@Override
public String toString() {
return "ExceptionResponse(" + exception + ")";
}
public static class Externalizer extends AbstractExternalizer<ExceptionResponse> {
@Override
public void writeObject(ObjectOutput output, ExceptionResponse response) throws IOException {
output.writeObject(response.exception);
}
@Override
public ExceptionResponse readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new ExceptionResponse((Exception) input.readObject());
}
@Override
public Integer getId() {
return Ids.EXCEPTION_RESPONSE;
}
@Override
public Set<Class<? extends ExceptionResponse>> getTypeClasses() {
return Util.<Class<? extends ExceptionResponse>>asSet(ExceptionResponse.class);
}
}
}
| 1,620
| 24.730159
| 105
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/responses/IgnoreExtraResponsesValidityFilter.java
|
package org.infinispan.remoting.responses;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.infinispan.remoting.rpc.ResponseFilter;
import org.infinispan.remoting.transport.Address;
/**
* A filter that only expects responses from an initial set of targets.
*
* Useful when sending a command to {@code null} to ensure we don't wait for responses from
* cluster members that weren't properly started when the command was sent.
*
* JGroups calls our handler while holding a lock, so we don't need any synchronization.
*
* @author Dan Berindei <dan@infinispan.org>
* @since 5.1
*/
public final class IgnoreExtraResponsesValidityFilter implements ResponseFilter {
private final Set<Address> targets;
private int missingResponses;
public IgnoreExtraResponsesValidityFilter(Collection<Address> targets, Address self, boolean removeSelf) {
this.targets = new HashSet<Address>(targets);
this.missingResponses = targets.size();
if (removeSelf && this.targets.contains(self)) {
missingResponses--;
}
}
@Override
public boolean isAcceptable(Response response, Address address) {
if (targets.contains(address)) {
missingResponses--;
}
// always return true to make sure a response is logged by the JGroups RpcDispatcher.
return true;
}
@Override
public boolean needMoreResponses() {
return missingResponses > 0;
}
}
| 1,469
| 28.4
| 109
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/responses/Response.java
|
package org.infinispan.remoting.responses;
/**
* A response to be sent back to a remote caller
*
* @author Manik Surtani
* @since 4.0
*/
public interface Response {
boolean isSuccessful();
boolean isValid();
}
| 224
| 14
| 48
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/responses/CacheNotFoundResponse.java
|
package org.infinispan.remoting.responses;
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;
import org.infinispan.marshall.core.Ids;
/**
* A response that signals the named cache is not running on the target node.
*
* @author Dan Berindei
* @since 6.0
*/
public class CacheNotFoundResponse extends InvalidResponse {
public static final CacheNotFoundResponse INSTANCE = new CacheNotFoundResponse();
private CacheNotFoundResponse() {
}
public static class Externalizer extends AbstractExternalizer<CacheNotFoundResponse> {
@Override
public void writeObject(ObjectOutput output, CacheNotFoundResponse response) throws IOException {
}
@Override
public CacheNotFoundResponse readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return INSTANCE;
}
@Override
public Integer getId() {
return Ids.CACHE_NOT_FOUND_RESPONSE;
}
@Override
public Set<Class<? extends CacheNotFoundResponse>> getTypeClasses() {
return Util.<Class<? extends CacheNotFoundResponse>>asSet(CacheNotFoundResponse.class);
}
}
}
| 1,299
| 27.888889
| 109
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/responses/ValidResponse.java
|
package org.infinispan.remoting.responses;
/**
* A valid response
*
* @author manik
* @since 4.0
*/
public abstract class ValidResponse implements Response {
@Override
public boolean isValid() {
return true;
}
public abstract Object getResponseValue();
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| 371
| 15.173913
| 57
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/responses/PrepareResponse.java
|
package org.infinispan.remoting.responses;
import static org.infinispan.commons.marshall.MarshallUtil.marshallMap;
import static org.infinispan.commons.marshall.MarshallUtil.unmarshallMap;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.container.versioning.IncrementableEntryVersion;
import org.infinispan.marshall.core.Ids;
import org.infinispan.metadata.impl.IracMetadata;
import org.infinispan.transaction.impl.WriteSkewHelper;
/**
* A {@link ValidResponse} used by Optimistic Transactions.
* <p>
* It contains the new {@link IncrementableEntryVersion} for each key updated.
* <p>
* To be extended in the future.
*
* @author Pedro Ruivo
* @since 11.0
*/
public class PrepareResponse extends ValidResponse {
public static final Externalizer EXTERNALIZER = new Externalizer();
private Map<Object, IncrementableEntryVersion> newWriteSkewVersions;
private Map<Integer, IracMetadata> newIracMetadata;
public static void writeTo(PrepareResponse response, ObjectOutput output) throws IOException {
marshallMap(response.newWriteSkewVersions, output);
marshallMap(response.newIracMetadata, DataOutput::writeInt, IracMetadata::writeTo, output);
}
public static PrepareResponse readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
PrepareResponse response = new PrepareResponse();
response.newWriteSkewVersions = unmarshallMap(input, HashMap::new);
response.newIracMetadata = unmarshallMap(input, DataInput::readInt, IracMetadata::readFrom, HashMap::new);
return response;
}
public static PrepareResponse asPrepareResponse(Object rv) {
assert rv == null || rv instanceof PrepareResponse;
return rv == null ? new PrepareResponse() : (PrepareResponse) rv;
}
@Override
public boolean isSuccessful() {
return true;
}
@Override
public Object getResponseValue() {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return "PrepareResponse{" +
"WriteSkewVersions=" + newWriteSkewVersions +
", IracMetadataMap=" + newIracMetadata +
'}';
}
public IracMetadata getIracMetadata(int segment) {
return newIracMetadata != null ? newIracMetadata.get(segment) : null;
}
public void setNewIracMetadata(Map<Integer, IracMetadata> map) {
this.newIracMetadata = map;
}
public void merge(PrepareResponse remote) {
if (remote.newWriteSkewVersions != null) {
mergeEntryVersions(remote.newWriteSkewVersions);
}
if (remote.newIracMetadata != null) {
if (newIracMetadata == null) {
newIracMetadata = new HashMap<>(remote.newIracMetadata);
} else {
newIracMetadata.putAll(remote.newIracMetadata);
}
}
}
public Map<Object, IncrementableEntryVersion> mergeEntryVersions(Map<Object, IncrementableEntryVersion> entryVersions) {
if (newWriteSkewVersions == null) {
newWriteSkewVersions = new HashMap<>();
}
newWriteSkewVersions = WriteSkewHelper.mergeEntryVersions(newWriteSkewVersions, entryVersions);
return newWriteSkewVersions;
}
private static class Externalizer extends AbstractExternalizer<PrepareResponse> {
@Override
public Integer getId() {
return Ids.PREPARE_RESPONSE;
}
@Override
public Set<Class<? extends PrepareResponse>> getTypeClasses() {
return Collections.singleton(PrepareResponse.class);
}
@Override
public void writeObject(ObjectOutput output, PrepareResponse object) throws IOException {
writeTo(object, output);
}
@Override
public PrepareResponse readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return readFrom(input);
}
}
}
| 4,118
| 31.433071
| 123
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/responses/UnsuccessfulResponse.java
|
package org.infinispan.remoting.responses;
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;
import org.infinispan.marshall.core.Ids;
/**
* An unsuccessful response
*
* @author Manik Surtani
* @since 4.0
*/
public class UnsuccessfulResponse extends ValidResponse {
public static final UnsuccessfulResponse EMPTY = new UnsuccessfulResponse(null);
private final Object responseValue;
private UnsuccessfulResponse(Object value) {
this.responseValue = value;
}
public static UnsuccessfulResponse create(Object value) {
return value == null ? EMPTY : new UnsuccessfulResponse(value);
}
@Override
public boolean isSuccessful() {
return false;
}
public Object getResponseValue() {
return responseValue;
}
@Override
public String toString() {
return "UnsuccessfulResponse{responseValue=" + Util.toStr(responseValue) + "} ";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UnsuccessfulResponse that = (UnsuccessfulResponse) o;
if (responseValue != null ? !responseValue.equals(that.responseValue) : that.responseValue != null) return false;
return true;
}
@Override
public int hashCode() {
return responseValue != null ? responseValue.hashCode() : 0;
}
public static class Externalizer extends AbstractExternalizer<UnsuccessfulResponse> {
@Override
public void writeObject(ObjectOutput output, UnsuccessfulResponse response) throws IOException {
output.writeObject(response.getResponseValue());
}
@Override
public UnsuccessfulResponse readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return create(input.readObject());
}
@Override
public Integer getId() {
return Ids.UNSUCCESSFUL_RESPONSE;
}
@Override
public Set<Class<? extends UnsuccessfulResponse>> getTypeClasses() {
return Util.<Class<? extends UnsuccessfulResponse>>asSet(UnsuccessfulResponse.class);
}
}
}
| 2,286
| 26.554217
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/NonTxPerCacheInboundInvocationHandler.java
|
package org.infinispan.remoting.inboundhandler;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commands.remote.SingleRpcCommand;
import org.infinispan.commands.statetransfer.ConflictResolutionStartCommand;
import org.infinispan.commands.statetransfer.StateTransferCancelCommand;
import org.infinispan.commands.statetransfer.StateTransferGetListenersCommand;
import org.infinispan.commands.statetransfer.StateTransferGetTransactionsCommand;
import org.infinispan.commands.statetransfer.StateTransferStartCommand;
import org.infinispan.util.concurrent.BlockingRunnable;
/**
* A {@link org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler} implementation for non-total order
* caches.
*
* @author Pedro Ruivo
* @since 7.1
*/
public class NonTxPerCacheInboundInvocationHandler extends BasePerCacheInboundInvocationHandler {
@Override
public void handle(CacheRpcCommand command, Reply reply, DeliverOrder order) {
try {
final int commandTopologyId = extractCommandTopologyId(command);
final boolean onExecutorService = executeOnExecutorService(order, command);
final boolean sync = order.preserveOrder();
final BlockingRunnable runnable;
boolean waitForTransactionalData = true;
switch (command.getCommandId()) {
case SingleRpcCommand.COMMAND_ID:
runnable = createDefaultRunnable(command, reply, commandTopologyId, onExecutorService ? TopologyMode.READY_TX_DATA : TopologyMode.WAIT_TX_DATA, sync);
break;
case ConflictResolutionStartCommand.COMMAND_ID:
case StateTransferCancelCommand.COMMAND_ID:
case StateTransferGetListenersCommand.COMMAND_ID:
case StateTransferGetTransactionsCommand.COMMAND_ID:
case StateTransferStartCommand.COMMAND_ID:
waitForTransactionalData = false;
default:
runnable = createDefaultRunnable(command, reply, commandTopologyId, waitForTransactionalData, onExecutorService, sync);
break;
}
handleRunnable(runnable, onExecutorService);
} catch (Throwable throwable) {
reply.reply(exceptionHandlingCommand(command, throwable));
}
}
}
| 2,279
| 43.705882
| 165
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/GlobalInboundInvocationHandler.java
|
package org.infinispan.remoting.inboundhandler;
import static org.infinispan.factories.KnownComponentNames.BLOCKING_EXECUTOR;
import static org.infinispan.util.logging.Log.CLUSTER;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.function.BiConsumer;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.GlobalRpcCommand;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.configuration.ConfigurationManager;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
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.notifications.Listener;
import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier;
import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStopped;
import org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.ExceptionResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.SuccessfulResponse;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.HeartBeatCommand;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.XSiteReplicateCommand;
import org.infinispan.xsite.metrics.XSiteMetricsCollector;
/**
* {@link org.infinispan.remoting.inboundhandler.InboundInvocationHandler} implementation that handles all the {@link
* org.infinispan.commands.ReplicableCommand}.
* <p/>
* This component handles the {@link org.infinispan.commands.ReplicableCommand} from local and remote site. The remote
* site {@link org.infinispan.commands.ReplicableCommand} are sent to the {@link org.infinispan.xsite.BackupReceiver} to
* be handled.
* <p/>
* Also, the non-{@link org.infinispan.commands.remote.CacheRpcCommand} are processed directly and the {@link
* org.infinispan.commands.remote.CacheRpcCommand} are processed in the cache's {@link
* org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler} implementation.
*
* @author Pedro Ruivo
* @since 7.1
*/
@Listener
@Scope(Scopes.GLOBAL)
public class GlobalInboundInvocationHandler implements InboundInvocationHandler {
private static final Log log = LogFactory.getLog(GlobalInboundInvocationHandler.class);
// TODO: To be removed with https://issues.redhat.com/browse/ISPN-11483
@Inject @ComponentName(BLOCKING_EXECUTOR)
ExecutorService blockingExecutor;
@Inject GlobalComponentRegistry globalComponentRegistry;
@Inject CacheManagerNotifier managerNotifier;
private final Map<RemoteSiteCache, LocalSiteCache> localCachesMap = new ConcurrentHashMap<>();
private static Response shuttingDownResponse() {
return CacheNotFoundResponse.INSTANCE;
}
private static ExceptionResponse exceptionHandlingCommand(Throwable throwable) {
if (throwable instanceof Exception) {
return new ExceptionResponse(((Exception) throwable));
} else {
return new ExceptionResponse(new CacheException("Problems invoking command.", throwable));
}
}
@Start
public void start() {
managerNotifier.addListener(this);
}
@Stop
public void stop() {
managerNotifier.removeListener(this);
}
@CacheStopped
public void cacheStopped(CacheStoppedEvent event) {
ByteString cacheName = ByteString.fromString(event.getCacheName());
localCachesMap.entrySet().removeIf(entry -> entry.getValue().cacheName.equals(cacheName));
}
@Override
public void handleFromCluster(Address origin, ReplicableCommand command, Reply reply, DeliverOrder order) {
command.setOrigin(origin);
try {
if (command.getCommandId() == HeartBeatCommand.COMMAND_ID) {
reply.reply(null);
} else if (command instanceof CacheRpcCommand) {
handleCacheRpcCommand(origin, (CacheRpcCommand) command, reply, order);
} else {
handleReplicableCommand(origin, command, reply, order);
}
} catch (Throwable t) {
if (command.logThrowable(t)) {
CLUSTER.exceptionHandlingCommand(command, t);
}
reply.reply(exceptionHandlingCommand(t));
}
}
@Override
public void handleFromRemoteSite(String origin, XSiteReplicateCommand<?> command, Reply reply, DeliverOrder order) {
if (log.isTraceEnabled()) {
log.tracef("Handling command %s from remote site %s", command, origin);
}
LocalSiteCache localCache = findLocalCacheForRemoteSite(origin, command.getCacheName());
if (localCache == null) {
reply.reply(new ExceptionResponse(log.xsiteCacheNotFound(origin, command.getCacheName())));
return;
} else if (localCache.local) {
reply.reply(new ExceptionResponse(log.xsiteInLocalCache(origin, localCache.cacheName)));
return;
}
ComponentRegistry cr = globalComponentRegistry.getNamedComponentRegistry(localCache.cacheName);
if (cr == null) {
reply.reply(new ExceptionResponse(log.xsiteCacheNotStarted(origin, localCache.cacheName)));
return;
}
cr.getComponent(XSiteMetricsCollector.class).recordRequestsReceived(origin);
command.performInLocalSite(cr, order.preserveOrder()).whenComplete(new ResponseConsumer(command, reply));
}
private void handleCacheRpcCommand(Address origin, CacheRpcCommand command, Reply reply, DeliverOrder mode) {
if (log.isTraceEnabled()) {
log.tracef("Attempting to execute CacheRpcCommand: %s [sender=%s]", command, origin);
}
ByteString cacheName = command.getCacheName();
ComponentRegistry cr = globalComponentRegistry.getNamedComponentRegistry(cacheName);
if (cr == null) {
if (log.isTraceEnabled()) {
log.tracef("Silently ignoring that %s cache is not defined", cacheName);
}
reply.reply(CacheNotFoundResponse.INSTANCE);
return;
}
CommandsFactory commandsFactory = cr.getCommandsFactory();
// initialize this command with components specific to the intended cache instance
commandsFactory.initializeReplicableCommand(command, true);
PerCacheInboundInvocationHandler handler = cr.getPerCacheInboundInvocationHandler();
handler.handle(command, reply, mode);
}
private void handleReplicableCommand(Address origin, ReplicableCommand command, Reply reply, DeliverOrder order) {
if (log.isTraceEnabled()) {
log.tracef("Attempting to execute non-CacheRpcCommand: %s [sender=%s]", command, origin);
}
Runnable runnable = new ReplicableCommandRunner(command, reply, globalComponentRegistry, order.preserveOrder());
if (order.preserveOrder() || !command.canBlock()) {
//we must/can run in this thread
runnable.run();
} else {
blockingExecutor.execute(runnable);
}
}
/**
* test only! See BackupCacheStoppedTest
*/
public ByteString getLocalCacheForRemoteSite(String remoteSite, ByteString remoteCache) {
LocalSiteCache cache = localCachesMap.get(new RemoteSiteCache(remoteSite, remoteCache));
return cache == null ? null : cache.cacheName;
}
private LocalSiteCache findLocalCacheForRemoteSite(String remoteSite, ByteString remoteCache) {
RemoteSiteCache key = new RemoteSiteCache(remoteSite, remoteCache);
return localCachesMap.computeIfAbsent(key, this::lookupLocalCaches);
}
private LocalSiteCache lookupLocalCaches(RemoteSiteCache remoteSiteCache) {
for (String name : getCacheNames()) {
Configuration configuration = getCacheConfiguration(name);
if (configuration != null && isBackupForRemoteCache(configuration, remoteSiteCache, name)) {
return new LocalSiteCache(ByteString.fromString(name), isLocal(configuration));
}
}
String name = remoteSiteCache.originCache.toString();
log.debugf("Did not find any backup explicitly configured backup cache for remote cache/site: %s/%s. Using %s",
remoteSiteCache.originSite, name, name);
Configuration configuration = getCacheConfiguration(name);
if (configuration == null) {
return null;
}
return new LocalSiteCache(remoteSiteCache.originCache, isLocal(configuration));
}
private Collection<String> getCacheNames() {
return globalComponentRegistry.getCacheManager().getCacheNames();
}
private Configuration getCacheConfiguration(String cacheName) {
return globalComponentRegistry.getComponent(ConfigurationManager.class).getConfiguration(cacheName, false);
}
private static boolean isLocal(Configuration configuration) {
return !configuration.clustering().cacheMode().isClustered();
}
private boolean isBackupForRemoteCache(Configuration cacheConfiguration, RemoteSiteCache remoteSite, String localCacheName) {
String remoteSiteName = remoteSite.originSite;
String remoteCacheName = remoteSite.originCache.toString();
boolean found = cacheConfiguration.sites().backupFor().isBackupFor(remoteSiteName, remoteCacheName);
if (log.isTraceEnabled() && found) {
log.tracef("Found local cache '%s' is backup for cache '%s' from site '%s'", localCacheName, remoteCacheName,
remoteSiteName);
}
return found;
}
private static class ReplicableCommandRunner extends ResponseConsumer implements Runnable {
private final GlobalComponentRegistry globalComponentRegistry;
private final boolean preserveOrder;
private ReplicableCommandRunner(ReplicableCommand command, Reply reply,
GlobalComponentRegistry globalComponentRegistry, boolean preserveOrder) {
super(command, reply);
this.globalComponentRegistry = globalComponentRegistry;
this.preserveOrder = preserveOrder;
}
@Override
public void run() {
try {
CompletionStage<?> stage;
if (command instanceof GlobalRpcCommand) {
stage = ((GlobalRpcCommand) command).invokeAsync(globalComponentRegistry).whenComplete(this);
} else {
globalComponentRegistry.wireDependencies(command);
stage = command.invokeAsync().whenComplete(this);
}
if (preserveOrder) {
CompletionStages.join(stage);
}
} catch (Throwable throwable) {
accept(null, throwable);
}
}
}
private static class ResponseConsumer implements BiConsumer<Object, Throwable> {
final ReplicableCommand command;
private final Reply reply;
private ResponseConsumer(ReplicableCommand command, Reply reply) {
this.command = command;
this.reply = reply;
}
@Override
public void accept(Object retVal, Throwable throwable) {
reply.reply(convertToResponse(retVal, throwable));
}
private Response convertToResponse(Object retVal, Throwable throwable) {
if (throwable != null) {
throwable = CompletableFutures.extractException(throwable);
if (throwable instanceof InterruptedException || throwable instanceof IllegalLifecycleStateException) {
CLUSTER.debugf("Shutdown while handling command %s", command);
return shuttingDownResponse();
} else {
if (command.logThrowable(throwable)) {
CLUSTER.exceptionHandlingCommand(command, throwable);
}
return exceptionHandlingCommand(throwable);
}
} else {
if (retVal == null || retVal instanceof Response) {
return (Response) retVal;
} else {
return SuccessfulResponse.create(retVal);
}
}
}
}
private static class RemoteSiteCache {
private final String originSite;
private final ByteString originCache;
private RemoteSiteCache(String originSite, ByteString originCache) {
this.originSite = originSite;
this.originCache = originCache;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RemoteSiteCache remoteSiteCache = (RemoteSiteCache) o;
return Objects.equals(originSite, remoteSiteCache.originSite) &&
Objects.equals(originCache, remoteSiteCache.originCache);
}
@Override
public int hashCode() {
return Objects.hash(originSite, originCache);
}
}
private static class LocalSiteCache {
private final ByteString cacheName;
private final boolean local;
private LocalSiteCache(ByteString cacheName, boolean local) {
this.cacheName = cacheName;
this.local = local;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LocalSiteCache that = (LocalSiteCache) o;
return local == that.local &&
Objects.equals(cacheName, that.cacheName);
}
@Override
public int hashCode() {
return Objects.hash(cacheName, local);
}
}
}
| 14,363
| 38.789474
| 128
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/package-info.java
|
/**
* Handling of inbound commands on remote nodes.
*
* @api.private
*/
package org.infinispan.remoting.inboundhandler;
| 124
| 16.857143
| 48
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/AbstractDelegatingHandler.java
|
package org.infinispan.remoting.inboundhandler;
import org.infinispan.commands.remote.CacheRpcCommand;
/**
* Class to be extended to allow some control over the {@link PerCacheInboundInvocationHandler}
* in tests.
*
* @author Pedro Ruivo
* @since 7.1
*/
public abstract class AbstractDelegatingHandler implements PerCacheInboundInvocationHandler {
protected final PerCacheInboundInvocationHandler delegate;
protected AbstractDelegatingHandler(PerCacheInboundInvocationHandler delegate) {
this.delegate = delegate;
}
@Override
public void handle(CacheRpcCommand command, Reply reply, DeliverOrder order) {
boolean canDelegate = beforeHandle(command, reply, order);
if (canDelegate) {
delegate.handle(command, reply, order);
}
afterHandle(command, order, canDelegate);
}
@Override
public void setFirstTopologyAsMember(int firstTopologyAsMember) {
delegate.setFirstTopologyAsMember(firstTopologyAsMember);
}
@Override
public int getFirstTopologyAsMember() {
return delegate.getFirstTopologyAsMember();
}
/**
* Invoked before the command is handled by the real {@link PerCacheInboundInvocationHandler}.
*
* @return {@code true} if the command should be handled by the read {@link PerCacheInboundInvocationHandler},
* {@code false} otherwise.
*/
protected boolean beforeHandle(CacheRpcCommand command, Reply reply, DeliverOrder order) {
return true;
}
/**
* Invoked after the command is handled.
*
* @param delegated {@code true} if the command was handled by the real {@link PerCacheInboundInvocationHandler},
* {@code false} otherwise.
*/
protected void afterHandle(CacheRpcCommand command, DeliverOrder order, boolean delegated) {
//no-op by default
}
@Override
public void checkForReadyTasks() {
delegate.checkForReadyTasks();
}
}
| 1,935
| 29.25
| 116
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/InboundInvocationHandler.java
|
package org.infinispan.remoting.inboundhandler;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.remoting.transport.Address;
import org.infinispan.xsite.XSiteReplicateCommand;
/**
* Interface to invoke when the {@link org.infinispan.remoting.transport.Transport} receives a command from other node
* or site.
*
* @author Pedro Ruivo
* @since 7.1
*/
public interface InboundInvocationHandler {
/**
* Handles the {@link org.infinispan.commands.ReplicableCommand} from other node belonging to local site.
*
* @param origin the sender {@link org.infinispan.remoting.transport.Address}
* @param command the {@link org.infinispan.commands.ReplicableCommand} to handler
* @param reply the return value is passed to this object in order to be sent back to the origin
* @param order the {@link org.infinispan.remoting.inboundhandler.DeliverOrder} in which the command was sent
*/
void handleFromCluster(Address origin, ReplicableCommand command, Reply reply, DeliverOrder order);
/**
* Handles the {@link org.infinispan.commands.ReplicableCommand} from remote site.
* @param origin the sender site
* @param command the {@link org.infinispan.commands.ReplicableCommand} to handle
* @param reply the return value is passed to this object in order to be sent back to the origin
* @param order the {@link DeliverOrder} in which the command was sent
*/
void handleFromRemoteSite(String origin, XSiteReplicateCommand<?> command, Reply reply, DeliverOrder order);
}
| 1,557
| 43.514286
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/TrianglePerCacheInboundInvocationHandler.java
|
package org.infinispan.remoting.inboundhandler;
import static org.infinispan.commons.util.EnumUtil.containsAll;
import static org.infinispan.context.impl.FlagBitSets.FORCE_ASYNCHRONOUS;
import static org.infinispan.context.impl.FlagBitSets.FORCE_SYNCHRONOUS;
import static org.infinispan.remoting.inboundhandler.DeliverOrder.NONE_NO_FC;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commands.remote.SingleRpcCommand;
import org.infinispan.commands.statetransfer.ConflictResolutionStartCommand;
import org.infinispan.commands.statetransfer.StateTransferCancelCommand;
import org.infinispan.commands.statetransfer.StateTransferGetListenersCommand;
import org.infinispan.commands.statetransfer.StateTransferGetTransactionsCommand;
import org.infinispan.commands.statetransfer.StateTransferStartCommand;
import org.infinispan.commands.triangle.BackupNoopCommand;
import org.infinispan.commands.triangle.BackupWriteCommand;
import org.infinispan.commands.triangle.MultiEntriesFunctionalBackupWriteCommand;
import org.infinispan.commands.triangle.MultiKeyFunctionalBackupWriteCommand;
import org.infinispan.commands.triangle.PutMapBackupWriteCommand;
import org.infinispan.commands.triangle.SingleKeyBackupWriteCommand;
import org.infinispan.commands.triangle.SingleKeyFunctionalBackupWriteCommand;
import org.infinispan.commands.write.BackupAckCommand;
import org.infinispan.commands.write.BackupMultiKeyAckCommand;
import org.infinispan.commands.write.ExceptionAckCommand;
import org.infinispan.distribution.TriangleOrderManager;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.remoting.inboundhandler.action.Action;
import org.infinispan.remoting.inboundhandler.action.ActionState;
import org.infinispan.remoting.inboundhandler.action.ActionStatus;
import org.infinispan.remoting.inboundhandler.action.DefaultReadyAction;
import org.infinispan.remoting.inboundhandler.action.ReadyAction;
import org.infinispan.remoting.inboundhandler.action.TriangleOrderAction;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.concurrent.BlockingRunnable;
import org.infinispan.util.concurrent.CommandAckCollector;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* A {@link PerCacheInboundInvocationHandler} implementation for non-transactional and distributed caches that uses the
* triangle algorithm.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class TrianglePerCacheInboundInvocationHandler extends BasePerCacheInboundInvocationHandler implements Action {
private static final Log log = LogFactory.getLog(TrianglePerCacheInboundInvocationHandler.class);
@Inject TriangleOrderManager triangleOrderManager;
@Inject CommandAckCollector commandAckCollector;
@Inject CommandsFactory commandsFactory;
private Address localAddress;
private boolean asyncCache;
@Override
public void start() {
super.start();
localAddress = rpcManager.getAddress();
asyncCache = !configuration.clustering().cacheMode().isSynchronous();
}
@Override
public void handle(CacheRpcCommand command, Reply reply, DeliverOrder order) {
try {
switch (command.getCommandId()) {
case SingleRpcCommand.COMMAND_ID:
handleSingleRpcCommand((SingleRpcCommand) command, reply, order);
return;
case SingleKeyBackupWriteCommand.COMMAND_ID:
case SingleKeyFunctionalBackupWriteCommand.COMMAND_ID:
case BackupNoopCommand.COMMAND_ID:
handleSingleKeyBackupCommand((BackupWriteCommand) command);
break;
case PutMapBackupWriteCommand.COMMAND_ID:
case MultiEntriesFunctionalBackupWriteCommand.COMMAND_ID:
case MultiKeyFunctionalBackupWriteCommand.COMMAND_ID:
handleMultiKeyBackupCommand((BackupWriteCommand) command);
return;
case BackupAckCommand.COMMAND_ID:
case BackupMultiKeyAckCommand.COMMAND_ID:
case ExceptionAckCommand.COMMAND_ID:
handleBackupAckCommand((BackupAckCommand) command);
return;
case ConflictResolutionStartCommand.COMMAND_ID:
case StateTransferCancelCommand.COMMAND_ID:
case StateTransferGetListenersCommand.COMMAND_ID:
case StateTransferGetTransactionsCommand.COMMAND_ID:
case StateTransferStartCommand.COMMAND_ID:
handleStateRequestCommand(command, reply, order);
return;
default:
handleDefaultCommand(command, reply, order);
}
} catch (Throwable throwable) {
reply.reply(exceptionHandlingCommand(command, throwable));
}
}
//action interface
@Override
public ActionStatus check(ActionState state) {
return isCommandSentBeforeFirstTopology(state.getCommandTopologyId()) ?
ActionStatus.CANCELED :
ActionStatus.READY;
}
public TriangleOrderManager getTriangleOrderManager() {
return triangleOrderManager;
}
@Override
public void onFinally(ActionState state) {
//no-op
//needed for ConditionalOperationPrimaryOwnerFailTest
//it mocks this class and when Action.onFinally is invoked, it doesn't behave well with the default implementation
//in the interface.
}
private void handleStateRequestCommand(CacheRpcCommand command, Reply reply, DeliverOrder order) {
if (executeOnExecutorService(order, command)) {
BlockingRunnable runnable = createDefaultRunnable(command, reply, extractCommandTopologyId(command),
TopologyMode.READY_TOPOLOGY, order.preserveOrder());
blockingExecutor.execute(runnable);
} else {
BlockingRunnable runnable = createDefaultRunnable(command, reply, extractCommandTopologyId(command),
TopologyMode.WAIT_TOPOLOGY, order.preserveOrder());
runnable.run();
}
}
private void handleDefaultCommand(CacheRpcCommand command, Reply reply, DeliverOrder order) {
if (executeOnExecutorService(order, command)) {
BlockingRunnable runnable = createDefaultRunnable(command, reply, extractCommandTopologyId(command),
TopologyMode.READY_TX_DATA, order.preserveOrder());
blockingExecutor.execute(runnable);
} else {
BlockingRunnable runnable = createDefaultRunnable(command, reply, extractCommandTopologyId(command),
TopologyMode.WAIT_TX_DATA, order.preserveOrder());
runnable.run();
}
}
private void handleMultiKeyBackupCommand(BackupWriteCommand command) {
final int topologyId = command.getTopologyId();
ReadyAction readyAction = createTriangleOrderAction(command, topologyId, command.getSequence(),
command.getSegmentId());
BlockingRunnable runnable = createMultiKeyBackupRunnable(command, topologyId, readyAction);
nonBlockingExecutor.execute(runnable);
}
private void handleSingleKeyBackupCommand(BackupWriteCommand command) {
final int topologyId = command.getTopologyId();
ReadyAction readyAction = createTriangleOrderAction(command, topologyId, command.getSequence(), command.getSegmentId());
BlockingRunnable runnable = createSingleKeyBackupRunnable(command, topologyId, readyAction);
nonBlockingExecutor.execute(runnable);
}
private void handleBackupAckCommand(BackupAckCommand command) {
command.ack(commandAckCollector);
}
private void handleSingleRpcCommand(SingleRpcCommand command, Reply reply, DeliverOrder order) {
if (executeOnExecutorService(order, command)) {
int commandTopologyId = extractCommandTopologyId(command);
BlockingRunnable runnable = createDefaultRunnable(command, reply, commandTopologyId,
TopologyMode.READY_TX_DATA,
order.preserveOrder());
blockingExecutor.execute(runnable);
} else {
createDefaultRunnable(command, reply, extractCommandTopologyId(command), TopologyMode.WAIT_TX_DATA,
order.preserveOrder()).run();
}
}
private void sendExceptionAck(CommandInvocationId id, Throwable throwable, int topologyId, long flagBitSet) {
final Address origin = id.getAddress();
if (skipBackupAck(flagBitSet)) {
if (log.isTraceEnabled()) {
log.tracef("Skipping ack for command %s.", id);
}
return;
}
if (log.isTraceEnabled()) {
log.tracef("Sending exception ack for command %s. Originator=%s.", id, origin);
}
if (origin.equals(localAddress)) {
commandAckCollector.completeExceptionally(id.getId(), throwable, topologyId);
} else {
rpcManager.sendTo(origin, commandsFactory.buildExceptionAckCommand(id.getId(), throwable, topologyId), NONE_NO_FC);
}
}
private void sendBackupAck(CommandInvocationId id, int topologyId, long flagBitSet) {
final Address origin = id.getAddress();
if (skipBackupAck(flagBitSet)) {
if (log.isTraceEnabled()) {
log.tracef("Skipping ack for command %s.", id);
}
return;
}
boolean isLocal = localAddress.equals(origin);
if (log.isTraceEnabled()) {
log.tracef("Sending ack for command %s. isLocal? %s.", id, isLocal);
}
if (isLocal) {
commandAckCollector.backupAck(id.getId(), origin, topologyId);
} else {
rpcManager.sendTo(origin, commandsFactory.buildBackupAckCommand(id.getId(), topologyId), NONE_NO_FC);
}
}
private void onBackupException(BackupWriteCommand command, Throwable throwable, ReadyAction readyAction) {
readyAction.onException();
readyAction.onFinally(); //notified TriangleOrderManager before sending the ack.
sendExceptionAck(command.getCommandInvocationId(), throwable, command.getTopologyId(), command.getFlags());
}
private BlockingRunnable createSingleKeyBackupRunnable(BackupWriteCommand command, int commandTopologyId,
ReadyAction readyAction) {
readyAction.addListener(this::checkForReadyTasks);
return new DefaultTopologyRunnable(this, command, Reply.NO_OP, TopologyMode.READY_TX_DATA, commandTopologyId,
false) {
@Override
public boolean isReady() {
return super.isReady() && readyAction.isReady();
}
@Override
protected void onException(Throwable throwable) {
super.onException(throwable);
onBackupException((BackupWriteCommand) command, throwable, readyAction);
}
@Override
protected void afterInvoke() {
super.afterInvoke();
readyAction.onFinally();
BackupWriteCommand backupCommand = (BackupWriteCommand) command;
sendBackupAck(backupCommand.getCommandInvocationId(), commandTopologyId, backupCommand.getFlags());
}
};
}
private void sendMultiKeyAck(CommandInvocationId id, int topologyId, int segment, long flagBitSet) {
final Address origin = id.getAddress();
if (skipBackupAck(flagBitSet)) {
if (log.isTraceEnabled()) {
log.tracef("Skipping ack for command %s.", id);
}
return;
}
if (log.isTraceEnabled()) {
log.tracef("Sending ack for command %s. Originator=%s.", id, origin);
}
if (id.getAddress().equals(localAddress)) {
commandAckCollector.multiKeyBackupAck(id.getId(), localAddress, segment, topologyId);
} else {
BackupMultiKeyAckCommand command =
commandsFactory.buildBackupMultiKeyAckCommand(id.getId(), segment, topologyId);
rpcManager.sendTo(origin, command, NONE_NO_FC);
}
}
private BlockingRunnable createMultiKeyBackupRunnable(BackupWriteCommand command, int commandTopologyId,
ReadyAction readyAction) {
readyAction.addListener(this::checkForReadyTasks);
return new DefaultTopologyRunnable(this, command, Reply.NO_OP, TopologyMode.READY_TX_DATA, commandTopologyId,
false) {
@Override
public boolean isReady() {
return super.isReady() && readyAction.isReady();
}
@Override
protected void onException(Throwable throwable) {
super.onException(throwable);
onBackupException((BackupWriteCommand) command, throwable, readyAction);
}
@Override
protected void afterInvoke() {
super.afterInvoke();
readyAction.onFinally();
BackupWriteCommand backupCommand = (BackupWriteCommand) command;
sendMultiKeyAck(backupCommand.getCommandInvocationId(), commandTopologyId, backupCommand.getSegmentId(),
backupCommand.getFlags());
}
};
}
private ReadyAction createTriangleOrderAction(ReplicableCommand command, int topologyId, long sequence, int segmentId) {
return new DefaultReadyAction(new ActionState(command, topologyId), this,
new TriangleOrderAction(this, sequence, segmentId));
}
private boolean skipBackupAck(long flagBitSet) {
return containsAll(flagBitSet, FORCE_ASYNCHRONOUS) ||
(asyncCache && !containsAll(flagBitSet, FORCE_SYNCHRONOUS));
}
}
| 13,700
| 43.77451
| 126
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/DefaultTopologyRunnable.java
|
package org.infinispan.remoting.inboundhandler;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.util.concurrent.CompletionStages;
/**
* The default {@link Runnable} for the remote commands receives.
* <p/>
* It checks the command topology and ensures that the topology higher or equal is installed in this node.
*
* @author Pedro Ruivo
* @since 8.0
*/
public class DefaultTopologyRunnable extends BaseBlockingRunnable {
private final TopologyMode topologyMode;
protected final int commandTopologyId;
public DefaultTopologyRunnable(BasePerCacheInboundInvocationHandler handler, CacheRpcCommand command, Reply reply,
TopologyMode topologyMode, int commandTopologyId, boolean sync) {
super(handler, command, reply, sync);
this.topologyMode = topologyMode;
this.commandTopologyId = commandTopologyId;
}
@Override
public boolean isReady() {
switch (topologyMode) {
case READY_TOPOLOGY:
return handler.getStateTransferLock().topologyReceived(waitTopology());
case READY_TX_DATA:
return handler.getStateTransferLock().transactionDataReceived(waitTopology());
default:
return true;
}
}
@Override
protected CompletionStage<CacheNotFoundResponse> beforeInvoke() {
CompletionStage<Void> stage = null;
switch (topologyMode) {
case WAIT_TOPOLOGY:
stage = handler.getStateTransferLock().topologyFuture(waitTopology());
break;
case WAIT_TX_DATA:
stage = handler.getStateTransferLock().transactionDataFuture(waitTopology());
break;
default:
break;
}
if (stage != null && !CompletionStages.isCompletedSuccessfully(stage)) {
return stage.thenApply(nil -> handler.isCommandSentBeforeFirstTopology(commandTopologyId) ?
CacheNotFoundResponse.INSTANCE :
null);
} else {
return handler.isCommandSentBeforeFirstTopology(commandTopologyId) ?
CompletableFuture.completedFuture(CacheNotFoundResponse.INSTANCE) :
null;
}
}
private int waitTopology() {
// Always wait for the first topology (i.e. for the join to finish)
return Math.max(commandTopologyId, 0);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("DefaultTopologyRunnable{");
sb.append("topologyMode=").append(topologyMode);
sb.append(", commandTopologyId=").append(commandTopologyId);
sb.append(", command=").append(command);
sb.append(", sync=").append(sync);
sb.append('}');
return sb.toString();
}
}
| 2,898
| 34.353659
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/Reply.java
|
package org.infinispan.remoting.inboundhandler;
import org.infinispan.remoting.responses.Response;
/**
* Interface responsible to send back the return value to the sender.
*
* @author Pedro Ruivo
* @since 7.1
*/
public interface Reply {
Reply NO_OP = returnValue -> {};
/**
* Sends back the return value to the sender.
*
* @param response the return value
*/
void reply(Response response);
}
| 426
| 18.409091
| 69
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/BaseBlockingRunnable.java
|
package org.infinispan.remoting.inboundhandler;
import static org.infinispan.remoting.inboundhandler.BasePerCacheInboundInvocationHandler.exceptionHandlingCommand;
import static org.infinispan.remoting.inboundhandler.BasePerCacheInboundInvocationHandler.interruptedException;
import static org.infinispan.remoting.inboundhandler.BasePerCacheInboundInvocationHandler.outdatedTopology;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.function.BiConsumer;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.statetransfer.OutdatedTopologyException;
import org.infinispan.util.concurrent.BlockingRunnable;
import org.infinispan.util.concurrent.CompletionStages;
/**
* Common logic to handle {@link org.infinispan.commands.remote.CacheRpcCommand}.
*
* @author Pedro Ruivo
* @since 7.1
*/
public abstract class BaseBlockingRunnable implements BlockingRunnable {
protected final BasePerCacheInboundInvocationHandler handler;
protected final CacheRpcCommand command;
protected final Reply reply;
protected final boolean sync;
protected Response response;
private final BiConsumer<Response, Throwable> handleBeforeInvoke = this::handleBeforeInvoke;
protected BaseBlockingRunnable(BasePerCacheInboundInvocationHandler handler, CacheRpcCommand command, Reply reply,
boolean sync) {
this.handler = handler;
this.command = command;
this.reply = reply;
this.sync = sync;
}
@Override
public void run() {
if (sync) {
runSync();
} else {
runAsync();
}
}
private void runSync() {
try {
CompletionStage<CacheNotFoundResponse> beforeStage = beforeInvoke();
if (beforeStage != null) {
response = CompletionStages.join(beforeStage);
if (response != null) {
afterInvoke();
return;
}
}
CompletableFuture<Response> commandFuture = handler.invokeCommand(command);
response = commandFuture.join();
afterInvoke();
} catch (Throwable t) {
afterCommandException(unwrap(t));
} finally {
if (handler.isStopped()) {
response = CacheNotFoundResponse.INSTANCE;
}
reply.reply(response);
onFinally();
}
}
private void runAsync() {
CompletionStage<CacheNotFoundResponse> beforeStage = beforeInvoke();
if (beforeStage == null) {
invoke();
} else if (CompletionStages.isCompletedSuccessfully(beforeStage)) {
handleBeforeInvoke(CompletionStages.join(beforeStage), null);
} else {
beforeStage.whenComplete(handleBeforeInvoke);
}
}
private void handleBeforeInvoke(Response rsp, Throwable throwable) {
if (rsp != null) {
response = rsp;
afterInvoke();
if (handler.isStopped()) {
response = rsp = CacheNotFoundResponse.INSTANCE;
}
reply.reply(rsp);
onFinally();
} else if (throwable != null) {
afterCommandException(unwrap(throwable));
if (handler.isStopped()) {
response = CacheNotFoundResponse.INSTANCE;
}
reply.reply(response);
onFinally();
} else {
invoke();
}
}
private void invoke() {
CompletableFuture<Response> commandFuture;
try {
commandFuture = handler.invokeCommand(command);
} catch (Throwable t) {
afterCommandException(unwrap(t));
if (handler.isStopped()) {
response = CacheNotFoundResponse.INSTANCE;
}
reply.reply(response);
onFinally();
return;
}
if (CompletionStages.isCompletedSuccessfully(commandFuture)) {
invokedComplete(commandFuture.join(), null);
} else {
// Not worried about caching this method invocation, as this runnable is only used once
commandFuture.whenComplete(this::invokedComplete);
}
}
private void invokedComplete(Response rsp, Throwable throwable) {
try {
if (throwable == null) {
response = rsp;
afterInvoke();
} else {
afterCommandException(unwrap(throwable));
}
} finally {
if (handler.isStopped()) {
response = CacheNotFoundResponse.INSTANCE;
}
reply.reply(response);
onFinally();
}
}
private static Throwable unwrap(Throwable throwable) {
if (throwable instanceof CompletionException && throwable.getCause() != null) {
throwable = throwable.getCause();
}
return throwable;
}
private void afterCommandException(Throwable throwable) {
if (throwable instanceof InterruptedException) {
response = interruptedException(command);
} else if (throwable instanceof OutdatedTopologyException) {
response = outdatedTopology((OutdatedTopologyException) throwable);
} else if (throwable instanceof IllegalLifecycleStateException) {
response = CacheNotFoundResponse.INSTANCE;
} else {
response = exceptionHandlingCommand(command, throwable);
}
onException(throwable);
}
protected void onFinally() {
//no-op by default
}
protected void onException(Throwable throwable) {
//no-op by default
}
protected void afterInvoke() {
//no-op by default
}
protected CompletionStage<CacheNotFoundResponse> beforeInvoke() {
return null; //no-op by default
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(getClass().getSimpleName());
sb.append("{command=").append(command);
sb.append(", sync=").append(sync);
sb.append('}');
return sb.toString();
}
}
| 6,133
| 31.115183
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/TopologyMode.java
|
package org.infinispan.remoting.inboundhandler;
/**
* It checks or waits until the required topology is installed.
*
* @author Pedro Ruivo
* @since 8.0
*/
public enum TopologyMode {
WAIT_TOPOLOGY,
READY_TOPOLOGY,
WAIT_TX_DATA,
READY_TX_DATA;
public static TopologyMode create(boolean onExecutor, boolean txData) {
if (onExecutor && txData) {
return TopologyMode.READY_TX_DATA;
} else if (onExecutor) {
return TopologyMode.READY_TOPOLOGY;
} else if (txData) {
return TopologyMode.WAIT_TX_DATA;
} else {
return TopologyMode.WAIT_TOPOLOGY;
}
}
}
| 634
| 22.518519
| 74
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/BasePerCacheInboundInvocationHandler.java
|
package org.infinispan.remoting.inboundhandler;
import static org.infinispan.factories.KnownComponentNames.BLOCKING_EXECUTOR;
import static org.infinispan.factories.KnownComponentNames.NON_BLOCKING_EXECUTOR;
import static org.infinispan.util.logging.Log.CLUSTER;
import java.util.concurrent.CompletableFuture;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.TopologyAffectedCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commands.remote.ClusteredGetAllCommand;
import org.infinispan.commands.remote.ClusteredGetCommand;
import org.infinispan.commands.remote.SingleRpcCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.factories.ComponentRegistry;
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.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.ExceptionResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.ResponseGenerator;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.statetransfer.OutdatedTopologyException;
import org.infinispan.statetransfer.StateTransferLock;
import org.infinispan.util.concurrent.BlockingRunnable;
import org.infinispan.util.concurrent.BlockingTaskAwareExecutorService;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Implementation with the default handling methods and utilities methods.
*
* @author Pedro Ruivo
* @since 7.1
*/
@Scope(Scopes.NAMED_CACHE)
public abstract class BasePerCacheInboundInvocationHandler implements PerCacheInboundInvocationHandler {
private static final Log log = LogFactory.getLog(BasePerCacheInboundInvocationHandler.class);
private static final int NO_TOPOLOGY_COMMAND = Integer.MIN_VALUE;
// TODO: To be removed with https://issues.redhat.com/browse/ISPN-11483
@Inject @ComponentName(BLOCKING_EXECUTOR)
protected BlockingTaskAwareExecutorService blockingExecutor;
@Inject @ComponentName(NON_BLOCKING_EXECUTOR)
protected BlockingTaskAwareExecutorService nonBlockingExecutor;
@Inject StateTransferLock stateTransferLock;
@Inject ResponseGenerator responseGenerator;
@Inject ComponentRegistry componentRegistry;
@Inject protected Configuration configuration;
// Stop after RpcManager, so we stop accepting requests before we are unable to send requests ourselves
@Inject RpcManager rpcManager;
private volatile boolean stopped;
private volatile int firstTopologyAsMember = Integer.MAX_VALUE;
private static int extractCommandTopologyId(SingleRpcCommand command) {
ReplicableCommand innerCmd = command.getCommand();
if (innerCmd instanceof TopologyAffectedCommand) {
return ((TopologyAffectedCommand) innerCmd).getTopologyId();
}
return NO_TOPOLOGY_COMMAND;
}
static int extractCommandTopologyId(CacheRpcCommand command) {
switch (command.getCommandId()) {
case SingleRpcCommand.COMMAND_ID:
return extractCommandTopologyId((SingleRpcCommand) command);
case ClusteredGetCommand.COMMAND_ID:
case ClusteredGetAllCommand.COMMAND_ID:
// These commands are topology aware but we don't block them here - topologyId logic
// is handled in StateTransferInterceptor
return NO_TOPOLOGY_COMMAND;
default:
if (command instanceof TopologyAffectedCommand) {
return ((TopologyAffectedCommand) command).getTopologyId();
}
}
return NO_TOPOLOGY_COMMAND;
}
@Start
public void start() {
this.stopped = false;
}
@Stop
public void stop() {
this.stopped = true;
}
public boolean isStopped() {
return stopped;
}
final CompletableFuture<Response> invokeCommand(CacheRpcCommand cmd) throws Throwable {
if (log.isTraceEnabled()) {
log.tracef("Calling perform() on %s", cmd);
}
CompletableFuture<?> future = cmd.invokeAsync(componentRegistry).toCompletableFuture();
if (CompletionStages.isCompletedSuccessfully(future)) {
Object obj = future.join();
Response response = responseGenerator.getResponse(cmd, obj);
if (response == null) {
return CompletableFutures.completedNull();
}
return CompletableFuture.completedFuture(response);
}
return future.handle((rv, throwable) -> {
CompletableFutures.rethrowExceptionIfPresent(throwable);
return responseGenerator.getResponse(cmd, rv);
});
}
final StateTransferLock getStateTransferLock() {
return stateTransferLock;
}
static ExceptionResponse exceptionHandlingCommand(CacheRpcCommand command, Throwable throwable) {
if (command.logThrowable(throwable)) {
CLUSTER.exceptionHandlingCommand(command, throwable);
}
if (throwable instanceof Exception) {
return new ExceptionResponse(((Exception) throwable));
} else {
return new ExceptionResponse(new CacheException("Problems invoking command.", throwable));
}
}
static ExceptionResponse outdatedTopology(OutdatedTopologyException exception) {
log.tracef("Topology changed, retrying: %s", exception);
return new ExceptionResponse(exception);
}
static Response interruptedException(CacheRpcCommand command) {
CLUSTER.debugf("Shutdown while handling command %s", command);
return CacheNotFoundResponse.INSTANCE;
}
final void handleRunnable(BlockingRunnable runnable, boolean onExecutorService) {
// This means it is blocking and not preserve order per executeOnExecutorService
if (onExecutorService) {
blockingExecutor.execute(runnable);
} else {
runnable.run();
}
}
public final boolean isCommandSentBeforeFirstTopology(int commandTopologyId) {
if (0 <= commandTopologyId && commandTopologyId < firstTopologyAsMember) {
if (log.isTraceEnabled()) {
log.tracef("Ignoring command sent before the local node was a member (command topology id is %d, first topology as member is %d)", commandTopologyId, firstTopologyAsMember);
}
return true;
}
return false;
}
final BlockingRunnable createDefaultRunnable(CacheRpcCommand command, Reply reply, int commandTopologyId,
boolean waitTransactionalData, boolean onExecutorService,
boolean sync) {
return new DefaultTopologyRunnable(this, command, reply,
TopologyMode.create(onExecutorService, waitTransactionalData),
commandTopologyId, sync);
}
final BlockingRunnable createDefaultRunnable(final CacheRpcCommand command, final Reply reply,
final int commandTopologyId, TopologyMode topologyMode,
boolean sync) {
return new DefaultTopologyRunnable(this, command, reply, topologyMode, commandTopologyId, sync);
}
static boolean executeOnExecutorService(DeliverOrder order, CacheRpcCommand command) {
return !order.preserveOrder() && command.canBlock();
}
@Override
public void setFirstTopologyAsMember(int firstTopologyAsMember) {
this.firstTopologyAsMember = firstTopologyAsMember;
}
@Override
public int getFirstTopologyAsMember() {
return firstTopologyAsMember;
}
@Override
public void checkForReadyTasks() {
blockingExecutor.checkForReadyTasks();
nonBlockingExecutor.checkForReadyTasks();
}
}
| 8,020
| 38.707921
| 185
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/DeliverOrder.java
|
package org.infinispan.remoting.inboundhandler;
/**
* Used in RPC, it defines how the messages are delivered to the nodes.
*
* @author Pedro Ruivo
* @since 7.1
*/
public enum DeliverOrder {
/**
* The message is delivered as soon as it is received. No order is ensured between messages.
*/
NONE {
@Override
public boolean preserveOrder() {
return false;
}
},
/**
* The message is delivered as soon as it is received and, it is not affected by any flow control algorithm. No order
* is ensured between messages.
*/
NONE_NO_FC {
@Override
public boolean preserveOrder() {
return false;
}
@Override
public boolean skipFlowControl() {
return true;
}
},
/**
* The message is delivered by the order they are sent. If a node sends M1 and M2 to other node, it delivers first M1
* and then M2.
*/
PER_SENDER {
@Override
public boolean preserveOrder() {
return true;
}
},
/**
* The message is delivered by the order they are sent and, it is not affected by any flow control algorithm. If a
* node sends M1 and M2 to other node, it delivers first M1 and then M2.
*/
PER_SENDER_NO_FC {
@Override
public boolean preserveOrder() {
return true;
}
@Override
public boolean skipFlowControl() {
return true;
}
};
public abstract boolean preserveOrder();
public boolean skipFlowControl() {
return false;
}
}
| 1,555
| 22.575758
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/PerCacheInboundInvocationHandler.java
|
package org.infinispan.remoting.inboundhandler;
import org.infinispan.commands.remote.CacheRpcCommand;
/**
* Interface to invoke when a {@link CacheRpcCommand} is received from other node in the
* local site.
*
* @author Pedro Ruivo
* @since 7.1
*/
public interface PerCacheInboundInvocationHandler {
/**
* Handles the {@link CacheRpcCommand} from other node.
*
* @param command the {@link CacheRpcCommand} to handle.
* @param reply the return value is passed to this object in order to be sent back to the sender
* @param order the {@link DeliverOrder} in which the command was sent
*/
void handle(CacheRpcCommand command, Reply reply, DeliverOrder order);
/**
* @param firstTopologyAsMember The first topology in which the local node was a member.
* Any command with a lower topology id will be ignored.
*/
void setFirstTopologyAsMember(int firstTopologyAsMember);
/**
* @return The first topology in which the local node was a member.
*
* Any command with a lower topology id will be ignored.
*/
int getFirstTopologyAsMember();
/**
* Checks if any pending tasks are now ready to be ran and will run in them in a separate thread. This method does not
* block.
*/
void checkForReadyTasks();
}
| 1,328
| 29.906977
| 121
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/TxPerCacheInboundInvocationHandler.java
|
package org.infinispan.remoting.inboundhandler;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commands.statetransfer.ConflictResolutionStartCommand;
import org.infinispan.commands.statetransfer.StateTransferCancelCommand;
import org.infinispan.commands.statetransfer.StateTransferGetListenersCommand;
import org.infinispan.commands.statetransfer.StateTransferGetTransactionsCommand;
import org.infinispan.commands.statetransfer.StateTransferStartCommand;
import org.infinispan.util.concurrent.BlockingRunnable;
/**
* A {@link PerCacheInboundInvocationHandler} implementation for non-total order caches.
*
* @author Pedro Ruivo
* @since 7.1
*/
public class TxPerCacheInboundInvocationHandler extends BasePerCacheInboundInvocationHandler {
@Override
public void handle(CacheRpcCommand command, Reply reply, DeliverOrder order) {
try {
final int commandTopologyId = extractCommandTopologyId(command);
final boolean onExecutorService = executeOnExecutorService(order, command);
final boolean sync = order.preserveOrder();
final BlockingRunnable runnable;
switch (command.getCommandId()) {
case ConflictResolutionStartCommand.COMMAND_ID:
case StateTransferCancelCommand.COMMAND_ID:
case StateTransferGetListenersCommand.COMMAND_ID:
case StateTransferGetTransactionsCommand.COMMAND_ID:
case StateTransferStartCommand.COMMAND_ID:
runnable = createDefaultRunnable(command, reply, commandTopologyId, false, onExecutorService, sync);
break;
default:
runnable = createDefaultRunnable(command, reply, commandTopologyId, true, onExecutorService, sync);
}
handleRunnable(runnable, onExecutorService);
} catch (Throwable throwable) {
reply.reply(exceptionHandlingCommand(command, throwable));
}
}
}
| 1,940
| 43.113636
| 115
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/action/DefaultReadyAction.java
|
package org.infinispan.remoting.inboundhandler.action;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import org.infinispan.commons.util.InfinispanCollections;
/**
* A list of {@link Action} to be executed to check when it is ready.
* <p/>
* If an {@link Action} is canceled, then the remaining {@link Action} are not invoked.
*
* @author Pedro Ruivo
* @since 8.0
*/
public class DefaultReadyAction implements ReadyAction, ActionListener {
private final ActionState state;
private final Action[] actions;
private final AtomicInteger currentAction;
private final CompletableFuture<Void> notifier;
public DefaultReadyAction(ActionState state, Action... actions) {
this.state = Objects.requireNonNull(state, "Action state must be non null.");
this.actions = Objects.requireNonNull(actions, "Actions must be non null.");
notifier = new CompletableFuture<>();
currentAction = new AtomicInteger(0);
}
public void registerListener() {
for (Action action : actions) {
action.addListener(this);
}
}
@Override
public boolean isReady() {
int current = currentAction.get();
if (current >= actions.length) {
return true;
}
Action action = actions[current];
switch (action.check(state)) {
case READY:
//check the next action. If currentAction has changed, some thread already advanced.
return currentAction.compareAndSet(current, current + 1) && isReady();
case NOT_READY:
return false;
case CANCELED:
currentAction.set(actions.length);
return true;
}
return false;
}
@Override
public void addListener(ActionListener listener) {
if (notifier.isDone()) {
listener.onComplete();
} else {
notifier.thenRun(listener::onComplete);
}
}
@Override
public void onException() {
InfinispanCollections.forEach(actions, action -> action.onException(state));
}
@Override
public void onComplete() {
if (isReady()) {
notifier.complete(null);
}
}
@Override
public void onFinally() {
InfinispanCollections.forEach(actions, action -> action.onFinally(state));
}
}
| 2,346
| 27.277108
| 96
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/action/ActionStatus.java
|
package org.infinispan.remoting.inboundhandler.action;
/**
* The status for an {@link Action}.
*
* @author Pedro Ruivo
* @since 8.0
*/
public enum ActionStatus {
/**
* The action is completed successfully.
*/
READY,
/**
* The action isn't completed yet.
*/
NOT_READY,
/**
* The action is completed unsuccessfully.
*/
CANCELED
}
| 376
| 15.391304
| 54
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/action/Action.java
|
package org.infinispan.remoting.inboundhandler.action;
/**
* An action represents a step in {@link org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler}.
*
* @author Pedro Ruivo
* @since 8.0
*/
public interface Action {
/**
* It checks this action.
* <p/>
* When {@link ActionStatus#READY} or {@link ActionStatus#CANCELED} are final states.
* <p/>
* This method should be thread safe and idempotent since it can be invoked multiple times by multiples threads.
*
* @param state the current state.
* @return the status of this action.
*/
ActionStatus check(ActionState state);
/**
* Adds a listener to be invoked when this action is ready or canceled.
*
* @param listener the {@link ActionListener} to add.
*/
default void addListener(ActionListener listener) {
}
/**
* Invoked when an exception occurs while processing the command.
*
* @param state the current state.
*/
default void onException(ActionState state) {
}
/**
* Invoked always after the command is executed.
*
* @param state the current state.\
*/
default void onFinally(ActionState state) {
}
}
| 1,204
| 24.638298
| 115
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/action/TriangleOrderAction.java
|
package org.infinispan.remoting.inboundhandler.action;
import org.infinispan.remoting.inboundhandler.TrianglePerCacheInboundInvocationHandler;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* An {@link Action} that checks if the command is the next to be executed.
* <p>
* This action is used by the triangle algorithm to order updates from the primary owner to the backup owner.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class TriangleOrderAction implements Action {
private static final Log log = LogFactory.getLog(TriangleOrderAction.class);
private final long sequenceNumber;
private final TrianglePerCacheInboundInvocationHandler handler;
private final int segmentId;
public TriangleOrderAction(TrianglePerCacheInboundInvocationHandler handler, long sequenceNumber, int segmentId) {
this.handler = handler;
this.sequenceNumber = sequenceNumber;
this.segmentId = segmentId;
}
@Override
public ActionStatus check(ActionState state) {
if (log.isTraceEnabled()) {
log.tracef("Checking if next for segment %s and sequence %s", segmentId, sequenceNumber);
}
return handler.getTriangleOrderManager().isNext(segmentId, sequenceNumber, state.getCommandTopologyId()) ?
ActionStatus.READY :
ActionStatus.NOT_READY;
}
@Override
public void onFinally(ActionState state) {
handler.getTriangleOrderManager().markDelivered(segmentId, sequenceNumber, state.getCommandTopologyId());
handler.checkForReadyTasks();
}
}
| 1,583
| 35
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/action/ActionState.java
|
package org.infinispan.remoting.inboundhandler.action;
import org.infinispan.commands.ReplicableCommand;
/**
* The state used by an {@link Action}.
* <p/>
* It is shared among them.
*
* @author Pedro Ruivo
* @since 8.0
*/
public class ActionState {
private final ReplicableCommand command;
private final int commandTopologyId;
public ActionState(ReplicableCommand command, int commandTopologyId) {
this.command = command;
this.commandTopologyId = commandTopologyId;
}
public final <T extends ReplicableCommand> T getCommand() {
//noinspection unchecked
return (T) command;
}
public final int getCommandTopologyId() {
return commandTopologyId;
}
}
| 715
| 20.69697
| 73
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/action/ReadyAction.java
|
package org.infinispan.remoting.inboundhandler.action;
/**
* An interface that allows the {@link org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler} to check
* when this action is ready.
*
* @author Pedro Ruivo
* @since 8.0
*/
public interface ReadyAction {
/**
* @return {@code true} if ready.
*/
boolean isReady();
/**
* It adds a listener that is invoked when this action is ready.
*
* @param listener the listener to invoke.
*/
void addListener(ActionListener listener);
/**
* Cleanup when the command throws an exception while executing.
*/
void onException();
/**
* Invoked always after the command is executed and the reply is sent.
*/
void onFinally();
}
| 759
| 21.352941
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/inboundhandler/action/ActionListener.java
|
package org.infinispan.remoting.inboundhandler.action;
/**
* A listener that is invoked when an {@link Action} is completed.
*
* @author Pedro Ruivo
* @since 8.0
*/
public interface ActionListener {
/**
* Invoked when an {@link Action} is completed.
*/
void onComplete();
}
| 296
| 16.470588
| 66
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/rpc/package-info.java
|
/**
* Remote Procedure Call (RPC) interfaces and components used to invoke remote methods on cache instances.
*/
package org.infinispan.remoting.rpc;
| 152
| 29.6
| 106
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/rpc/RpcManagerImpl.java
|
package org.infinispan.remoting.rpc;
import static org.infinispan.factories.impl.MBeanMetadata.AttributeMetadata;
import static org.infinispan.remoting.rpc.RpcManagerImpl.OBJECT_NAME;
import static org.infinispan.util.logging.Log.CLUSTER;
import java.text.NumberFormat;
import java.util.Collection;
import java.util.LinkedList;
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.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.TopologyAffectedCommand;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.configuration.attributes.Attribute;
import org.infinispan.commons.configuration.attributes.AttributeListener;
import org.infinispan.commons.stat.TimerTracker;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.logging.TraceException;
import org.infinispan.configuration.cache.ClusteringConfiguration;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.jmx.JmxStatisticsExposer;
import org.infinispan.jmx.annotations.DataType;
import org.infinispan.jmx.annotations.MBean;
import org.infinispan.jmx.annotations.ManagedAttribute;
import org.infinispan.jmx.annotations.ManagedOperation;
import org.infinispan.jmx.annotations.MeasurementType;
import org.infinispan.jmx.annotations.Parameter;
import org.infinispan.jmx.annotations.Units;
import org.infinispan.metrics.impl.CustomMetricsSupplier;
import org.infinispan.metrics.impl.MetricUtils;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollector;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.remoting.transport.XSiteResponse;
import org.infinispan.topology.CacheTopology;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.XSiteBackup;
import org.infinispan.xsite.XSiteReplicateCommand;
import org.infinispan.xsite.metrics.XSiteMetricsCollector;
/**
* This component really is just a wrapper around a {@link org.infinispan.remoting.transport.Transport} implementation,
* and is used to set up the transport and provide lifecycle and dependency hooks into external transport
* implementations.
*
* @author Manik Surtani
* @author Galder Zamarreño
* @author Mircea.Markus@jboss.com
* @author Pedro Ruivo
* @since 4.0
*/
@MBean(objectName = OBJECT_NAME, description = "Manages all remote calls to remote cache instances in the cluster.")
@Scope(Scopes.NAMED_CACHE)
public class RpcManagerImpl implements RpcManager, JmxStatisticsExposer, CustomMetricsSupplier {
public static final String OBJECT_NAME = "RpcManager";
private static final Log log = LogFactory.getLog(RpcManagerImpl.class);
@Inject Transport t;
@Inject Configuration configuration;
@Inject ComponentRef<CommandsFactory> cf;
@Inject DistributionManager distributionManager;
@Inject TimeService timeService;
@Inject XSiteMetricsCollector xSiteMetricsCollector;
private final Function<ReplicableCommand, ReplicableCommand> toCacheRpcCommand = this::toCacheRpcCommand;
private final AttributeListener<Long> updateRpcOptions = this::updateRpcOptions;
private final XSiteResponse.XSiteResponseCompleted xSiteResponseCompleted = this::registerXSiteTime;
private final LongAdder replicationCount = new LongAdder();
private final LongAdder replicationFailures = new LongAdder();
private final LongAdder totalReplicationTime = new LongAdder();
private boolean statisticsEnabled = false; // by default, don't gather statistics.
private volatile RpcOptions syncRpcOptions;
@Override
public Collection<AttributeMetadata> getCustomMetrics() {
List<AttributeMetadata> attributes = new LinkedList<>();
for (String site : xSiteMetricsCollector.sites()) {
String lSite = site.toLowerCase();
attributes.add(MetricUtils.<RpcManagerImpl>createGauge("AverageXSiteReplicationTimeTo_" + lSite,
"Average Cross-Site replication time to " + site,
rpcManager -> rpcManager.getAverageXSiteReplicationTimeTo(site)));
attributes.add(MetricUtils.<RpcManagerImpl>createGauge("MinimumXSiteReplicationTimeTo_" + lSite,
"Minimum Cross-Site replication time to " + site,
rpcManager -> rpcManager.getMinimumXSiteReplicationTimeTo(site)));
attributes.add(MetricUtils.<RpcManagerImpl>createGauge("MaximumXSiteReplicationTimeTo_" + lSite,
"Maximum Cross-Site replication time to " + site,
rpcManager -> rpcManager.getMaximumXSiteReplicationTimeTo(site)));
attributes.add(MetricUtils.<RpcManagerImpl>createGauge("NumberXSiteRequestsSentTo_" + lSite,
"Number of Cross-Site request sent to " + site,
rpcManager -> rpcManager.getNumberXSiteRequestsSentTo(site)));
attributes.add(MetricUtils.<RpcManagerImpl>createGauge("NumberXSiteRequestsReceivedFrom_" + lSite,
"Number of Cross-Site request received from " + site,
rpcManager -> rpcManager.getNumberXSiteRequestsReceivedFrom(site)));
attributes.add(MetricUtils.<RpcManagerImpl>createTimer("ReplicationTimesTo_" + lSite,
"Replication times to " + site,
(rpcManager, timer) -> rpcManager.xSiteMetricsCollector.registerTimer(site, timer)));
}
return attributes;
}
@Start(priority = 9)
void start() {
statisticsEnabled = configuration.statistics().enabled();
configuration.clustering()
.attributes().attribute(ClusteringConfiguration.REMOTE_TIMEOUT)
.addListener(updateRpcOptions);
updateRpcOptions(configuration.clustering().attributes().attribute(ClusteringConfiguration.REMOTE_TIMEOUT), null);
}
@Stop
void stop() {
configuration.clustering()
.attributes().attribute(ClusteringConfiguration.REMOTE_TIMEOUT)
.removeListener(updateRpcOptions);
}
private void updateRpcOptions(Attribute<Long> attribute, Long oldValue) {
syncRpcOptions = new RpcOptions(DeliverOrder.NONE, attribute.get(), TimeUnit.MILLISECONDS);
}
@ManagedAttribute(description = "Retrieves the committed view.", displayName = "Committed view", dataType = DataType.TRAIT)
public String getCommittedViewAsString() {
CacheTopology cacheTopology = distributionManager.getCacheTopology();
if (cacheTopology == null)
return "N/A";
return cacheTopology.getCurrentCH().getMembers().toString();
}
@ManagedAttribute(description = "Retrieves the pending view.", displayName = "Pending view", dataType = DataType.TRAIT)
public String getPendingViewAsString() {
CacheTopology cacheTopology = distributionManager.getCacheTopology();
if (cacheTopology == null)
return "N/A";
ConsistentHash pendingCH = cacheTopology.getPendingCH();
return pendingCH != null ? pendingCH.getMembers().toString() : "null";
}
@Override
public <T> CompletionStage<T> invokeCommand(Address target, ReplicableCommand command,
ResponseCollector<T> collector, RpcOptions rpcOptions) {
CacheRpcCommand cacheRpc = toCacheRpcCommand(command);
if (!statisticsEnabled) {
return t.invokeCommand(target, cacheRpc, collector, rpcOptions.deliverOrder(),
rpcOptions.timeout(), rpcOptions.timeUnit());
}
long startTimeNanos = timeService.time();
CompletionStage<T> invocation;
try {
invocation = t.invokeCommand(target, cacheRpc, collector, rpcOptions.deliverOrder(),
rpcOptions.timeout(), rpcOptions.timeUnit());
} catch (Exception e) {
return errorReplicating(e);
}
return invocation.handle((response, throwable) -> updateStatistics(startTimeNanos, response, throwable));
}
private void checkTopologyId(ReplicableCommand command) {
if (command instanceof TopologyAffectedCommand && ((TopologyAffectedCommand) command).getTopologyId() < 0) {
throw new IllegalArgumentException("Command does not have a topology id");
}
}
@Override
public <T> CompletionStage<T> invokeCommand(Collection<Address> targets, ReplicableCommand command,
ResponseCollector<T> collector, RpcOptions rpcOptions) {
CacheRpcCommand cacheRpc = toCacheRpcCommand(command);
if (!statisticsEnabled) {
return t.invokeCommand(targets, cacheRpc, collector, rpcOptions.deliverOrder(),
rpcOptions.timeout(), rpcOptions.timeUnit());
}
long startTimeNanos = timeService.time();
CompletionStage<T> invocation;
try {
invocation = t.invokeCommand(targets, cacheRpc, collector, rpcOptions.deliverOrder(),
rpcOptions.timeout(), rpcOptions.timeUnit());
} catch (Exception e) {
return errorReplicating(e);
}
return invocation.handle((response, throwable) -> updateStatistics(startTimeNanos, response, throwable));
}
private <T> T updateStatistics(long startTimeNanos, T response, Throwable throwable) {
long timeTaken = timeService.timeDuration(startTimeNanos, TimeUnit.MILLISECONDS);
totalReplicationTime.add(timeTaken);
if (throwable == null) {
if (statisticsEnabled) {
replicationCount.increment();
}
return response;
} else {
if (statisticsEnabled) {
replicationFailures.increment();
}
return rethrowAsCacheException(throwable);
}
}
@Override
public <T> CompletionStage<T> invokeCommandOnAll(ReplicableCommand command, ResponseCollector<T> collector,
RpcOptions rpcOptions) {
CacheRpcCommand cacheRpc = toCacheRpcCommand(command);
List<Address> cacheMembers = distributionManager.getCacheTopology().getMembers();
if (!statisticsEnabled) {
return t.invokeCommandOnAll(cacheMembers, cacheRpc, collector, rpcOptions.deliverOrder(),
rpcOptions.timeout(), rpcOptions.timeUnit());
}
long startTimeNanos = timeService.time();
CompletionStage<T> invocation;
try {
invocation = t.invokeCommandOnAll(cacheMembers, cacheRpc, collector, rpcOptions.deliverOrder(),
rpcOptions.timeout(), rpcOptions.timeUnit());
} catch (Exception e) {
return errorReplicating(e);
}
return invocation.handle((response, throwable) -> updateStatistics(startTimeNanos, response, throwable));
}
@Override
public <T> CompletionStage<T> invokeCommandStaggered(Collection<Address> targets, ReplicableCommand command,
ResponseCollector<T> collector, RpcOptions rpcOptions) {
CacheRpcCommand cacheRpc = toCacheRpcCommand(command);
if (!statisticsEnabled) {
return t.invokeCommandStaggered(targets, cacheRpc, collector, rpcOptions.deliverOrder(), rpcOptions.timeout(),
rpcOptions.timeUnit());
}
long startTimeNanos = timeService.time();
CompletionStage<T> invocation;
try {
invocation = t.invokeCommandStaggered(targets, cacheRpc, collector, rpcOptions.deliverOrder(),
rpcOptions.timeout(), rpcOptions.timeUnit());
} catch (Exception e) {
return errorReplicating(e);
}
return invocation.handle((response, throwable) -> updateStatistics(startTimeNanos, response, throwable));
}
@Override
public <T> CompletionStage<T> invokeCommands(Collection<Address> targets,
Function<Address, ReplicableCommand> commandGenerator,
ResponseCollector<T> collector, RpcOptions rpcOptions) {
if (!statisticsEnabled) {
return t.invokeCommands(targets, commandGenerator.andThen(toCacheRpcCommand), collector,
rpcOptions.deliverOrder(), rpcOptions.timeout(), rpcOptions.timeUnit());
}
long startTimeNanos = timeService.time();
CompletionStage<T> invocation;
try {
invocation = t.invokeCommands(targets, commandGenerator.andThen(toCacheRpcCommand), collector,
rpcOptions.deliverOrder(), rpcOptions.timeout(), rpcOptions.timeUnit());
} catch (Exception e) {
return errorReplicating(e);
}
return invocation.handle((response, throwable) -> updateStatistics(startTimeNanos, response, throwable));
}
@Override
public <T> T blocking(CompletionStage<T> request) {
try {
return CompletableFutures.await(request.toCompletableFuture());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CacheException("Thread interrupted while invoking RPC", e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
cause.addSuppressed(new TraceException());
if (cause instanceof CacheException) {
throw ((CacheException) cause);
} else {
throw new CacheException("Unexpected exception replicating command", cause);
}
}
}
@Override
public CompletableFuture<Map<Address, Response>> invokeRemotelyAsync(Collection<Address> recipients,
ReplicableCommand rpc,
RpcOptions options) {
// Set the topology id of the command, in case we don't have it yet
setTopologyId(rpc);
CacheRpcCommand cacheRpc = toCacheRpcCommand(rpc);
long startTimeNanos = statisticsEnabled ? timeService.time() : 0;
CompletableFuture<Map<Address, Response>> invocation;
try {
// Using Transport.invokeCommand* would require us to duplicate the JGroupsTransport.invokeRemotelyAsync logic
invocation = t.invokeRemotelyAsync(recipients, cacheRpc,
ResponseMode.SYNCHRONOUS, options.timeUnit().toMillis(options.timeout()),
null, options.deliverOrder(),
configuration.clustering().cacheMode().isDistributed());
} catch (Exception e) {
CLUSTER.unexpectedErrorReplicating(e);
if (statisticsEnabled) {
replicationFailures.increment();
}
return rethrowAsCacheException(e);
}
return invocation.whenComplete((responseMap, throwable) -> {
if (statisticsEnabled) {
updateStatistics(startTimeNanos, responseMap, throwable);
}
});
}
private <T> T rethrowAsCacheException(Throwable throwable) {
if (throwable.getCause() != null && throwable instanceof CompletionException) {
throwable = throwable.getCause();
}
if (throwable instanceof CacheException) {
log.trace("Replication exception", throwable);
throw ((CacheException) throwable);
} else {
CLUSTER.unexpectedErrorReplicating(throwable);
throw new CacheException(throwable);
}
}
private CacheRpcCommand toCacheRpcCommand(ReplicableCommand command) {
checkTopologyId(command);
return command instanceof CacheRpcCommand ?
(CacheRpcCommand) command :
cf.wired().buildSingleRpcCommand((VisitableCommand) command);
}
@Override
public void sendTo(Address destination, ReplicableCommand command, DeliverOrder deliverOrder) {
// Set the topology id of the command, in case we don't have it yet
setTopologyId(command);
CacheRpcCommand cacheRpc = toCacheRpcCommand(command);
try {
t.sendTo(destination, cacheRpc, deliverOrder);
} catch (Exception e) {
errorReplicating(e);
}
}
@Override
public void sendToMany(Collection<Address> destinations, ReplicableCommand command, DeliverOrder deliverOrder) {
// Set the topology id of the command, in case we don't have it yet
setTopologyId(command);
CacheRpcCommand cacheRpc = toCacheRpcCommand(command);
try {
t.sendToMany(destinations, cacheRpc, deliverOrder);
} catch (Exception e) {
errorReplicating(e);
}
}
@Override
public void sendToAll(ReplicableCommand command, DeliverOrder deliverOrder) {
// Set the topology id of the command, in case we don't have it yet
setTopologyId(command);
CacheRpcCommand cacheRpc = toCacheRpcCommand(command);
try {
t.sendToAll(cacheRpc, deliverOrder);
} catch (Exception e) {
errorReplicating(e);
}
}
@Override
public <O> XSiteResponse<O> invokeXSite(XSiteBackup backup, XSiteReplicateCommand<O> command) {
if (!statisticsEnabled) {
return t.backupRemotely(backup, command);
}
XSiteResponse<O> rsp = t.backupRemotely(backup, command);
rsp.whenCompleted(xSiteResponseCompleted);
return rsp;
}
private void registerXSiteTime(XSiteBackup backup, long sentTimestamp, long durationNanos, Throwable ignored) {
if (durationNanos <= 0) {
// no network involved
return;
}
xSiteMetricsCollector.recordRequestSent(backup.getSiteName(), durationNanos, TimeUnit.NANOSECONDS);
}
private <T> T errorReplicating(Throwable t) {
CLUSTER.unexpectedErrorReplicating(t);
if (statisticsEnabled) {
replicationFailures.increment();
}
return rethrowAsCacheException(t);
}
@Override
public Transport getTransport() {
return t;
}
private void setTopologyId(ReplicableCommand command) {
if (command instanceof TopologyAffectedCommand) {
TopologyAffectedCommand topologyAffectedCommand = (TopologyAffectedCommand) command;
if (topologyAffectedCommand.getTopologyId() == -1) {
int currentTopologyId = distributionManager.getCacheTopology().getTopologyId();
if (log.isTraceEnabled()) {
log.tracef("Topology id missing on command %s, setting it to %d", command, currentTopologyId);
}
topologyAffectedCommand.setTopologyId(currentTopologyId);
}
}
}
// -------------------------------------------- JMX information -----------------------------------------------
@Override
@ManagedOperation(description = "Resets statistics gathered by this component", displayName = "Reset statistics")
public void resetStatistics() {
replicationCount.reset();
replicationFailures.reset();
totalReplicationTime.reset();
xSiteMetricsCollector.resetRequestsSent();
xSiteMetricsCollector.resetRequestReceived();
}
@ManagedAttribute(description = "Number of successful replications", displayName = "Number of successful replications", measurementType = MeasurementType.TRENDSUP)
public long getReplicationCount() {
return isStatisticsEnabled() ? replicationCount.sum() : -1;
}
@ManagedAttribute(description = "Number of failed replications", displayName = "Number of failed replications", measurementType = MeasurementType.TRENDSUP)
public long getReplicationFailures() {
return isStatisticsEnabled() ? replicationFailures.sum() : -1;
}
@ManagedAttribute(description = "Enables or disables the gathering of statistics by this component", displayName = "Statistics enabled", dataType = DataType.TRAIT, writable = true)
public boolean isStatisticsEnabled() {
return statisticsEnabled;
}
@Override
public boolean getStatisticsEnabled() {
return isStatisticsEnabled();
}
/**
* @deprecated We already have an attribute, we shouldn't have an operation for the same thing.
*/
@Override
@Deprecated
@ManagedOperation(displayName = "Enable/disable statistics. Deprecated, use the statisticsEnabled attribute instead.")
public void setStatisticsEnabled(@Parameter(name = "enabled", description = "Whether statistics should be enabled or disabled (true/false)") boolean statisticsEnabled) {
this.statisticsEnabled = statisticsEnabled;
}
@ManagedAttribute(description = "Successful replications as a ratio of total replications", displayName = "Successful replications ratio")
public String getSuccessRatio() {
double ration;
if (isStatisticsEnabled() && (ration = calculateSuccessRatio()) != 0) {
return NumberFormat.getInstance().format(ration * 100d) + "%";
}
return "N/A";
}
@ManagedAttribute(description = "Successful replications as a ratio of total replications in numeric double format", displayName = "Successful replication ratio", units = Units.PERCENTAGE)
public double getSuccessRatioFloatingPoint() {
return isStatisticsEnabled() ? calculateSuccessRatio() : 0;
}
private double calculateSuccessRatio() {
double totalCount = replicationCount.sum() + replicationFailures.sum();
return totalCount == 0 ? 0 : replicationCount.sum() / totalCount;
}
@ManagedAttribute(description = "The average time spent in the transport layer, in milliseconds", displayName = "Average time spent in the transport layer", units = Units.MILLISECONDS)
public long getAverageReplicationTime() {
long count = replicationCount.sum();
return isStatisticsEnabled() && count != 0 ? totalReplicationTime.sum() / count : 0;
}
@ManagedAttribute(description = "Retrieves the x-site view.", displayName = "Cross site (x-site) view", dataType = DataType.TRAIT)
public String getSitesView() {
Set<String> sitesView = t.getSitesView();
return sitesView != null ? sitesView.toString() : "N/A";
}
@ManagedAttribute(description = "Returns the average replication time, in milliseconds, for a cross-site replication request",
displayName = "Average Cross-Site replication time",
units = Units.MILLISECONDS)
public long getAverageXSiteReplicationTime() {
return isStatisticsEnabled() ?
xSiteMetricsCollector.getAvgRequestSentDuration(-1, TimeUnit.MILLISECONDS) :
-1;
}
@ManagedOperation(description = "Returns the average replication time, in milliseconds, for cross-site request sent to the remote site.",
displayName = "Average Cross-Site replication time to Site",
name = "AverageXSiteReplicationTimeTo")
public long getAverageXSiteReplicationTimeTo(
@Parameter(name = "dstSite", description = "Destination site name") String dstSite) {
return isStatisticsEnabled() ?
xSiteMetricsCollector.getAvgRequestSentDuration(dstSite, -1, TimeUnit.MILLISECONDS) :
-1;
}
@ManagedAttribute(description = "Returns the minimum replication time, in milliseconds, for a cross-site replication request",
displayName = "Minimum Cross-Site replication time",
units = Units.MILLISECONDS,
measurementType = MeasurementType.TRENDSDOWN)
public long getMinimumXSiteReplicationTime() {
return isStatisticsEnabled() ?
xSiteMetricsCollector.getMinRequestSentDuration(-1, TimeUnit.MILLISECONDS) :
-1;
}
@ManagedOperation(description = "Returns the minimum replication time, in milliseconds, for cross-site request sent to the remote site.",
displayName = "Minimum Cross-Site replication time to Site",
name = "MinimumXSiteReplicationTimeTo")
public long getMinimumXSiteReplicationTimeTo(
@Parameter(name = "dstSite", description = "Destination site name") String dstSite) {
return isStatisticsEnabled() ?
xSiteMetricsCollector.getMinRequestSentDuration(dstSite, -1, TimeUnit.MILLISECONDS) :
-1;
}
@ManagedAttribute(description = "Returns the maximum replication time, in milliseconds, for a cross-site replication request",
displayName = "Maximum Cross-Site replication time",
units = Units.MILLISECONDS,
measurementType = MeasurementType.TRENDSUP)
public long getMaximumXSiteReplicationTime() {
return isStatisticsEnabled() ?
xSiteMetricsCollector.getMaxRequestSentDuration(-1, TimeUnit.MILLISECONDS) :
-1;
}
@ManagedOperation(description = "Returns the maximum replication time, in milliseconds, for cross-site request sent to the remote site.",
displayName = "Maximum Cross-Site replication time to Site",
name = "MaximumXSiteReplicationTimeTo")
public long getMaximumXSiteReplicationTimeTo(
@Parameter(name = "dstSite", description = "Destination site name") String dstSite) {
return isStatisticsEnabled() ?
xSiteMetricsCollector.getMaxRequestSentDuration(dstSite, -1, TimeUnit.MILLISECONDS) :
-1;
}
@ManagedAttribute(description = "Returns the number of sync cross-site requests",
displayName = "Cross-Site replication requests",
measurementType = MeasurementType.TRENDSUP)
public long getNumberXSiteRequests() {
return isStatisticsEnabled() ? xSiteMetricsCollector.countRequestsSent() : 0;
}
@ManagedOperation(description = "Returns the number of cross-site requests sent to the remote site.",
displayName = "Number of Cross-Site request sent to site",
name = "NumberXSiteRequestsSentTo")
public long getNumberXSiteRequestsSentTo(
@Parameter(name = "dstSite", description = "Destination site name") String dstSite) {
return isStatisticsEnabled() ? xSiteMetricsCollector.countRequestsSent(dstSite) : 0;
}
@ManagedAttribute(description = "Returns the number of cross-site requests received from all nodes",
displayName = "Number of Cross-Site Requests Received from all sites",
measurementType = MeasurementType.TRENDSUP)
public long getNumberXSiteRequestsReceived() {
return isStatisticsEnabled() ? xSiteMetricsCollector.countRequestsReceived() : 0;
}
@ManagedOperation(description = "Returns the number of cross-site requests received from the remote site.",
displayName = "Number of Cross-Site request received from site",
name = "NumberXSiteRequestsReceivedFrom")
public long getNumberXSiteRequestsReceivedFrom(
@Parameter(name = "srcSite", description = "Originator site name") String srcSite) {
return isStatisticsEnabled() ? xSiteMetricsCollector.countRequestsReceived(srcSite) : 0;
}
@ManagedAttribute(description = "Cross Site Replication Times",
displayName = "Cross Site Replication Times",
dataType = DataType.TIMER,
units = Units.NANOSECONDS)
public void setCrossSiteReplicationTimes(TimerTracker timer) {
xSiteMetricsCollector.registerTimer(timer);
}
// mainly for unit testing
public void setTransport(Transport t) {
this.t = t;
}
@Override
public Address getAddress() {
return t != null ? t.getAddress() : null;
}
@Override
public int getTopologyId() {
CacheTopology cacheTopology = distributionManager.getCacheTopology();
return cacheTopology != null ? cacheTopology.getTopologyId() : -1;
}
@Override
public RpcOptions getSyncRpcOptions() {
return syncRpcOptions;
}
@Override
public List<Address> getMembers() {
return distributionManager.getCacheTopology().getMembers();
}
}
| 28,687
| 43.340031
| 191
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/rpc/RpcManager.java
|
package org.infinispan.remoting.rpc;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollector;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.remoting.transport.XSiteResponse;
import org.infinispan.remoting.transport.impl.MapResponseCollector;
import org.infinispan.xsite.XSiteBackup;
import org.infinispan.xsite.XSiteReplicateCommand;
/**
* Provides a mechanism for communicating with other caches in the cluster, by formatting and passing requests down to
* the registered {@link Transport}.
*
* @author Manik Surtani
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public interface RpcManager {
/**
* Invoke a command on a single node and pass the response to a {@link ResponseCollector}.
*
* If the target is the local node, the command is never executed and {@link ResponseCollector#finish()} is called directly.
*
* @since 9.2
*/
<T> CompletionStage<T> invokeCommand(Address target, ReplicableCommand command,
ResponseCollector<T> collector, RpcOptions rpcOptions);
/**
* Invoke a command on a collection of node and pass the responses to a {@link ResponseCollector}.
*
* If one of the targets is the local node, it is ignored. The command is only executed on the remote nodes.
*
* @since 9.2
*/
<T> CompletionStage<T> invokeCommand(Collection<Address> targets, ReplicableCommand command,
ResponseCollector<T> collector, RpcOptions rpcOptions);
/**
* Invoke a command on all the nodes in the cluster and pass the responses to a {@link ResponseCollector}.
*
* The command is not executed locally and it is not sent across RELAY2 bridges to remote sites.
*
* @since 9.2
*/
<T> CompletionStage<T> invokeCommandOnAll(ReplicableCommand command, ResponseCollector<T> collector,
RpcOptions rpcOptions);
/**
* Invoke a command on a collection of nodes and pass the responses to a {@link ResponseCollector}.
*
* The command is only sent immediately to the first target, and there is an implementation-dependent
* delay before sending the command to each target. There is no delay if the target responds or leaves
* the cluster. The remaining targets are skipped if {@link ResponseCollector#addResponse(Address, Response)}
* returns a non-{@code null} value.
*
* The command is only executed on the remote nodes.
*
* @since 9.2
*/
<T> CompletionStage<T> invokeCommandStaggered(Collection<Address> targets, ReplicableCommand command,
ResponseCollector<T> collector, RpcOptions rpcOptions);
/**
* Invoke different commands on a collection of nodes and pass the responses to a {@link ResponseCollector}.
*
* The command is only executed on the remote nodes and it is not executed in the local node even if it is in the {@code targets}.
*
* @since 9.2
*/
<T> CompletionStage<T> invokeCommands(Collection<Address> targets,
Function<Address, ReplicableCommand> commandGenerator,
ResponseCollector<T> collector, RpcOptions rpcOptions);
/**
* Block on a request and return its result.
*
* @since 9.2
*/
<T> T blocking(CompletionStage<T> request);
/**
* Invokes a command on remote nodes.
*
* @param recipients A list of nodes, or {@code null} to invoke the command on all the members of the cluster
* @param rpc The command to invoke
* @param options The invocation options
* @return A future that, when completed, returns the responses from the remote nodes.
* @deprecated since 11.0, use {@link #sendToMany(Collection, ReplicableCommand, DeliverOrder)} or
* {@link #invokeCommand(Collection, ReplicableCommand, ResponseCollector, RpcOptions)} instead.
*/
@Deprecated
default CompletableFuture<Map<Address, Response>> invokeRemotelyAsync(Collection<Address> recipients,
ReplicableCommand rpc, RpcOptions options) {
// Always perform with ResponseMode.SYNCHRONOUS as RpcOptions no longer allows ResponseMode to be passed
Collection<Address> targets = recipients != null ? recipients : getTransport().getMembers();
MapResponseCollector collector = MapResponseCollector.ignoreLeavers(false, targets.size());
return invokeCommand(recipients, rpc, collector, options).toCompletableFuture();
}
/**
* Asynchronously sends the {@link ReplicableCommand} to the destination using the specified {@link DeliverOrder}.
*
* @param destination the destination's {@link Address}.
* @param command the {@link ReplicableCommand} to send.
* @param deliverOrder the {@link DeliverOrder} to use.
*/
void sendTo(Address destination, ReplicableCommand command, DeliverOrder deliverOrder);
/**
* Asynchronously sends the {@link ReplicableCommand} to the set of destination using the specified {@link
* DeliverOrder}.
*
* @param destinations the collection of destination's {@link Address}. If {@code null}, it sends to all the members
* in the cluster.
* @param command the {@link ReplicableCommand} to send.
* @param deliverOrder the {@link DeliverOrder} to use.
*/
void sendToMany(Collection<Address> destinations, ReplicableCommand command, DeliverOrder deliverOrder);
/**
* Asynchronously sends the {@link ReplicableCommand} to the entire cluster.
*
* @since 9.2
*/
void sendToAll(ReplicableCommand command, DeliverOrder deliverOrder);
/**
* Sends the {@link XSiteReplicateCommand} to a remote site.
* <p>
* If {@link XSiteBackup#isSync()} returns {@code false}, the {@link XSiteResponse} is only completed when the an
* ACK from the remote site is received. The invoker needs to make sure not to wait for the {@link XSiteResponse}.
*
* @param backup The site to where the command is sent.
* @param command The command to send.
* @return A {@link XSiteResponse} that is completed when the request is completed.
*/
<O> XSiteResponse<O> invokeXSite(XSiteBackup backup, XSiteReplicateCommand<O> command);
/**
* @return a reference to the underlying transport.
*/
Transport getTransport();
/**
* Returns members of a cluster scoped to the cache owning this RpcManager. Note that this List
* is always a subset of {@link Transport#getMembers()}
*
* @return a list of cache scoped cluster members
*/
List<Address> getMembers();
/**
* Returns the address associated with this RpcManager or null if not part of the cluster.
*/
Address getAddress();
/**
* Returns the current topology id. As opposed to the viewId which is updated whenever the cluster changes,
* the topologyId is updated when a new cache instance is started or removed - this doesn't necessarily coincide
* with a node being added/removed to the cluster.
*/
int getTopologyId();
/**
* @return The default options for synchronous remote invocations.
*/
RpcOptions getSyncRpcOptions();
/**
* @return The default options for total order remote invocations.
*/
default RpcOptions getTotalSyncRpcOptions() {
throw new UnsupportedOperationException();
}
}
| 7,911
| 40.862434
| 133
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/rpc/ResponseFilter.java
|
package org.infinispan.remoting.rpc;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.transport.Address;
/**
* A mechanism of filtering RPC responses. Used with the RPC manager.
*
* @author Manik Surtani
* @since 4.0
*/
public interface ResponseFilter {
/**
* Determines whether a response from a given sender should be added to the response list of the request
*
* @param response The response (usually a serializable value)
* @param sender The sender of response
* @return True if we should add the response to the response list of a request, otherwise false. In the latter case,
* we don't add the response to the response list.
*/
boolean isAcceptable(Response response, Address sender);
/**
* Right after calling {@link #isAcceptable(Response, Address)}, this method is called to see whether we are done
* with the request and can unblock the caller
*
* @return False if the request is done, otherwise true
*/
boolean needMoreResponses();
}
| 1,059
| 32.125
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/rpc/RpcOptions.java
|
package org.infinispan.remoting.rpc;
import java.util.concurrent.TimeUnit;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
/**
* Classes that wraps all the configuration parameters to configure a remote invocation.
*
* @author Pedro Ruivo
* @since 5.3
*/
public class RpcOptions {
private final long timeout;
private final TimeUnit unit;
private final DeliverOrder deliverOrder;
/**
* @since 9.2
*/
public RpcOptions(DeliverOrder deliverOrder, long timeout, TimeUnit unit) {
if (unit == null) {
throw new IllegalArgumentException("TimeUnit cannot be null");
} else if (deliverOrder == null) {
throw new IllegalArgumentException("DeliverMode cannot be null");
}
this.timeout = timeout;
this.unit = unit;
this.deliverOrder = deliverOrder;
}
/**
* @return the timeout value to give up.
*/
public long timeout() {
return timeout;
}
/**
* @return the {@link TimeUnit} in which the timeout value is.
*/
public TimeUnit timeUnit() {
return unit;
}
/**
* @return the {@link org.infinispan.remoting.inboundhandler.DeliverOrder}.
*/
public DeliverOrder deliverOrder() {
return deliverOrder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RpcOptions options = (RpcOptions) o;
return timeout == options.timeout &&
deliverOrder == options.deliverOrder &&
unit == options.unit;
}
@Override
public int hashCode() {
int result = (int) (timeout ^ (timeout >>> 32));
result = 31 * result + unit.hashCode();
result = 31 * result + deliverOrder.hashCode();
return result;
}
@Override
public String toString() {
return "RpcOptions{" +
"timeout=" + timeout +
", unit=" + unit +
", deliverOrder=" + deliverOrder +
'}';
}
}
| 2,018
| 23.325301
| 88
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/rpc/ResponseMode.java
|
package org.infinispan.remoting.rpc;
/**
* Represents different handling mechanisms when dealing with remote command responses.
* These include waiting for responses from all nodes in the cluster ({@link ResponseMode#SYNCHRONOUS}}),
* not waiting for any responses at all ({@link ResponseMode#ASYNCHRONOUS}}),
* or waiting for first valid response ({@link ResponseMode#WAIT_FOR_VALID_RESPONSE}})
*
* @author Manik Surtani
* @since 4.0
*/
public enum ResponseMode {
SYNCHRONOUS,
/**
* Most commands should use this mode to prevent SuspectExceptions when we are doing a broadcast
* (or anycast that translates to JGroups broadcast). That would cause SuspectExceptions in SYNCHRONOUS mode
* in a situation when:
* 1) node is leaving, we want to address all living members but while topology was already updated, view was not yet
* 2) we use asymmetric cluster so the other nodes respond with CacheNotFoundResponse to such broadcast
*/
SYNCHRONOUS_IGNORE_LEAVERS,
ASYNCHRONOUS,
WAIT_FOR_VALID_RESPONSE;
public boolean isSynchronous() {
return !isAsynchronous();
}
public boolean isAsynchronous() {
return this == ASYNCHRONOUS;
}
}
| 1,201
| 35.424242
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/package-info.java
|
/**
* Transports handle the low-level networking, used by the remoting components.
*/
package org.infinispan.remoting.transport;
| 131
| 25.4
| 79
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/ValidSingleResponseCollector.java
|
package org.infinispan.remoting.transport;
import org.infinispan.commons.util.Experimental;
import org.infinispan.remoting.RpcException;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.ExceptionResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.ValidResponse;
/**
* @author Dan Berindei
* @since 9.1
*/
@Experimental
public abstract class ValidSingleResponseCollector<T> implements ResponseCollector<T> {
@Override
public final T addResponse(Address sender, Response response) {
if (response instanceof ValidResponse) {
return withValidResponse(sender, ((ValidResponse) response));
} else if (response instanceof ExceptionResponse) {
return withException(sender, ((ExceptionResponse) response).getException());
} else if (response instanceof CacheNotFoundResponse) {
return targetNotFound(sender);
} else {
// Should never happen
return withException(sender, new RpcException("Unknown response type: " + response));
}
}
@Override
public final T finish() {
// addResponse returned null, that means we want the final result to be null.
return null;
}
protected T withException(Address sender, Exception exception) {
throw ResponseCollectors.wrapRemoteException(sender, exception);
}
protected abstract T withValidResponse(Address sender, ValidResponse response);
protected abstract T targetNotFound(Address sender);
}
| 1,557
| 33.622222
| 94
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/AbstractDelegatingTransport.java
|
package org.infinispan.remoting.transport;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commons.CacheConfigurationException;
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.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.rpc.ResponseFilter;
import org.infinispan.remoting.rpc.ResponseMode;
import org.infinispan.remoting.transport.raft.RaftManager;
import org.infinispan.util.logging.Log;
import org.infinispan.xsite.XSiteBackup;
import org.infinispan.xsite.XSiteReplicateCommand;
/**
* Designed to be overwrite.
*
* @author Pedro Ruivo
* @since 6.0
*/
@Scope(Scopes.GLOBAL)
public abstract class AbstractDelegatingTransport implements Transport {
protected final Transport actual;
protected AbstractDelegatingTransport(Transport actual) {
this.actual = actual;
}
@Deprecated
@Override
public Map<Address, Response> invokeRemotely(Collection<Address> recipients, ReplicableCommand rpcCommand, ResponseMode mode, long timeout, ResponseFilter responseFilter, DeliverOrder deliverOrder, boolean anycast) throws Exception {
return actual.invokeRemotely(recipients, rpcCommand, mode, timeout, responseFilter, deliverOrder, anycast);
}
@Deprecated
@Override
public Map<Address, Response> invokeRemotely(Map<Address, ReplicableCommand> rpcCommands, ResponseMode mode, long timeout, boolean usePriorityQueue, ResponseFilter responseFilter, boolean totalOrder, boolean anycast) throws Exception {
return actual.invokeRemotely(rpcCommands, mode, timeout, usePriorityQueue, responseFilter, totalOrder, anycast);
}
@Deprecated
@Override
public Map<Address, Response> invokeRemotely(Map<Address, ReplicableCommand> rpcCommands, ResponseMode mode, long timeout, ResponseFilter responseFilter, DeliverOrder deliverOrder, boolean anycast) throws Exception {
return actual.invokeRemotely(rpcCommands, mode, timeout, responseFilter, deliverOrder, anycast);
}
@Override
public CompletableFuture<Map<Address, Response>> invokeRemotelyAsync(Collection<Address> recipients,
ReplicableCommand rpcCommand,
ResponseMode mode, long timeout,
ResponseFilter responseFilter,
DeliverOrder deliverOrder,
boolean anycast) throws Exception {
return actual.invokeRemotelyAsync(recipients, rpcCommand, mode, timeout, responseFilter, deliverOrder, anycast);
}
@Override
public void sendTo(Address destination, ReplicableCommand rpcCommand, DeliverOrder deliverOrder) throws Exception {
actual.sendTo(destination, rpcCommand, deliverOrder);
}
@Override
public void sendToMany(Collection<Address> destinations, ReplicableCommand rpcCommand, DeliverOrder deliverOrder) throws Exception {
actual.sendToMany(destinations, rpcCommand, deliverOrder);
}
@Override
public void sendToAll(ReplicableCommand rpcCommand, DeliverOrder deliverOrder) throws Exception {
actual.sendToAll(rpcCommand, deliverOrder);
}
@Override
public BackupResponse backupRemotely(Collection<XSiteBackup> backups, XSiteReplicateCommand rpcCommand) throws Exception {
return actual.backupRemotely(backups, rpcCommand);
}
@Override
public <O> XSiteResponse<O> backupRemotely(XSiteBackup backup, XSiteReplicateCommand<O> rpcCommand) {
return actual.backupRemotely(backup, rpcCommand);
}
@Override
public boolean isCoordinator() {
return actual.isCoordinator();
}
@Override
public Address getCoordinator() {
return actual.getCoordinator();
}
@Override
public Address getAddress() {
return actual.getAddress();
}
@Override
public List<Address> getPhysicalAddresses() {
return actual.getPhysicalAddresses();
}
@Override
public List<Address> getMembers() {
return actual.getMembers();
}
@Override
public List<Address> getMembersPhysicalAddresses() {
return actual.getMembersPhysicalAddresses();
}
@Override
public boolean isMulticastCapable() {
return actual.isMulticastCapable();
}
@Override
public void checkCrossSiteAvailable() throws CacheConfigurationException {
actual.checkCrossSiteAvailable();
}
@Override
public String localSiteName() {
return actual.localSiteName();
}
@Start
@Override
public void start() {
actual.start();
}
@Stop
@Override
public void stop() {
actual.stop();
}
@Override
public int getViewId() {
return actual.getViewId();
}
@Override
public CompletableFuture<Void> withView(int expectedViewId) {
return actual.withView(expectedViewId);
}
@Deprecated
@Override
public void waitForView(int viewId) throws InterruptedException {
actual.waitForView(viewId);
}
@Override
public Log getLog() {
return actual.getLog();
}
public Transport getDelegate() {
return actual;
}
@Override
public Set<String> getSitesView() {
return actual.getSitesView();
}
@Override
public boolean isSiteCoordinator() {
return actual.isSiteCoordinator();
}
@Override
public Collection<Address> getRelayNodesAddress() {
return actual.getRelayNodesAddress();
}
@Override
public <T> CompletionStage<T> invokeCommand(Address target, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
return actual.invokeCommand(target, command, collector, deliverOrder, timeout, unit);
}
@Override
public <T> CompletionStage<T> invokeCommand(Collection<Address> targets, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
return actual.invokeCommand(targets, command, collector, deliverOrder, timeout, unit);
}
@Override
public <T> CompletionStage<T> invokeCommandOnAll(ReplicableCommand command, ResponseCollector<T> collector,
DeliverOrder deliverOrder, long timeout, TimeUnit unit) {
return actual.invokeCommandOnAll(command, collector, deliverOrder, timeout, unit);
}
@Override
public <T> CompletionStage<T> invokeCommandStaggered(Collection<Address> targets, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
return actual.invokeCommandStaggered(targets, command, collector, deliverOrder, timeout, unit);
}
@Override
public <T> CompletionStage<T> invokeCommands(Collection<Address> targets,
Function<Address, ReplicableCommand> commandGenerator,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout,
TimeUnit timeUnit) {
return actual.invokeCommands(targets, commandGenerator, collector, deliverOrder, timeout, timeUnit);
}
@Override
public RaftManager raftManager() {
return actual.raftManager();
}
}
| 8,244
| 34.386266
| 238
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/ValidResponseCollector.java
|
package org.infinispan.remoting.transport;
import org.infinispan.commons.util.Experimental;
import org.infinispan.remoting.RpcException;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.ExceptionResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.ValidResponse;
/**
* Base class for response collectors, splitting responses into valid responses, exception responses, and target missing.
*
* Returning a non-{@code null} value or throwing an exception from any of the
* {@link #addValidResponse(Address, ValidResponse)}, {@link #addException(Address, Exception)}, or
* {@link #addTargetNotFound(Address)} methods will complete the request.
* If all invocations return {@code null}, the request will be completed with the result of {@link #finish()}.
*
* @author Dan Berindei
* @since 9.1
*/
@Experimental
public abstract class ValidResponseCollector<T> implements ResponseCollector<T> {
@Override
public final T addResponse(Address sender, Response response) {
if (response instanceof ValidResponse) {
return addValidResponse(sender, ((ValidResponse) response));
} else if (response instanceof ExceptionResponse) {
return addException(sender, ((ExceptionResponse) response).getException());
} else if (response instanceof CacheNotFoundResponse) {
return addTargetNotFound(sender);
} else {
addException(sender, new RpcException("Unknown response type: " + response));
}
return null;
}
@Override
public abstract T finish();
/**
* Process a valid response from a target.
*
* @return {@code null} to continue waiting for response, non-{@code null} to complete with that value.
*/
protected abstract T addValidResponse(Address sender, ValidResponse response);
/**
* Process a target leaving the cluster or stopping the cache.
*
* @return {@code null} to continue waiting for response, non-{@code null} to complete with that value.
*/
protected abstract T addTargetNotFound(Address sender);
/**
* Process an exception from a target.
*
* @return {@code null} to continue waiting for responses (the default), non-{@code null} to complete with that
* value.
*/
protected abstract T addException(Address sender, Exception exception);
}
| 2,406
| 37.206349
| 121
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/TopologyAwareAddress.java
|
package org.infinispan.remoting.transport;
/**
* Wraps a TopologyUUID JGroups address
*
* @author Bela Ban
* @since 5.0
*/
public interface TopologyAwareAddress extends Address {
String getSiteId();
String getRackId();
String getMachineId();
boolean isSameSite(TopologyAwareAddress addr);
boolean isSameRack(TopologyAwareAddress addr);
boolean isSameMachine(TopologyAwareAddress addr);
}
| 413
| 22
| 55
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/SiteAddress.java
|
package org.infinispan.remoting.transport;
import java.util.Objects;
/**
* Implementation {@link Address} that contains the site name.
*
* @author Pedro Ruivo
* @since 13.0
*/
public class SiteAddress implements Address {
private final String name;
public SiteAddress(String name) {
this.name = Objects.requireNonNull(name, "Site's name is mandatory");
}
@Override
public int compareTo(@SuppressWarnings("NullableProblems") Address o) {
if (o instanceof SiteAddress) {
return name.compareTo(((SiteAddress) o).name);
}
return -1;
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SiteAddress that = (SiteAddress) o;
return name.equals(that.name);
}
@Override
public String toString() {
return "SiteAddress{" +
"name='" + name + '\'' +
'}';
}
}
| 1,078
| 20.156863
| 75
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/XSiteAsyncAckListener.java
|
package org.infinispan.remoting.transport;
/**
* A listener to be notified when an asynchronous cross-site request is completed.
*
* @author Pedro Ruivo
* @since 10.0
*/
@FunctionalInterface
public interface XSiteAsyncAckListener {
/**
* Invoked when an ack for an asynchronous request is received.
* <p>
* If an exception is received (could be a network exception or an exception from the remote site), the {@code
* throwable} is set to a non {@code null} value.
*
* @param sendTimestampNanos The timestamp when the request was sent to the remote site (nanoseconds).
* @param siteName The remote site name.
* @param throwable The exception received (including timeouts and site unreachable) or {@code null}.
*/
void onAckReceived(long sendTimestampNanos, String siteName, Throwable throwable);
}
| 866
| 33.68
| 113
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/AbstractTransport.java
|
package org.infinispan.remoting.transport;
import static org.infinispan.util.logging.Log.CLUSTER;
import org.infinispan.commons.CacheException;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.partitionhandling.AvailabilityException;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.ExceptionResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.SuccessfulResponse;
import org.infinispan.remoting.transport.jgroups.SuspectException;
import org.infinispan.statetransfer.OutdatedTopologyException;
import org.infinispan.util.logging.Log;
/**
* Common transport-related behaviour
*
* @author Manik Surtani
* @version 4.2
* @deprecated Since 9.1, please implement {@link Transport} directly.
*/
@Deprecated
@Scope(Scopes.GLOBAL)
public abstract class AbstractTransport implements Transport {
@Inject protected GlobalConfiguration configuration;
public Response checkResponse(Object responseObject, Address sender, boolean ignoreCacheNotFoundResponse) {
Log log = getLog();
if (responseObject == null) {
return SuccessfulResponse.SUCCESSFUL_EMPTY_RESPONSE;
} else if (responseObject instanceof Response) {
Response response = (Response) responseObject;
if (response instanceof ExceptionResponse) {
ExceptionResponse exceptionResponse = (ExceptionResponse) response;
Exception e = exceptionResponse.getException();
if (e instanceof SuspectException) throw CLUSTER.thirdPartySuspected(sender, (SuspectException) e);
if (e instanceof AvailabilityException || e instanceof OutdatedTopologyException) throw (CacheException) e;
// if we have any application-level exceptions make sure we throw them!!
throw CLUSTER.remoteException(sender, e);
} else if (!ignoreCacheNotFoundResponse && response instanceof CacheNotFoundResponse) {
throw new SuspectException("Cache not running on node " + sender, sender);
}
return response;
} else {
// All other responses should trigger an exception
Class<?> responseClass = responseObject.getClass();
log.tracef("Unexpected response object type from %s: %s", sender, responseClass);
throw new CacheException(String.format("Unexpected response object type from %s: %s", sender, responseClass));
}
}
}
| 2,637
| 43.711864
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/BackupResponse.java
|
package org.infinispan.remoting.transport;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.LongConsumer;
/**
* Represents a response from a backup replication call.
*
* @author Mircea Markus
* @since 5.2
*/
public interface BackupResponse {
void waitForBackupToFinish() throws Exception;
Map<String,Throwable> getFailedBackups();
/**
* Returns the list of sites where the backups failed due to a bridge communication error (as opposed to an
* error caused by Infinispan, e.g. due to a lock acquisition timeout).
*/
Set<String> getCommunicationErrors();
/**
* Return the time in millis when this operation was initiated.
*/
long getSendTimeMillis();
boolean isEmpty();
/**
* Registers a listener that is notified when the cross-site request is finished.
* <p>
* The parameter is the time spent in the network in milliseconds.
*
* @param timeElapsedConsumer The {@link Consumer} to be invoke.
*/
void notifyFinish(LongConsumer timeElapsedConsumer);
/**
* Invokes {@link XSiteAsyncAckListener} for each ack received from an asynchronous cross site request.
*
* If the request times-out or failed to be sent, the listeners receives a non-null {@link Throwable}.
*/
void notifyAsyncAck(XSiteAsyncAckListener listener);
/**
* @return {@code true} if the request for the remote site is synchronous.
*/
boolean isSync(String siteName);
}
| 1,510
| 26.981481
| 110
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/AggregateBackupResponse.java
|
package org.infinispan.remoting.transport;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.LongConsumer;
/**
* @author Mircea Markus
* @since 5.2
*/
public class AggregateBackupResponse implements BackupResponse {
final Collection<BackupResponse> responses;
public AggregateBackupResponse(BackupResponse onePcResponse, BackupResponse twoPcResponse) {
responses = new ArrayList<>(2);
if (onePcResponse != null) responses.add(onePcResponse);
if (twoPcResponse != null) responses.add(twoPcResponse);
}
@Override
public void waitForBackupToFinish() throws Exception {
for (BackupResponse br : responses) {
br.waitForBackupToFinish();
}
}
@Override
public Map<String, Throwable> getFailedBackups() {
Map<String, Throwable> result = new HashMap<>();
for (BackupResponse br : responses) {
result.putAll(br.getFailedBackups());
}
return result;
}
@Override
public Set<String> getCommunicationErrors() {
Set<String> result = new HashSet<>();
for (BackupResponse br : responses) {
result.addAll(br.getCommunicationErrors());
}
return result;
}
@Override
public long getSendTimeMillis() {
long min = Long.MAX_VALUE;
for (BackupResponse br: responses) {
min = Math.min(br.getSendTimeMillis(), min);
}
return min;
}
@Override
public String toString() {
return "AggregateBackupResponse{" +
"responses=" + responses +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof AggregateBackupResponse)) return false;
AggregateBackupResponse that = (AggregateBackupResponse) o;
return responses != null ? responses.equals(that.responses) : that.responses == null;
}
@Override
public int hashCode() {
return responses != null ? responses.hashCode() : 0;
}
@Override
public boolean isEmpty() {
for (BackupResponse br : responses) {
if (!br.isEmpty()) return false;
}
return true;
}
@Override
public void notifyFinish(LongConsumer timeElapsedConsumer) {
for (BackupResponse br : responses) {
br.notifyFinish(timeElapsedConsumer);
}
}
@Override
public void notifyAsyncAck(XSiteAsyncAckListener listener) {
for (BackupResponse br : responses) {
br.notifyAsyncAck(listener);
}
}
@Override
public boolean isSync(String siteName) {
for (BackupResponse br : responses) {
if (br.isSync(siteName)) {
return true;
}
}
return false;
}
}
| 2,821
| 23.973451
| 95
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/XSiteResponse.java
|
package org.infinispan.remoting.transport;
import java.util.concurrent.CompletionStage;
import org.infinispan.xsite.XSiteBackup;
/**
* An extension to {@link CompletionStage} with {@link #whenCompleted(XSiteResponseCompleted)}.
* <p>
* It provides a method to register the cross-site request statistics and data for the {@link
* org.infinispan.xsite.OfflineStatus}.
* <p>
* Note: do not complete the {@link java.util.concurrent.CompletableFuture} returned by {@link #toCompletableFuture()}.
*
* @author Pedro Ruivo
* @since 10.0
*/
public interface XSiteResponse<O> extends CompletionStage<O> {
void whenCompleted(XSiteResponseCompleted xSiteResponseCompleted);
@FunctionalInterface
interface XSiteResponseCompleted {
void onCompleted(XSiteBackup backup, long sendTimeNanos, long durationNanos, Throwable throwable);
}
}
| 855
| 29.571429
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/AbstractRequest.java
|
package org.infinispan.remoting.transport;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.infinispan.remoting.transport.impl.Request;
import org.infinispan.remoting.transport.impl.RequestRepository;
/**
* A remote invocation request.
*
* <p>Thread-safety: This class and its sub-classes are thread-safe. They use the {@code ResponseCollector}'s monitor
* for synchronization, so that collectors usually don't need any explicit synchronization.</p>
*
* @author Dan Berindei
* @since 9.1
*/
public abstract class AbstractRequest<T> extends CompletableFuture<T> implements Callable<Void>, Request<T> {
protected final ResponseCollector<T> responseCollector;
protected final long requestId;
protected final RequestRepository repository;
private volatile Future<?> timeoutFuture = null;
private volatile long timeoutMs = -1;
protected AbstractRequest(long requestId, ResponseCollector<T> responseCollector, RequestRepository repository) {
this.responseCollector = responseCollector;
this.repository = repository;
this.requestId = requestId;
}
/**
* Called when the timeout task scheduled with {@link #setTimeout(ScheduledExecutorService, long, TimeUnit)} expires.
*/
protected abstract void onTimeout();
@Override
public final long getRequestId() {
return requestId;
}
/**
* Schedule a timeout task on the given executor, and complete the request with a {@link
* org.infinispan.util.concurrent.TimeoutException}
* when the task runs.
*
* If a timeout task was already registered with this request, it is cancelled.
*/
public void setTimeout(ScheduledExecutorService timeoutExecutor, long timeout, TimeUnit unit) {
cancelTimeoutTask();
ScheduledFuture<Void> timeoutFuture = timeoutExecutor.schedule(this, timeout, unit);
setTimeoutFuture(timeoutFuture, unit.toMillis(timeout));
}
public void cancel(Exception exception) {
completeExceptionally(exception);
}
// Override complete(), completeExceptionally(), and cancel() to cancel the timeout task and remove the request from the map
@Override
public boolean complete(T value) {
cancelTimeoutTask();
repository.removeRequest(requestId);
return super.complete(value);
}
@Override
public boolean completeExceptionally(Throwable ex) {
cancelTimeoutTask();
repository.removeRequest(requestId);
return super.completeExceptionally(ex);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
cancelTimeoutTask();
repository.removeRequest(requestId);
return super.cancel(mayInterruptIfRunning);
}
// Implement Callable for the timeout task
@Override
public final Void call() throws Exception {
onTimeout();
return null;
}
private void setTimeoutFuture(Future<?> timeoutFuture, long timeout) {
this.timeoutFuture = timeoutFuture;
this.timeoutMs = timeout;
if (isDone()) {
timeoutFuture.cancel(false);
}
}
private void cancelTimeoutTask() {
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
timeoutMs = -1;
}
}
public long getTimeoutMs() {
return timeoutMs;
}
}
| 3,487
| 30.423423
| 127
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/LocalModeAddress.java
|
package org.infinispan.remoting.transport;
/**
* Represents the local node's address.
*
* @since 9.0
*/
public class LocalModeAddress implements Address {
public static final Address INSTANCE = new LocalModeAddress();
private LocalModeAddress() {
}
@Override
public String toString() {
return "<local>";
}
@Override
public int compareTo(Address o) {
return o == this ? 0 : -1;
}
}
| 429
| 16.2
| 65
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/Address.java
|
package org.infinispan.remoting.transport;
/**
* A destination for an Infinispan command or operation.
*
* @author Manik Surtani
* @since 4.0
*/
public interface Address extends Comparable<Address> {
Address[] EMPTY_ARRAY = new Address[0];
}
| 251
| 20
| 56
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/ResponseCollectors.java
|
package org.infinispan.remoting.transport;
import static org.infinispan.util.logging.Log.CLUSTER;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.util.Experimental;
import org.infinispan.partitionhandling.AvailabilityException;
import org.infinispan.remoting.transport.jgroups.SuspectException;
import org.infinispan.statetransfer.OutdatedTopologyException;
/**
* @author Dan Berindei
* @since 9.1
*/
@Experimental
public class ResponseCollectors {
public static CacheException wrapRemoteException(Address sender, Throwable exception) {
CacheException e;
if (exception instanceof SuspectException) {
e = CLUSTER.thirdPartySuspected(sender, (SuspectException) exception);
} else if (exception instanceof AvailabilityException || exception instanceof OutdatedTopologyException) {
e = (CacheException) exception;
} else {
// if we have any application-level exceptions make sure we throw them!!
e = CLUSTER.remoteException(sender, exception);
}
return e;
}
public static SuspectException remoteNodeSuspected(Address sender) {
return CLUSTER.remoteNodeSuspected(sender);
}
}
| 1,196
| 34.205882
| 112
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/ResponseCollector.java
|
package org.infinispan.remoting.transport;
import org.infinispan.commons.util.Experimental;
import org.infinispan.remoting.responses.Response;
/**
* A representation of a request's responses.
*
* <p>Thread-safety: The request will invoke {@link #addResponse(Address, Response)} and
* {@link #finish()} while holding the collector's monitor, so
* implementations don't normally need explicit synchronization.</p>
*
* @author Dan Berindei
* @since 9.1
*/
@Experimental
public interface ResponseCollector<T> {
/**
* Called when a response is received, or when a target node becomes unavailable.
*
* <p>When a target node leaves the cluster, this method is called with a
* {@link org.infinispan.remoting.responses.CacheNotFoundResponse}.</p>
*
* <p>Should return a non-{@code null} result if the request should complete with that value, or {@code null}
* if it should wait for more responses.
* If the method throws an exception, the request will be completed with that exception.
*
* If the last response is received and {@code addResponse()} still returns {@code null},
* {@link #finish()} will also be called to obtain a result.
*
* <p>Thread safety: {@code addResponse()} will *not* be called concurrently from multiple threads,
* and the request will not be completed while {@code addResponse()} is running.</p>
*/
T addResponse(Address sender, Response response);
/**
* Called after {@link #addResponse(Address, Response)} returns {@code null} for the last response.
*
* <p>If {@code finish()} finishes normally, the request will complete with its return value
* (even if {@code null}).
* If {@code finish()} throws an exception, the request will complete exceptionally with that exception,
* wrapped in a {@link java.util.concurrent.CompletionException} (unless the exception is already a
* {@link java.util.concurrent.CompletionException}).
* </p>
*/
T finish();
}
| 1,989
| 40.458333
| 112
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/Transport.java
|
package org.infinispan.remoting.transport;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.api.Lifecycle;
import org.infinispan.commons.util.Experimental;
import org.infinispan.commons.util.Util;
import org.infinispan.commons.util.logging.TraceException;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.rpc.ResponseFilter;
import org.infinispan.remoting.rpc.ResponseMode;
import org.infinispan.remoting.transport.raft.RaftManager;
import org.infinispan.util.concurrent.AggregateCompletionStage;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.Log;
import org.infinispan.xsite.XSiteBackup;
import org.infinispan.xsite.XSiteReplicateCommand;
/**
* An interface that provides a communication link with remote caches. Also allows remote caches to invoke commands on
* this cache instance.
*
* @author Manik Surtani
* @author Galder Zamarreño
* @since 4.0
*/
@Scope(Scopes.GLOBAL)
public interface Transport extends Lifecycle {
/**
* Invokes an RPC call on other caches in the cluster.
*
* @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to the
* entire cluster.
* @param rpcCommand the cache command to invoke
* @param mode the response mode to use
* @param timeout a timeout after which to throw a replication exception. implementations.
* @param responseFilter a response filter with which to filter out failed/unwanted/invalid responses.
* @param deliverOrder the {@link org.infinispan.remoting.inboundhandler.DeliverOrder}.
* @param anycast used when {@param totalOrder} is {@code true}, it means that it must use TOA instead of
* TOB.
* @return a map of responses from each member contacted.
* @throws Exception in the event of problems.
* @deprecated Since 9.2, please use {@link #invokeCommand(Collection, ReplicableCommand, ResponseCollector, DeliverOrder, long, TimeUnit)} instead.
*/
@Deprecated
default Map<Address, Response> invokeRemotely(Collection<Address> recipients, ReplicableCommand rpcCommand,
ResponseMode mode, long timeout,
ResponseFilter responseFilter, DeliverOrder deliverOrder,
boolean anycast) throws Exception {
CompletableFuture<Map<Address, Response>> future = invokeRemotelyAsync(recipients, rpcCommand, mode,
timeout, responseFilter, deliverOrder,
anycast);
try {
//no need to set a timeout for the future. The rpc invocation is guaranteed to complete within the timeout
// milliseconds
return CompletableFutures.await(future);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
cause.addSuppressed(new TraceException());
throw Util.rewrapAsCacheException(cause);
}
}
CompletableFuture<Map<Address, Response>> invokeRemotelyAsync(Collection<Address> recipients,
ReplicableCommand rpcCommand,
ResponseMode mode, long timeout,
ResponseFilter responseFilter,
DeliverOrder deliverOrder,
boolean anycast) throws Exception;
/**
* Asynchronously sends the {@link ReplicableCommand} to the destination using the specified {@link DeliverOrder}.
*
* @param destination the destination's {@link Address}.
* @param rpcCommand the {@link ReplicableCommand} to send.
* @param deliverOrder the {@link DeliverOrder} to use.
* @throws Exception if there was problem sending the request.
*/
void sendTo(Address destination, ReplicableCommand rpcCommand, DeliverOrder deliverOrder) throws Exception;
/**
* Asynchronously sends the {@link ReplicableCommand} to the set of destination using the specified {@link
* DeliverOrder}.
*
* @param destinations the collection of destination's {@link Address}. If {@code null}, it sends to all the members
* in the cluster.
* @param rpcCommand the {@link ReplicableCommand} to send.
* @param deliverOrder the {@link DeliverOrder} to use.
* @throws Exception if there was problem sending the request.
*/
void sendToMany(Collection<Address> destinations, ReplicableCommand rpcCommand, DeliverOrder deliverOrder) throws Exception;
/**
* Asynchronously sends the {@link ReplicableCommand} to the entire cluster.
*
* @since 9.2
*/
@Experimental
default void sendToAll(ReplicableCommand rpcCommand, DeliverOrder deliverOrder) throws Exception {
sendToMany(null, rpcCommand, deliverOrder);
}
/**
* @deprecated Use {@link #invokeRemotely(Map, ResponseMode, long, ResponseFilter, DeliverOrder, boolean)} instead
*/
@Deprecated
default Map<Address, Response> invokeRemotely(Map<Address, ReplicableCommand> rpcCommands, ResponseMode mode,
long timeout,
boolean usePriorityQueue, ResponseFilter responseFilter,
boolean totalOrder,
boolean anycast) throws Exception {
if (totalOrder) {
throw new UnsupportedOperationException();
}
DeliverOrder deliverOrder = usePriorityQueue ? DeliverOrder.NONE : DeliverOrder.PER_SENDER;
return invokeRemotely(rpcCommands, mode, timeout, responseFilter, deliverOrder, anycast);
}
/**
* @deprecated Since 9.2, please use {@link #invokeRemotelyAsync(Collection, ReplicableCommand, ResponseMode, long, ResponseFilter, DeliverOrder, boolean)} instead.
*/
@Deprecated
default Map<Address, Response> invokeRemotely(Map<Address, ReplicableCommand> rpcCommands, ResponseMode mode,
long timeout, ResponseFilter responseFilter,
DeliverOrder deliverOrder, boolean anycast) throws Exception {
// This overload didn't have an async version, so implement it on top of the regular invokeRemotelyAsync
Map<Address, Response> result = new ConcurrentHashMap<>(rpcCommands.size());
ResponseFilter partResponseFilter = new ResponseFilter() {
@Override
public boolean isAcceptable(Response response, Address sender) {
// Guarantee collector.addResponse() isn't called concurrently
synchronized (result) {
result.put(sender, response);
return responseFilter.isAcceptable(response, sender);
}
}
@Override
public boolean needMoreResponses() {
return responseFilter.needMoreResponses();
}
};
List<CompletableFuture<Map<Address, Response>>> futures = new ArrayList<>(rpcCommands.size());
for (Map.Entry<Address, ReplicableCommand> e : rpcCommands.entrySet()) {
futures.add(invokeRemotelyAsync(Collections.singleton(e.getKey()), e.getValue(), mode,
timeout, partResponseFilter, deliverOrder, anycast));
}
try {
//no need to set a timeout for the future. The rpc invocation is guaranteed to complete within the timeout
// milliseconds
CompletableFutures.await(CompletableFuture.allOf(futures.toArray(new CompletableFuture[rpcCommands.size()])));
return result;
} catch (ExecutionException e) {
Throwable cause = e.getCause();
cause.addSuppressed(new TraceException());
throw Util.rewrapAsCacheException(cause);
}
}
/**
* @deprecated since 10.0. Use {@link #backupRemotely(XSiteBackup, XSiteReplicateCommand)} instead.
*/
@Deprecated
BackupResponse backupRemotely(Collection<XSiteBackup> backups, XSiteReplicateCommand rpcCommand) throws Exception;
/**
* Sends a cross-site request to a remote site.
* <p>
* Currently, no reply values are supported. Or the request completes successfully or it throws an {@link
* Exception}.
* <p>
* If {@link XSiteBackup#isSync()} returns {@code false}, the {@link XSiteResponse} is only completed when the an
* ACK from the remote site is received. The invoker needs to make sure not to wait for the {@link XSiteResponse}.
*
* @param backup The remote site.
* @param rpcCommand The command to send.
* @return A {@link XSiteResponse} that is completed when the request is completed.
*/
<O> XSiteResponse<O> backupRemotely(XSiteBackup backup, XSiteReplicateCommand<O> rpcCommand);
/**
* @return true if the current Channel is the coordinator of the cluster.
*/
boolean isCoordinator();
/**
* @return the Address of the current coordinator.
*/
Address getCoordinator();
/**
* Retrieves the current cache instance's network address
*
* @return an Address
*/
Address getAddress();
/**
* Retrieves the current cache instance's physical network addresses. Some implementations might differentiate
* between logical and physical addresses in which case, this method allows clients to query the physical ones
* associated with the logical address. Implementations where logical and physical address are the same will simply
* return a single entry List that contains the same Address as {@link #getAddress()}.
*
* @return an List of Address
*/
List<Address> getPhysicalAddresses();
/**
* Returns a list of members in the current cluster view.
*
* @return a list of members. Typically, this would be defensively copied.
*/
List<Address> getMembers();
/**
* Returns physical addresses of members in the current cluster view.
*
* @return a list of physical addresses
*/
List<Address> getMembersPhysicalAddresses();
/**
* Tests whether the transport supports true multicast
*
* @return true if the transport supports true multicast
*/
boolean isMulticastCapable();
/**
* Checks if this {@link Transport} is able to perform cross-site requests.
*
* @throws CacheConfigurationException if cross-site isn't available.
*/
void checkCrossSiteAvailable() throws CacheConfigurationException;
/**
* @return The local site name or {@code null} if this {@link Transport} cannot make cross-site requests.
*/
String localSiteName();
/**
* @return The local node name, defaults to the local node address.
*/
default String localNodeName() {
return getAddress().toString();
}
@Override
void start();
@Override
void stop();
/**
* @throws org.infinispan.commons.CacheException if the transport has been stopped.
*/
int getViewId();
/**
* @return A {@link CompletableFuture} that completes when the transport has installed the expected view.
*/
CompletableFuture<Void> withView(int expectedViewId);
/**
* @deprecated Since 9.0, please use {@link #withView(int)} instead.
*/
@Deprecated
void waitForView(int viewId) throws InterruptedException;
Log getLog();
/**
* check if the transport has configured with total order deliver properties (has the sequencer in JGroups
* protocol stack.
*
* @deprecated Total order support dropped
*/
@Deprecated
default void checkTotalOrderSupported() {
//no-op
}
/**
* Get the view of interconnected sites.
* If no cross site replication has been configured, this method returns null.
*
* Inspecting the site view can be useful to see if the different sites
* have managed to join each other, which is pre-requisite to get cross
* replication working.
*
* @return set containing the connected sites, or null if no cross site
* replication has been enabled.
*/
Set<String> getSitesView();
/**
* @return {@code true} if this node is a cross-site replication coordinator.
*/
boolean isSiteCoordinator();
/**
* @return The current site coordinators {@link Address}.
*/
Collection<Address> getRelayNodesAddress();
/**
* Invoke a command on a single node and pass the response to a {@link ResponseCollector}.
* <p>
* If the target is the local node, the command is never executed and {@link ResponseCollector#finish()} is called directly.
*
* @since 9.1
*/
@Experimental
default <T> CompletionStage<T> invokeCommand(Address target, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
// Implement the new methods on top of invokeRemotelyAsync to support custom implementations
return invokeCommand(Collections.singleton(target), command, collector, deliverOrder, timeout, unit);
}
/**
* Invoke a command on a collection of node and pass the responses to a {@link ResponseCollector}.
* <p>
* If one of the targets is the local node, it is ignored. The command is only executed on the remote nodes.
*
* @since 9.1
*/
@Experimental
default <T> CompletionStage<T> invokeCommand(Collection<Address> targets, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
// Implement the new methods on top of invokeRemotelyAsync to support custom implementations
try {
return invokeRemotelyAsync(targets, command, ResponseMode.SYNCHRONOUS_IGNORE_LEAVERS,
unit.toMillis(timeout), null, deliverOrder, false)
.thenApply(map -> {
for (Map.Entry<Address, Response> e : map.entrySet()) {
T result = collector.addResponse(e.getKey(), e.getValue());
if (result != null)
return result;
}
return collector.finish();
});
} catch (Exception e) {
throw Util.rewrapAsCacheException(e);
}
}
/**
* Invoke a command on all the nodes in the cluster and pass the responses to a {@link ResponseCollector}.
* <p>
* The command is not executed locally and it is not sent across RELAY2 bridges to remote sites.
*
* @since 9.1
*/
@Experimental
default <T> CompletionStage<T> invokeCommandOnAll(ReplicableCommand command, ResponseCollector<T> collector,
DeliverOrder deliverOrder, long timeout, TimeUnit unit) {
return invokeCommand(getMembers(), command, collector, deliverOrder, timeout, unit);
}
/**
* Invoke a command on all the nodes in the cluster and pass the responses to a {@link ResponseCollector}.
* <p>
* he command is not executed locally and it is not sent across RELAY2 bridges to remote sites.
*
* @since 9.3
*/
@Experimental
default <T> CompletionStage<T> invokeCommandOnAll(Collection<Address> requiredTargets, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
return invokeCommand(requiredTargets, command, collector, deliverOrder, timeout, unit);
}
/**
* Invoke a command on a collection of nodes and pass the responses to a {@link ResponseCollector}.
* <p>
* The command is only sent immediately to the first target, and there is an implementation-dependent
* delay before sending the command to each target. There is no delay if the target responds or leaves
* the cluster. The remaining targets are skipped if {@link ResponseCollector#addResponse(Address, Response)}
* returns a non-{@code null} value.
* <p>
* The command is only executed on the remote nodes.
*
* @since 9.1
*/
@Experimental
default <T> CompletionStage<T> invokeCommandStaggered(Collection<Address> targets, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
// Implement the new methods on top of invokeRemotelyAsync to support custom implementations
AtomicReference<Object> result = new AtomicReference<>(null);
try {
ResponseFilter responseFilter = new ResponseFilter() {
@Override
public boolean isAcceptable(Response response, Address sender) {
// Guarantee collector.addResponse() isn't called concurrently
synchronized (result) {
if (result.get() != null)
return false;
T t = collector.addResponse(sender, response);
result.set(t);
return t != null;
}
}
@Override
public boolean needMoreResponses() {
return result.get() == null;
}
};
return invokeRemotelyAsync(targets, command, ResponseMode.WAIT_FOR_VALID_RESPONSE,
unit.toMillis(timeout), responseFilter, deliverOrder, false)
.thenApply(map -> {
synchronized (result) {
if (result.get() != null) {
return (T) result.get();
} else {
// Prevent further calls to collector.addResponse()
result.set(new Object());
return collector.finish();
}
}
});
} catch (Exception e) {
throw Util.rewrapAsCacheException(e);
}
}
/**
* Invoke different commands on a collection of nodes and pass the responses to a {@link ResponseCollector}.
* <p>
* The command is only executed on the remote nodes.
*
* @deprecated Introduced in 9.1, but replaced in 9.2 with
* {@link #invokeCommands(Collection, Function, ResponseCollector, DeliverOrder, long, TimeUnit)}.
*/
@Deprecated
default <T> CompletionStage<T> invokeCommands(Collection<Address> targets,
Function<Address, ReplicableCommand> commandGenerator,
ResponseCollector<T> responseCollector, long timeout,
DeliverOrder deliverOrder) {
return invokeCommands(targets, commandGenerator, responseCollector, deliverOrder, timeout, TimeUnit.MILLISECONDS);
}
/**
* Invoke different commands on a collection of nodes and pass the responses to a {@link ResponseCollector}.
* <p>
* The command is only executed on the remote nodes.
*
* @since 9.2
*/
@Experimental
default <T> CompletionStage<T> invokeCommands(Collection<Address> targets,
Function<Address, ReplicableCommand> commandGenerator,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit timeUnit) {
AtomicReference<Object> result = new AtomicReference<>(null);
ResponseCollector<T> partCollector = new ResponseCollector<>() {
@Override
public T addResponse(Address sender, Response response) {
synchronized (this) {
if (result.get() != null)
return null;
result.set(collector.addResponse(sender, response));
return null;
}
}
@Override
public T finish() {
// Do nothing when individual commands finish
return null;
}
};
AggregateCompletionStage<Void> allStage = CompletionStages.aggregateCompletionStage();
for (Address target : targets) {
allStage.dependsOn(invokeCommand(target, commandGenerator.apply(target), partCollector, deliverOrder,
timeout, timeUnit));
}
return allStage.freeze().thenApply(v -> {
synchronized (partCollector) {
if (result.get() != null) {
return (T) result.get();
} else {
return collector.finish();
}
}
});
}
/**
* @return The {@link RaftManager} instance,
*/
RaftManager raftManager();
}
| 22,170
| 41.47318
| 167
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/JGroupsAddress.java
|
package org.infinispan.remoting.transport.jgroups;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Set;
import org.infinispan.commons.marshall.InstanceReusingAdvancedExternalizer;
import org.infinispan.commons.marshall.MarshallingException;
import org.infinispan.commons.marshall.ProtoStreamTypeIds;
import org.infinispan.commons.util.Util;
import org.infinispan.marshall.core.Ids;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoTypeId;
import org.infinispan.remoting.transport.Address;
/**
* An encapsulation of a JGroups Address
*
* @author Manik Surtani
* @since 4.0
*/
@ProtoTypeId(ProtoStreamTypeIds.JGROUPS_ADDRESS)
public class JGroupsAddress implements Address {
protected final org.jgroups.Address address;
private final int hashCode;
public JGroupsAddress(final org.jgroups.Address address) {
if (address == null)
throw new IllegalArgumentException("Address shall not be null");
this.address = address;
this.hashCode = address.hashCode();
}
@ProtoFactory
JGroupsAddress(byte[] bytes) throws IOException {
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
this.address = org.jgroups.util.Util.readAddress(in);
this.hashCode = address.hashCode();
} catch (ClassNotFoundException e) {
throw new MarshallingException(e);
}
}
@ProtoField(1)
byte[] getBytes() throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos)) {
org.jgroups.util.Util.writeAddress(address, out);
return baos.toByteArray();
}
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JGroupsAddress that = (JGroupsAddress) o;
return hashCode == that.hashCode && address.equals(that.address);
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public String toString() {
return String.valueOf(address);
}
public org.jgroups.Address getJGroupsAddress() {
return address;
}
@Override
public int compareTo(Address o) {
JGroupsAddress oa = (JGroupsAddress) o;
return address.compareTo(oa.address);
}
public static final class Externalizer extends InstanceReusingAdvancedExternalizer<JGroupsAddress> {
public Externalizer() {
super(false);
}
@Override
public void doWriteObject(ObjectOutput output, JGroupsAddress address) throws IOException {
try {
org.jgroups.util.Util.writeAddress(address.address, output);
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
public JGroupsAddress doReadObject(ObjectInput unmarshaller) throws IOException, ClassNotFoundException {
try {
// Note: Use org.jgroups.Address, not the concrete UUID class.
// Otherwise applications that only use local caches would have to bundle the JGroups jar,
// because the verifier needs to check the arguments of fromJGroupsAddress
// even if this method is never called.
org.jgroups.Address address = org.jgroups.util.Util.readAddress(unmarshaller);
return (JGroupsAddress) JGroupsAddressCache.fromJGroupsAddress(address);
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
public Integer getId() {
return Ids.JGROUPS_ADDRESS;
}
@Override
public Set<Class<? extends JGroupsAddress>> getTypeClasses() {
return Util.<Class<? extends JGroupsAddress>>asSet(JGroupsAddress.class);
}
}
}
| 4,114
| 30.653846
| 111
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/package-info.java
|
/**
* A transport implementation based on <a href="http://www.jgroups.org">JGroups</a>.
*/
package org.infinispan.remoting.transport.jgroups;
| 144
| 28
| 84
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/FileJGroupsChannelConfigurator.java
|
package org.infinispan.remoting.transport.jgroups;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import org.infinispan.commons.util.StringPropertyReplacer;
import org.jgroups.JChannel;
import org.jgroups.conf.ProtocolConfiguration;
import org.jgroups.conf.XmlConfigurator;
/**
* A JGroups {@link JGroupsChannelConfigurator} which loads configuration from an XML file supplied as an {@link InputStream}
*
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 10.0
**/
public class FileJGroupsChannelConfigurator extends AbstractJGroupsChannelConfigurator {
private final String name;
private final String path;
private final Properties properties;
private final List<ProtocolConfiguration> stack;
public FileJGroupsChannelConfigurator(String name, String path, InputStream is, Properties properties) throws IOException {
this.name = name;
this.path = path;
this.stack = XmlConfigurator.getInstance(is).getProtocolStack();
this.properties = properties;
}
@Override
public String getProtocolStackString() {
return stack.toString();
}
@Override
public List<ProtocolConfiguration> getProtocolStack() {
this.stack.forEach(c -> StringPropertyReplacer.replaceProperties(c.getProperties(), properties));
return stack;
}
public String getName() {
return name;
}
@Override
public JChannel createChannel(String name) throws Exception {
return amendChannel(new JChannel(this));
}
public String getPath() {
return path;
}
}
| 1,615
| 27.857143
| 126
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/ClusterView.java
|
package org.infinispan.remoting.transport.jgroups;
import java.util.List;
import java.util.Set;
import org.infinispan.commons.util.ImmutableHopscotchHashSet;
import org.infinispan.commons.util.Immutables;
import org.infinispan.remoting.transport.Address;
/**
* Information about the JGroups cluster.
*
* @author Dan Berindei
* @since 9.1
*/
public class ClusterView {
static final int INITIAL_VIEW_ID = -1;
static final int FINAL_VIEW_ID = Integer.MAX_VALUE;
private final int viewId;
private final List<Address> members;
private final Set<Address> membersSet;
private final Address coordinator;
private final boolean isCoordinator;
ClusterView(int viewId, List<Address> members, Address self) {
this.viewId = viewId;
this.members = Immutables.immutableListCopy(members);
this.membersSet = new ImmutableHopscotchHashSet<>(members);
if (!members.isEmpty()) {
this.coordinator = members.get(0);
this.isCoordinator = coordinator.equals(self);
} else {
this.coordinator = null;
this.isCoordinator = false;
}
}
public int getViewId() {
return viewId;
}
public boolean isViewIdAtLeast(int expectedViewId) {
return expectedViewId <= viewId;
}
public boolean isStopped() {
return viewId == FINAL_VIEW_ID;
}
public List<Address> getMembers() {
return members;
}
public Set<Address> getMembersSet() {
return membersSet;
}
public Address getCoordinator() {
return coordinator;
}
public boolean isCoordinator() {
return isCoordinator;
}
boolean contains(Address address) {
return getMembersSet().contains(address);
}
@Override
public String toString() {
return coordinator + "|" + viewId + members;
}
}
| 1,820
| 22.960526
| 65
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/JGroupsChannelConfigurator.java
|
package org.infinispan.remoting.transport.jgroups;
import org.jgroups.ChannelListener;
import org.jgroups.JChannel;
import org.jgroups.conf.ProtocolStackConfigurator;
import org.jgroups.util.SocketFactory;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 10.0
**/
public interface JGroupsChannelConfigurator extends ProtocolStackConfigurator {
String getName();
JChannel createChannel(String name) throws Exception;
void setSocketFactory(SocketFactory socketFactory);
void addChannelListener(ChannelListener listener);
}
| 562
| 25.809524
| 79
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/StaggeredRequest.java
|
package org.infinispan.remoting.transport.jgroups;
import java.util.Collection;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.impl.MultiTargetRequest;
import org.infinispan.remoting.transport.impl.RequestRepository;
import org.infinispan.remoting.transport.ResponseCollector;
import net.jcip.annotations.GuardedBy;
/**
* @author Dan Berindei
* @since 9.1
*/
public class StaggeredRequest<T> extends MultiTargetRequest<T> {
private final ReplicableCommand command;
private final DeliverOrder deliverOrder;
private final JGroupsTransport transport;
@GuardedBy("responseCollector")
private long deadline;
@GuardedBy("responseCollector")
private int targetIndex;
StaggeredRequest(ResponseCollector<T> responseCollector, long requestId, RequestRepository repository,
Collection<Address> targets, Address excludedTarget, ReplicableCommand command,
DeliverOrder deliverOrder, long timeout, TimeUnit unit, JGroupsTransport transport) {
super(responseCollector, requestId, repository, targets, excludedTarget);
this.command = command;
this.deliverOrder = deliverOrder;
this.transport = transport;
this.deadline = transport.timeService.expectedEndTime(timeout, unit);
}
@Override
public void setTimeout(ScheduledExecutorService timeoutExecutor, long timeout, TimeUnit unit) {
throw new UnsupportedOperationException("Timeout can only be set with sendFirstMessage!");
}
@Override
public synchronized void onResponse(Address sender, Response response) {
super.onResponse(sender, response);
sendNextMessage();
}
@Override
protected void onTimeout() {
// Don't call super.onTimeout() if it's just a stagger timeout
boolean isFinalTimeout;
synchronized (responseCollector) {
isFinalTimeout = targetIndex >= getTargetsSize();
}
if (isFinalTimeout) {
super.onTimeout();
} else {
sendNextMessage();
}
}
void sendNextMessage() {
try {
Address target = null;
boolean isFinalTarget;
// Need synchronization because sendNextMessage can be called both directly and from addResponse()
synchronized (responseCollector) {
if (isDone() || targetIndex >= getTargetsSize()) {
return;
}
// Skip over targets that are no longer in the cluster view
while (target == null && targetIndex < getTargetsSize()) {
target = getTarget(targetIndex++);
}
if (target == null) {
// The final targets were removed because they have left the cluster,
// but the request is not yet complete because we're still waiting for a response
// from one of the other targets (i.e. we are being called from onTimeout).
// We don't need to send another message, just wait for the real timeout to expire.
long delayNanos = transport.getTimeService().remainingTime(deadline, TimeUnit.NANOSECONDS);
super.setTimeout(transport.getTimeoutExecutor(), delayNanos, TimeUnit.NANOSECONDS);
return;
}
isFinalTarget = targetIndex >= getTargetsSize();
}
// Sending may block in flow-control or even in TCP, so we must do it outside the critical section
transport.sendCommand(target, command, requestId, deliverOrder, true, false);
// Scheduling the timeout task may also block
// If this is the last target, set the request timeout at the deadline
// Otherwise, schedule a timeout task to send a staggered request to the next target
long delayNanos = transport.getTimeService().remainingTime(deadline, TimeUnit.NANOSECONDS);
if (!isFinalTarget) {
delayNanos = delayNanos / 10 / getTargetsSize();
}
super.setTimeout(transport.getTimeoutExecutor(), delayNanos, TimeUnit.NANOSECONDS);
} catch (Exception e) {
completeExceptionally(e);
}
}
}
| 4,401
| 37.614035
| 107
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/JGroupsBackupResponse.java
|
package org.infinispan.remoting.transport.jgroups;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static org.infinispan.commons.util.Util.formatString;
import static org.infinispan.commons.util.Util.prettyPrintTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.LongConsumer;
import org.infinispan.commons.time.TimeService;
import org.infinispan.remoting.CacheUnreachableException;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.transport.BackupResponse;
import org.infinispan.remoting.transport.XSiteAsyncAckListener;
import org.infinispan.util.concurrent.TimeoutException;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.commons.util.logging.TraceException;
import org.infinispan.xsite.XSiteBackup;
import org.jgroups.UnreachableException;
/**
* @author Mircea Markus
* @since 5.2
*/
public class JGroupsBackupResponse implements BackupResponse {
private static Log log = LogFactory.getLog(JGroupsBackupResponse.class);
private final Map<XSiteBackup, CompletableFuture<ValidResponse>> backupCalls;
private Map<String, Throwable> errors;
private Set<String> communicationErrors;
private final TimeService timeService;
//there might be an significant difference in time between when the message is sent and when the actual wait
// happens. Track that and adjust the timeouts accordingly.
private final long sendTimeNanos;
private volatile LongConsumer timeElapsedConsumer = value -> {
};
public JGroupsBackupResponse(Map<XSiteBackup, CompletableFuture<ValidResponse>> backupCalls,
TimeService timeService) {
this.backupCalls = Objects.requireNonNull(backupCalls);
this.timeService = timeService;
sendTimeNanos = timeService.time();
}
@Override
public void waitForBackupToFinish() throws Exception {
long deductFromTimeout = timeService.timeDuration(sendTimeNanos, MILLISECONDS);
errors = new HashMap<>(backupCalls.size());
long elapsedTime = 0;
boolean hasSyncBackups = false;
for (Map.Entry<XSiteBackup, CompletableFuture<ValidResponse>> entry : backupCalls.entrySet()) {
XSiteBackup xSiteBackup = entry.getKey();
if (!xSiteBackup.isSync()) {
continue;
}
hasSyncBackups = true;
long timeout = xSiteBackup.getTimeout();
String siteName = xSiteBackup.getSiteName();
if (timeout > 0) { //0 means wait forever
timeout -= deductFromTimeout;
timeout -= elapsedTime;
if (timeout <= 0 && !entry.getValue().isDone() ) {
log.tracef("Timeout period %d exhausted with site %s", xSiteBackup.getTimeout(), siteName);
errors.put(siteName, newTimeoutException(xSiteBackup.getTimeout(), xSiteBackup));
addCommunicationError(siteName);
continue;
}
}
long startNanos = timeService.time();
Response response = null;
try {
response = entry.getValue().get(timeout, MILLISECONDS);
} catch (java.util.concurrent.TimeoutException te) {
errors.put(siteName, newTimeoutException(xSiteBackup.getTimeout(), xSiteBackup));
addCommunicationError(siteName);
} catch (ExecutionException ue) {
Throwable cause = ue.getCause();
cause.addSuppressed(new TraceException());
log.tracef(cause, "Communication error with site %s", siteName);
errors.put(siteName, filterException(cause));
addCommunicationError(siteName);
} finally {
elapsedTime += timeService.timeDuration(startNanos, MILLISECONDS);
}
log.tracef("Received response from site %s: %s", siteName, response);
}
if (hasSyncBackups) {
timeElapsedConsumer.accept(timeService.timeDuration(sendTimeNanos, MILLISECONDS));
}
}
private void addCommunicationError(String siteName) {
if (communicationErrors == null) //only create lazily as we don't expect communication errors to be the norm
communicationErrors = new HashSet<>(1);
communicationErrors.add(siteName);
}
@Override
public Set<String> getCommunicationErrors() {
return communicationErrors == null ?
Collections.emptySet() : communicationErrors;
}
@Override
public long getSendTimeMillis() {
return NANOSECONDS.toMillis(sendTimeNanos);
}
@Override
public boolean isEmpty() {
return backupCalls.keySet().stream().noneMatch(XSiteBackup::isSync);
}
@Override
public void notifyFinish(LongConsumer timeElapsedConsumer) {
this.timeElapsedConsumer = Objects.requireNonNull(timeElapsedConsumer);
}
@Override
public Map<String, Throwable> getFailedBackups() {
return errors;
}
private TimeoutException newTimeoutException(long timeout, XSiteBackup xSiteBackup) {
return new TimeoutException(formatString("Timed out after %s waiting for a response from %s",
prettyPrintTime(timeout), xSiteBackup));
}
@Override
public String toString() {
return "JGroupsBackupResponse{" +
"backupCalls=" + backupCalls +
", errors=" + errors +
", communicationErrors=" + communicationErrors +
", sendTimeNanos=" + sendTimeNanos +
'}';
}
private Throwable filterException(Throwable throwable) {
if (throwable instanceof UnreachableException) {
return new CacheUnreachableException((UnreachableException) throwable);
}
return throwable;
}
@Override
public void notifyAsyncAck(XSiteAsyncAckListener listener) {
XSiteAsyncAckListener nonNullListener = Objects.requireNonNull(listener);
for (Map.Entry<XSiteBackup, CompletableFuture<ValidResponse>> entry : backupCalls.entrySet()) {
XSiteBackup backup = entry.getKey();
if (backup.isSync()) {
continue;
}
// TODO whenCompleteAsync? currently not needed...
entry.getValue().whenComplete((response, throwable) -> nonNullListener
.onAckReceived(sendTimeNanos, backup.getSiteName(), throwable));
}
}
@Override
public boolean isSync(String siteName) {
for (XSiteBackup backup : backupCalls.keySet()) {
if (backup.getSiteName().equals(siteName)) {
return backup.isSync();
}
}
return false;
}
}
| 6,906
| 36.134409
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/AbstractJGroupsChannelConfigurator.java
|
package org.infinispan.remoting.transport.jgroups;
import java.util.ArrayList;
import java.util.List;
import org.jgroups.ChannelListener;
import org.jgroups.JChannel;
import org.jgroups.stack.Protocol;
import org.jgroups.util.SocketFactory;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 13.0
**/
public abstract class AbstractJGroupsChannelConfigurator implements JGroupsChannelConfigurator {
private SocketFactory socketFactory;
protected List<ChannelListener> channelListeners = new ArrayList<>(2);
@Override
public void setSocketFactory(SocketFactory socketFactory) {
this.socketFactory = socketFactory;
}
public SocketFactory getSocketFactory() {
return socketFactory;
}
protected JChannel amendChannel(JChannel channel) {
if (socketFactory != null) {
Protocol protocol = channel.getProtocolStack().getTopProtocol();
protocol.setSocketFactory(socketFactory);
}
for(ChannelListener listener : channelListeners) {
channel.addChannelListener(listener);
}
return channel;
}
public void addChannelListener(ChannelListener channelListener) {
channelListeners.add(channelListener);
}
}
| 1,226
| 26.886364
| 96
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/EmbeddedJGroupsChannelConfigurator.java
|
package org.infinispan.remoting.transport.jgroups;
import static org.infinispan.util.logging.Log.CONFIG;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.global.JGroupsConfiguration;
import org.infinispan.xsite.XSiteNamedCache;
import org.jgroups.ChannelListener;
import org.jgroups.JChannel;
import org.jgroups.conf.ProtocolConfiguration;
import org.jgroups.conf.ProtocolStackConfigurator;
import org.jgroups.protocols.relay.RELAY2;
import org.jgroups.protocols.relay.config.RelayConfig;
import org.jgroups.stack.Configurator;
import org.jgroups.stack.Protocol;
import org.jgroups.util.SocketFactory;
import org.jgroups.util.StackType;
/**
* A JGroups {@link ProtocolStackConfigurator} which
*
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 10.0
**/
public class EmbeddedJGroupsChannelConfigurator extends AbstractJGroupsChannelConfigurator {
private static final String PROTOCOL_PREFIX = "org.jgroups.protocols.";
private final String name;
private final String parent;
private JGroupsConfiguration jgroupsConfiguration;
private final List<ProtocolConfiguration> stack;
private final RemoteSites remoteSites;
public EmbeddedJGroupsChannelConfigurator(String name, List<ProtocolConfiguration> stack, RemoteSites remoteSites) {
this(name, stack, remoteSites, null);
}
public EmbeddedJGroupsChannelConfigurator(String name, List<ProtocolConfiguration> stack, RemoteSites remoteSites, String parent) {
this.name = name;
this.stack = stack;
this.remoteSites = remoteSites;
this.parent = parent;
}
public void setConfiguration(JGroupsConfiguration configuration) {
jgroupsConfiguration = configuration;
}
@Override
public String getProtocolStackString() {
return getProtocolStack().toString();
}
@Override
public List<ProtocolConfiguration> getProtocolStack() {
return combineStack(jgroupsConfiguration.configurator(parent), stack);
}
public List<ProtocolConfiguration> getUncombinedProtocolStack() {
return stack;
}
public String getName() {
return name;
}
@Override
public JChannel createChannel(String name) throws Exception {
StackType stackType = org.jgroups.util.Util.getIpStackType();
List<ProtocolConfiguration> actualStack = combineStack(jgroupsConfiguration.configurator(parent), stack);
List<Protocol> protocols = new ArrayList<>(actualStack.size());
boolean hasRelay2 = false;
for (ProtocolConfiguration c : actualStack) {
Protocol protocol;
try {
String className = PROTOCOL_PREFIX + c.getProtocolName();
protocol = Util.getInstanceStrict(className, getClass().getClassLoader());
} catch (ClassNotFoundException e) {
protocol = Util.getInstanceStrict(c.getProtocolName(), getClass().getClassLoader());
}
ProtocolConfiguration configuration = new ProtocolConfiguration(protocol.getName(), c.getProperties());
Configurator.initializeAttrs(protocol, configuration, stackType);
protocols.add(protocol);
if (protocol instanceof RELAY2) {
hasRelay2 = true;
// Process remote sites if any
RELAY2 relay2 = (RELAY2) protocol;
RemoteSites actualSites = getRemoteSites();
if (actualSites.remoteSites.size() == 0) {
throw CONFIG.jgroupsRelayWithoutRemoteSites(name);
}
for (Map.Entry<String, RemoteSite> remoteSite : actualSites.remoteSites.entrySet()) {
JGroupsChannelConfigurator configurator = jgroupsConfiguration.configurator(remoteSite.getValue().stack);
SocketFactory socketFactory = getSocketFactory();
String remoteCluster = remoteSite.getValue().cluster;
if (remoteCluster == null) {
remoteCluster = actualSites.defaultCluster;
}
if (socketFactory instanceof NamedSocketFactory) {
// Create a new NamedSocketFactory using the remote cluster name
socketFactory = new NamedSocketFactory((NamedSocketFactory) socketFactory, remoteCluster);
}
configurator.setSocketFactory(socketFactory);
for(ChannelListener listener : channelListeners) {
configurator.addChannelListener(listener);
}
RelayConfig.SiteConfig siteConfig = new RelayConfig.SiteConfig(remoteSite.getKey());
siteConfig.addBridge(new RelayConfig.BridgeConfig(remoteCluster) {
@Override
public JChannel createChannel() throws Exception {
// TODO The bridge channel is created lazily, and Infinispan doesn't see any errors
return configurator.createChannel(getClusterName());
}
});
relay2.addSite(remoteSite.getKey(), siteConfig);
}
}
}
if (!hasRelay2 && hasSites()) {
throw CONFIG.jgroupsRemoteSitesWithoutRelay(name);
}
return amendChannel(new JChannel(protocols));
}
private static List<ProtocolConfiguration> combineStack(JGroupsChannelConfigurator baseStack, List<ProtocolConfiguration> stack) {
List<ProtocolConfiguration> actualStack = new ArrayList<>(stack.size());
if (baseStack != null) {
// We copy the protocols and properties from the base stack. This will recursively perform inheritance
for (ProtocolConfiguration originalProtocol : baseStack.getProtocolStack()) {
ProtocolConfiguration protocol = new ProtocolConfiguration(originalProtocol.getProtocolName(), new HashMap<>(originalProtocol.getProperties()));
actualStack.add(protocol);
}
}
// We process this stack's rules
for (ProtocolConfiguration protocol : stack) {
String protocolName = protocol.getProtocolName();
int position = findProtocol(protocolName, actualStack);
EmbeddedJGroupsChannelConfigurator.StackCombine mode = position < 0 ? StackCombine.APPEND : StackCombine.COMBINE;
// See if there is a "stack.*" strategy
String stackCombine = protocol.getProperties().remove("stack.combine");
if (stackCombine != null) {
mode = EmbeddedJGroupsChannelConfigurator.StackCombine.valueOf(stackCombine);
}
String stackPosition = protocol.getProperties().remove("stack.position");
switch (mode) {
case APPEND:
assertNoStackPosition(mode, stackPosition);
actualStack.add(protocol);
break;
case COMBINE:
assertNoStackPosition(mode, stackPosition);
assertExisting(mode, protocolName, position);
// Combine/overwrite properties
actualStack.get(position).getProperties().putAll(protocol.getProperties());
break;
case REMOVE:
assertNoStackPosition(mode, stackPosition);
assertExisting(mode, protocolName, position);
actualStack.remove(position);
break;
case REPLACE:
if (stackPosition != null) {
position = findProtocol(stackPosition, actualStack);
assertExisting(mode, stackPosition, position);
} else {
assertExisting(mode, protocolName, position);
}
actualStack.set(position, protocol);
break;
case INSERT_BEFORE:
case INSERT_BELOW:
if (stackPosition == null) {
throw CONFIG.jgroupsInsertRequiresPosition(protocolName);
}
position = findProtocol(stackPosition, actualStack);
assertExisting(mode, stackPosition, position);
actualStack.add(position, protocol);
break;
case INSERT_AFTER:
case INSERT_ABOVE:
if (stackPosition == null) {
throw CONFIG.jgroupsInsertRequiresPosition(protocolName);
}
position = findProtocol(stackPosition, actualStack);
assertExisting(mode, stackPosition, position);
actualStack.add(position + 1, protocol);
break;
}
}
return actualStack;
}
private void combineSites(Map<String, RemoteSite> sites) {
JGroupsChannelConfigurator parentConfigurator = jgroupsConfiguration.configurator(parent);
if (parentConfigurator instanceof EmbeddedJGroupsChannelConfigurator) {
((EmbeddedJGroupsChannelConfigurator) parentConfigurator).combineSites(sites);
}
if (remoteSites != null) {
sites.putAll(remoteSites.remoteSites);
}
}
private boolean hasSites() {
if (remoteSites != null && !remoteSites.remoteSites.isEmpty()) {
return true;
}
if (parent == null) {
return false;
}
// let's see if the parent has remote sites
Map<String, RemoteSite> sites = new HashMap<>(4);
JGroupsChannelConfigurator parentConfigurator = jgroupsConfiguration.configurator(parent);
if (parentConfigurator instanceof EmbeddedJGroupsChannelConfigurator) {
((EmbeddedJGroupsChannelConfigurator) parentConfigurator).combineSites(sites);
}
return !sites.isEmpty();
}
private static void assertNoStackPosition(EmbeddedJGroupsChannelConfigurator.StackCombine mode, String stackAfter) {
if (stackAfter != null) {
throw CONFIG.jgroupsNoStackPosition(mode.name());
}
}
private static void assertExisting(EmbeddedJGroupsChannelConfigurator.StackCombine mode, String protocolName, int position) {
if (position < 0) {
throw CONFIG.jgroupsNoSuchProtocol(protocolName, mode.name());
}
}
private static int findProtocol(String protocol, List<ProtocolConfiguration> stack) {
for (int i = 0; i < stack.size(); i++) {
if (protocol.equals(stack.get(i).getProtocolName()))
return i;
}
return -1;
}
public RemoteSites getRemoteSites() {
RemoteSites combinedSites = new RemoteSites(remoteSites.defaultStack, remoteSites.defaultCluster);
combineSites(combinedSites.remoteSites);
return combinedSites;
}
public RemoteSites getUncombinedRemoteSites() {
return remoteSites;
}
@Override
public String toString() {
return "EmbeddedJGroupsChannelConfigurator{" +
"name='" + name + '\'' +
", parent='" + parent + '\'' +
", stack=" + stack +
", remoteSites=" + remoteSites +
'}';
}
public enum StackCombine {
COMBINE,
INSERT_AFTER,
INSERT_ABOVE,
INSERT_BEFORE,
INSERT_BELOW,
REPLACE,
REMOVE,
APPEND, // non-public
}
public static class RemoteSites {
final String defaultCluster;
final String defaultStack;
final Map<String, RemoteSite> remoteSites;
public RemoteSites(String defaultStack, String defaultCluster) {
this.defaultStack = defaultStack;
this.defaultCluster = defaultCluster;
remoteSites = new LinkedHashMap<>(4);
}
public String getDefaultCluster() {
return defaultCluster;
}
public String getDefaultStack() {
return defaultStack;
}
public Map<String, RemoteSite> getRemoteSites() {
return remoteSites;
}
public void addRemoteSite(String stackName, String remoteSite, String cluster, String stack) {
remoteSite = XSiteNamedCache.cachedString(remoteSite);
if (remoteSites.containsKey(remoteSite)) {
throw CONFIG.duplicateRemoteSite(remoteSite, stackName);
} else {
remoteSites.put(remoteSite, new RemoteSite(cluster, stack));
}
}
@Override
public String toString() {
return "RemoteSites{" +
"defaultCluster='" + defaultCluster + '\'' +
", defaultStack='" + defaultStack + '\'' +
", remoteSites=" + remoteSites +
'}';
}
}
public static class RemoteSite {
final String cluster;
final String stack;
RemoteSite(String cluster, String stack) {
this.cluster = cluster;
this.stack = stack;
}
public String getCluster() {
return cluster;
}
public String getStack() {
return stack;
}
@Override
public String toString() {
return "RemoteSite{" +
"cluster='" + cluster + '\'' +
", stack='" + stack + '\'' +
'}';
}
}
}
| 13,013
| 35.866856
| 156
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/SingleSiteRequest.java
|
package org.infinispan.remoting.transport.jgroups;
import static org.infinispan.util.logging.Log.CLUSTER;
import java.util.Set;
import org.infinispan.commons.util.Util;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.transport.AbstractRequest;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollector;
import org.infinispan.remoting.transport.SiteAddress;
import org.infinispan.remoting.transport.impl.RequestRepository;
/**
* Request implementation that waits for a response from a single target site.
*
* @author Dan Berindei
* @since 9.1
*/
public class SingleSiteRequest<T> extends AbstractRequest<T> {
private final String site;
SingleSiteRequest(ResponseCollector<T> wrapper, long requestId, RequestRepository repository, String site) {
super(requestId, wrapper, repository);
this.site = site;
}
@Override
public void onResponse(Address sender, Response response) {
receiveResponse(sender, response);
}
@Override
public boolean onNewView(Set<Address> members) {
// Ignore cluster views.
return false;
}
private void receiveResponse(Address sender, Response response) {
try {
// Ignore the return value, we won't receive another response
T result;
synchronized (responseCollector) {
if (isDone()) {
// CompletableFuture already completed. We can return immediately.
return;
}
result = responseCollector.addResponse(sender, response);
if (result == null) {
result = responseCollector.finish();
}
}
complete(result);
} catch (Exception e) {
completeExceptionally(e);
}
}
@Override
protected void onTimeout() {
completeExceptionally(CLUSTER.requestTimedOut(requestId, site, Util.prettyPrintTime(getTimeoutMs())));
}
public void sitesUnreachable(String unreachableSite) {
if (site.equals(unreachableSite)) {
receiveResponse(new SiteAddress(site), CacheNotFoundResponse.INSTANCE);
}
}
}
| 2,234
| 30.041667
| 111
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/JGroupsChannelLookup.java
|
package org.infinispan.remoting.transport.jgroups;
import java.util.Properties;
import org.jgroups.JChannel;
/**
* A hook to pass in a JGroups channel. Implementations need to provide a public no-arg constructor as instances are
* created via reflection.
*
* @author Manik Surtani
* @since 4.0
* @deprecated since 11.0, this will be removed in the next major version with no direct replacement.
*/
@Deprecated
public interface JGroupsChannelLookup {
/**
* Retrieves a JGroups channel. Passes in all of the properties used to configure the channel.
* @param p properties
* @return a JGroups channel
*/
JChannel getJGroupsChannel(Properties p);
/**
* @return true if the JGroupsTransport should connect the channel before using it; false if the transport
* should assume that the channel is connected.
*/
boolean shouldConnect();
/**
* @return true if the JGroupsTransport should disconnect the channel once it is done with it; false if
* the channel is to be left connected.
*/
boolean shouldDisconnect();
/**
* @return true if the JGroupsTransport should close the channel once it is done with it; false if
* the channel is to be left open.
*/
boolean shouldClose();
}
| 1,260
| 29.02381
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/BuiltinJGroupsChannelConfigurator.java
|
package org.infinispan.remoting.transport.jgroups;
import static org.infinispan.util.logging.Log.CONFIG;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.infinispan.commons.util.FileLookupFactory;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 10.0
**/
public class BuiltinJGroupsChannelConfigurator extends FileJGroupsChannelConfigurator {
public static final String TCP_STACK_NAME = "tcp";
public static BuiltinJGroupsChannelConfigurator TCP(Properties properties) {
return loadBuiltIn(TCP_STACK_NAME, "default-configs/default-jgroups-tcp.xml", properties);
}
public static BuiltinJGroupsChannelConfigurator UDP(Properties properties) {
return loadBuiltIn("udp", "default-configs/default-jgroups-udp.xml", properties);
}
public static BuiltinJGroupsChannelConfigurator KUBERNETES(Properties properties) {
return loadBuiltIn("kubernetes", "default-configs/default-jgroups-kubernetes.xml", properties);
}
public static BuiltinJGroupsChannelConfigurator EC2(Properties properties) {
return loadBuiltIn("ec2", "default-configs/default-jgroups-ec2.xml", properties);
}
public static BuiltinJGroupsChannelConfigurator GOOGLE(Properties properties) {
return loadBuiltIn("google", "default-configs/default-jgroups-google.xml", properties);
}
public static BuiltinJGroupsChannelConfigurator AZURE(Properties properties) {
return loadBuiltIn("azure", "default-configs/default-jgroups-azure.xml", properties);
}
private static BuiltinJGroupsChannelConfigurator loadBuiltIn(String name, String path, Properties properties) {
try (InputStream xml = FileLookupFactory.newInstance().lookupFileStrict(path, BuiltinJGroupsChannelConfigurator.class.getClassLoader())) {
return new BuiltinJGroupsChannelConfigurator(name, path, xml, properties);
} catch (IOException e) {
throw CONFIG.jgroupsConfigurationNotFound(path);
}
}
BuiltinJGroupsChannelConfigurator(String name, String path, InputStream is, Properties properties) throws IOException {
super(name, path, is, properties);
}
}
| 2,182
| 38.690909
| 144
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/JGroupsTransport.java
|
package org.infinispan.remoting.transport.jgroups;
import static org.infinispan.remoting.transport.jgroups.JGroupsAddressCache.fromJGroupsAddress;
import static org.infinispan.util.logging.Log.CLUSTER;
import static org.infinispan.util.logging.Log.CONTAINER;
import static org.infinispan.util.logging.Log.XSITE;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.management.ObjectName;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.commons.io.ByteBuffer;
import org.infinispan.commons.marshall.StreamingMarshaller;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.FileLookup;
import org.infinispan.commons.util.FileLookupFactory;
import org.infinispan.commons.util.TypedProperties;
import org.infinispan.commons.util.Util;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.commons.util.logging.TraceException;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.TransportConfiguration;
import org.infinispan.configuration.global.TransportConfigurationBuilder;
import org.infinispan.external.JGroupsProtocolComponent;
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.impl.ComponentRef;
import org.infinispan.factories.impl.MBeanMetadata;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.jmx.CacheManagerJmxRegistration;
import org.infinispan.jmx.ObjectNameKeys;
import org.infinispan.metrics.impl.MetricsCollector;
import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.inboundhandler.InboundInvocationHandler;
import org.infinispan.remoting.inboundhandler.Reply;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.ExceptionResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.SuccessfulResponse;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.rpc.ResponseFilter;
import org.infinispan.remoting.rpc.ResponseMode;
import org.infinispan.remoting.transport.AbstractRequest;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.BackupResponse;
import org.infinispan.remoting.transport.ResponseCollector;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.remoting.transport.XSiteResponse;
import org.infinispan.remoting.transport.impl.EmptyRaftManager;
import org.infinispan.remoting.transport.impl.FilterMapResponseCollector;
import org.infinispan.remoting.transport.impl.MapResponseCollector;
import org.infinispan.remoting.transport.impl.MultiTargetRequest;
import org.infinispan.remoting.transport.impl.Request;
import org.infinispan.remoting.transport.impl.RequestRepository;
import org.infinispan.remoting.transport.impl.SingleResponseCollector;
import org.infinispan.remoting.transport.impl.SingleTargetRequest;
import org.infinispan.remoting.transport.impl.SingletonMapResponseCollector;
import org.infinispan.remoting.transport.impl.SiteUnreachableXSiteResponse;
import org.infinispan.remoting.transport.impl.XSiteResponseImpl;
import org.infinispan.remoting.transport.raft.RaftManager;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.GlobalXSiteAdminOperations;
import org.infinispan.xsite.XSiteBackup;
import org.infinispan.xsite.XSiteNamedCache;
import org.infinispan.xsite.XSiteReplicateCommand;
import org.infinispan.xsite.commands.XSiteViewNotificationCommand;
import org.jgroups.BytesMessage;
import org.jgroups.ChannelListener;
import org.jgroups.Event;
import org.jgroups.Header;
import org.jgroups.JChannel;
import org.jgroups.MergeView;
import org.jgroups.Message;
import org.jgroups.PhysicalAddress;
import org.jgroups.UpHandler;
import org.jgroups.View;
import org.jgroups.blocks.RequestCorrelator;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.fork.ForkChannel;
import org.jgroups.jmx.JmxConfigurator;
import org.jgroups.protocols.FORK;
import org.jgroups.protocols.relay.RELAY2;
import org.jgroups.protocols.relay.RouteStatusListener;
import org.jgroups.protocols.relay.SiteAddress;
import org.jgroups.protocols.relay.SiteMaster;
import org.jgroups.stack.Protocol;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.util.ExtendedUUID;
import org.jgroups.util.MessageBatch;
import org.jgroups.util.SocketFactory;
/**
* An encapsulation of a JGroups transport. JGroups transports can be configured using a variety of methods, usually by
* passing in one of the following properties:
* <ul>
* <li><tt>configurationString</tt> - a JGroups configuration String</li>
* <li><tt>configurationXml</tt> - JGroups configuration XML as a String</li>
* <li><tt>configurationFile</tt> - String pointing to a JGroups XML configuration file</li>
* <li><tt>channelLookup</tt> - Fully qualified class name of a
* {@link JGroupsChannelLookup} instance</li>
* </ul>
* These are normally passed in as Properties in
* {@link TransportConfigurationBuilder#withProperties(Properties)} or
* in the Infinispan XML configuration file.
*
* @author Manik Surtani
* @author Galder Zamarreño
* @since 4.0
*/
@Scope(Scopes.GLOBAL)
@JGroupsProtocolComponent("JGroupsMetricsMetadata")
public class JGroupsTransport implements Transport, ChannelListener {
public static final String CONFIGURATION_STRING = "configurationString";
public static final String CONFIGURATION_XML = "configurationXml";
public static final String CONFIGURATION_FILE = "configurationFile";
public static final String CHANNEL_LOOKUP = "channelLookup";
public static final String CHANNEL_CONFIGURATOR = "channelConfigurator";
public static final String SOCKET_FACTORY = "socketFactory";
private static final String METRICS_PREFIX = "jgroups_";
public static final short REQUEST_FLAGS_UNORDERED =
(short) (Message.Flag.OOB.value() | Message.Flag.NO_TOTAL_ORDER.value());
public static final short REQUEST_FLAGS_UNORDERED_NO_FC = (short) (REQUEST_FLAGS_UNORDERED | Message.Flag.NO_FC.value());
public static final short REQUEST_FLAGS_PER_SENDER = Message.Flag.NO_TOTAL_ORDER.value();
public static final short REQUEST_FLAGS_PER_SENDER_NO_FC = (short) (REQUEST_FLAGS_PER_SENDER | Message.Flag.NO_FC.value());
public static final short REPLY_FLAGS =
(short) (Message.Flag.NO_FC.value() | Message.Flag.OOB.value() |
Message.Flag.NO_TOTAL_ORDER.value());
protected static final String DEFAULT_JGROUPS_CONFIGURATION_FILE = "default-configs/default-jgroups-udp.xml";
public static final Log log = LogFactory.getLog(JGroupsTransport.class);
private static final CompletableFuture<Map<Address, Response>> EMPTY_RESPONSES_FUTURE =
CompletableFuture.completedFuture(Collections.emptyMap());
private static final short CORRELATOR_ID = (short) 0;
private static final short HEADER_ID = ClassConfigurator.getProtocolId(RequestCorrelator.class);
private static final byte REQUEST = 0;
private static final byte RESPONSE = 1;
private static final byte SINGLE_MESSAGE = 2;
@Inject protected GlobalConfiguration configuration;
@Inject @ComponentName(KnownComponentNames.INTERNAL_MARSHALLER)
protected StreamingMarshaller marshaller;
@Inject protected CacheManagerNotifier notifier;
@Inject protected TimeService timeService;
@Inject protected InboundInvocationHandler invocationHandler;
@Inject @ComponentName(KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR)
protected ScheduledExecutorService timeoutExecutor;
@Inject @ComponentName(KnownComponentNames.NON_BLOCKING_EXECUTOR)
protected ExecutorService nonBlockingExecutor;
@Inject protected CacheManagerJmxRegistration jmxRegistration;
@Inject protected GlobalXSiteAdminOperations globalXSiteAdminOperations;
@Inject protected ComponentRef<MetricsCollector> metricsCollector;
private final Lock viewUpdateLock = new ReentrantLock();
private final Condition viewUpdateCondition = viewUpdateLock.newCondition();
private final ThreadPoolProbeHandler probeHandler;
private final ChannelCallbacks channelCallbacks = new ChannelCallbacks();
private final Map<JChannel, Set<Object>> clusters = new ConcurrentHashMap<>();
protected boolean connectChannel = true, disconnectChannel = true, closeChannel = true;
protected TypedProperties props;
protected JChannel channel;
protected Address address;
protected Address physicalAddress;
// these members are not valid until we have received the first view on a second thread
// and channelConnectedLatch is signaled
protected volatile ClusterView clusterView =
new ClusterView(ClusterView.INITIAL_VIEW_ID, Collections.emptyList(), null);
private CompletableFuture<Void> nextViewFuture = new CompletableFuture<>();
private RequestRepository requests;
private final Map<String, SiteUnreachableReason> unreachableSites;
private String localSite;
private volatile RaftManager raftManager = EmptyRaftManager.INSTANCE;
// ------------------------------------------------------------------------------------------------------------------
// Lifecycle and setup stuff
// ------------------------------------------------------------------------------------------------------------------
private boolean running;
public static FORK findFork(JChannel channel) {
return channel.getProtocolStack().findProtocol(FORK.class);
}
/**
* This form is used when the transport is created by an external source and passed in to the GlobalConfiguration.
*
* @param channel created and running channel to use
*/
public JGroupsTransport(JChannel channel) {
this();
this.channel = channel;
if (channel == null)
throw new IllegalArgumentException("Cannot deal with a null channel!");
if (channel.isConnected())
throw new IllegalArgumentException("Channel passed in cannot already be connected!");
}
public JGroupsTransport() {
this.probeHandler = new ThreadPoolProbeHandler();
this.unreachableSites = new ConcurrentHashMap<>();
}
@Override
public CompletableFuture<Map<Address, Response>> invokeRemotelyAsync(Collection<Address> recipients,
ReplicableCommand command,
ResponseMode mode, long timeout,
ResponseFilter responseFilter,
DeliverOrder deliverOrder,
boolean anycast) {
if (recipients != null && recipients.isEmpty()) {
// don't send if recipients list is empty
log.tracef("Destination list is empty: no need to send command %s", command);
return EMPTY_RESPONSES_FUTURE;
}
ClusterView view = this.clusterView;
List<Address> localMembers = view.getMembers();
int membersSize = localMembers.size();
boolean ignoreLeavers =
mode == ResponseMode.SYNCHRONOUS_IGNORE_LEAVERS || mode == ResponseMode.WAIT_FOR_VALID_RESPONSE;
boolean sendStaggeredRequest = mode == ResponseMode.WAIT_FOR_VALID_RESPONSE &&
deliverOrder == DeliverOrder.NONE && recipients != null && recipients.size() > 1 && timeout > 0;
// ISPN-6997: Never allow a switch from anycast -> broadcast and broadcast -> unicast
// We're still keeping the option to switch for a while in case forcing a broadcast in a 2-node replicated cache
// impacts performance significantly. If that is the case, we may need to use UNICAST3.closeConnection() instead.
boolean broadcast = recipients == null;
if (recipients == null && membersSize == 1) {
// don't send if recipients list is empty
log.tracef("The cluster has a single node: no need to broadcast command %s", command);
return EMPTY_RESPONSES_FUTURE;
}
Address singleTarget = computeSingleTarget(recipients, localMembers, membersSize, broadcast);
if (address.equals(singleTarget)) {
log.tracef("Skipping request to self for command %s", command);
return EMPTY_RESPONSES_FUTURE;
}
if (mode.isAsynchronous()) {
// Asynchronous RPC. Send the message, but don't wait for responses.
return performAsyncRemoteInvocation(recipients, command, deliverOrder, broadcast, singleTarget);
}
Collection<Address> actualTargets = broadcast ? localMembers : recipients;
return performSyncRemoteInvocation(actualTargets, command, mode, timeout, responseFilter, deliverOrder,
ignoreLeavers, sendStaggeredRequest, broadcast, singleTarget);
}
@Override
public void sendTo(Address destination, ReplicableCommand command, DeliverOrder deliverOrder) {
if (destination.equals(address)) { //removed requireNonNull. this will throw a NPE in that case
if (log.isTraceEnabled())
log.tracef("%s not sending command to self: %s", address, command);
return;
}
logCommand(command, destination);
sendCommand(destination, command, Request.NO_REQUEST_ID, deliverOrder, true, true);
}
@Override
public void sendToMany(Collection<Address> targets, ReplicableCommand command, DeliverOrder deliverOrder) {
if (targets == null) {
logCommand(command, "all");
sendCommandToAll(command, Request.NO_REQUEST_ID, deliverOrder);
} else {
logCommand(command, targets);
sendCommand(targets, command, Request.NO_REQUEST_ID, deliverOrder, true);
}
}
@Override
@Deprecated
public Map<Address, Response> invokeRemotely(Map<Address, ReplicableCommand> commands, ResponseMode mode,
long timeout, ResponseFilter responseFilter, DeliverOrder deliverOrder,
boolean anycast)
throws Exception {
if (commands == null || commands.isEmpty()) {
// don't send if recipients list is empty
log.trace("Destination list is empty: no need to send message");
return Collections.emptyMap();
}
if (mode.isSynchronous()) {
MapResponseCollector collector = MapResponseCollector.validOnly(commands.size());
CompletionStage<Map<Address, Response>> request =
invokeCommands(commands.keySet(), commands::get, collector, deliverOrder, timeout, TimeUnit.MILLISECONDS);
try {
return CompletableFutures.await(request.toCompletableFuture());
} catch (ExecutionException e) {
Throwable cause = e.getCause();
cause.addSuppressed(new TraceException());
throw Util.rewrapAsCacheException(cause);
}
} else {
commands.forEach(
(a, command) -> {
logCommand(command, a);
sendCommand(a, command, Request.NO_REQUEST_ID, deliverOrder, true, true);
});
return Collections.emptyMap();
}
}
@Override
public BackupResponse backupRemotely(Collection<XSiteBackup> backups, XSiteReplicateCommand command) {
if (log.isTraceEnabled())
log.tracef("About to send to backups %s, command %s", backups, command);
Map<XSiteBackup, CompletableFuture<ValidResponse>> backupCalls = new HashMap<>(backups.size());
for (XSiteBackup xsb : backups) {
assert !localSite.equals(xsb.getSiteName()) : "sending to local site";
Address recipient = JGroupsAddressCache.fromJGroupsAddress(new SiteMaster(xsb.getSiteName()));
long requestId = requests.newRequestId();
logRequest(requestId, command, recipient, "backup");
SingleSiteRequest<ValidResponse> request =
new SingleSiteRequest<>(SingleResponseCollector.validOnly(), requestId, requests, xsb.getSiteName());
addRequest(request);
backupCalls.put(xsb, request);
DeliverOrder order = xsb.isSync() ? DeliverOrder.NONE : DeliverOrder.PER_SENDER;
long timeout = xsb.getTimeout();
try {
sendCommand(recipient, command, request.getRequestId(), order, false, false);
if (timeout > 0) {
request.setTimeout(timeoutExecutor, timeout, TimeUnit.MILLISECONDS);
}
} catch (Throwable t) {
request.cancel(true);
throw t;
}
}
return new JGroupsBackupResponse(backupCalls, timeService);
}
@Override
public <O> XSiteResponse<O> backupRemotely(XSiteBackup backup, XSiteReplicateCommand<O> rpcCommand) {
assert !localSite.equals(backup.getSiteName()) : "sending to local site";
if (unreachableSites.containsKey(backup.getSiteName())) {
// fail fast if we have thread handling a SITE_UNREACHABLE event.
return new SiteUnreachableXSiteResponse<>(backup, timeService);
}
Address recipient = JGroupsAddressCache.fromJGroupsAddress(new SiteMaster(backup.getSiteName()));
long requestId = requests.newRequestId();
logRequest(requestId, rpcCommand, recipient, "backup");
SingleSiteRequest<ValidResponse> request =
new SingleSiteRequest<>(SingleResponseCollector.validOnly(), requestId, requests, backup.getSiteName());
addRequest(request);
DeliverOrder order = backup.isSync() ? DeliverOrder.NONE : DeliverOrder.PER_SENDER;
long timeout = backup.getTimeout();
XSiteResponseImpl<O> xSiteResponse = new XSiteResponseImpl<>(timeService, backup);
try {
sendCommand(recipient, rpcCommand, request.getRequestId(), order, false, false);
if (timeout > 0) {
request.setTimeout(timeoutExecutor, timeout, TimeUnit.MILLISECONDS);
}
request.whenComplete(xSiteResponse);
} catch (Throwable t) {
request.cancel(true);
xSiteResponse.completeExceptionally(t);
}
return xSiteResponse;
}
@Override
public boolean isCoordinator() {
return clusterView.isCoordinator();
}
@Override
public Address getCoordinator() {
return clusterView.getCoordinator();
}
@Override
public Address getAddress() {
return address;
}
@Override
public List<Address> getPhysicalAddresses() {
if (physicalAddress == null && channel != null) {
org.jgroups.Address addr =
(org.jgroups.Address) channel.down(new Event(Event.GET_PHYSICAL_ADDRESS, channel.getAddress()));
if (addr == null) {
return Collections.emptyList();
}
physicalAddress = new JGroupsAddress(addr);
}
return Collections.singletonList(physicalAddress);
}
@Override
public List<Address> getMembers() {
return clusterView.getMembers();
}
@Override
public List<Address> getMembersPhysicalAddresses() {
if (channel != null) {
View v = channel.getView();
org.jgroups.Address[] rawMembers = v.getMembersRaw();
List<Address> addresses = new ArrayList<>(rawMembers.length);
for (org.jgroups.Address rawMember : rawMembers) {
PhysicalAddress physical_addr = (PhysicalAddress) channel.down(new Event(Event.GET_PHYSICAL_ADDRESS, rawMember));
addresses.add(new JGroupsAddress(physical_addr));
}
return addresses;
} else {
return Collections.emptyList();
}
}
@Override
public boolean isMulticastCapable() {
return channel.getProtocolStack().getTransport().supportsMulticasting();
}
@Override
public void checkCrossSiteAvailable() throws CacheConfigurationException {
if (localSite == null) {
throw CLUSTER.crossSiteUnavailable();
}
}
@Override
public String localSiteName() {
return localSite;
}
@Override
public String localNodeName() {
if (channel == null) {
return Transport.super.localNodeName();
}
return channel.getName();
}
@Start
@Override
public void start() {
if (running)
throw new IllegalStateException("Two or more cache managers are using the same JGroupsTransport instance");
probeHandler.updateThreadPool(nonBlockingExecutor);
props = TypedProperties.toTypedProperties(configuration.transport().properties());
requests = new RequestRepository();
initChannel();
channel.setUpHandler(channelCallbacks);
setXSiteViewListener(channelCallbacks);
startJGroupsChannelIfNeeded();
waitForInitialNodes();
channel.getProtocolStack().getTransport().registerProbeHandler(probeHandler);
RELAY2 relay2 = findRelay2();
if (relay2 != null) {
localSite = XSiteNamedCache.cachedString(relay2.site());
}
running = true;
}
protected void initChannel() {
TransportConfiguration transportCfg = configuration.transport();
if (channel == null) {
buildChannel();
if (connectChannel) {
// Cannot change the name if the channelLookup already connected the channel
String transportNodeName = transportCfg.nodeName();
if (transportNodeName != null && !transportNodeName.isEmpty()) {
channel.setName(transportNodeName);
}
}
}
// Channel.LOCAL *must* be set to false so we don't see our own messages - otherwise
// invalidations targeted at remote instances will be received by self.
// NOTE: total order needs to deliver own messages. the invokeRemotely method has a total order boolean
// that when it is false, it discard our own messages, maintaining the property needed
channel.setDiscardOwnMessages(false);
// if we have a TopologyAwareConsistentHash, we need to set our own address generator in JGroups
if (transportCfg.hasTopologyInfo()) {
// We can do this only if the channel hasn't been started already
if (connectChannel) {
channel.addAddressGenerator(() -> JGroupsTopologyAwareAddress
.randomUUID(channel.getName(), transportCfg.siteId(), transportCfg.rackId(),
transportCfg.machineId()));
} else {
org.jgroups.Address jgroupsAddress = channel.getAddress();
if (jgroupsAddress instanceof ExtendedUUID) {
JGroupsTopologyAwareAddress address = new JGroupsTopologyAwareAddress((ExtendedUUID) jgroupsAddress);
if (!address.matches(transportCfg.siteId(), transportCfg.rackId(), transportCfg.machineId())) {
throw new CacheException(
"Topology information does not match the one set by the provided JGroups channel");
}
} else {
throw new CacheException("JGroups address does not contain topology coordinates");
}
}
}
initRaftManager();
}
private void initRaftManager() {
TransportConfiguration transportCfg = configuration.transport();
if (RaftUtil.isRaftAvailable()) {
if (transportCfg.nodeName() == null || transportCfg.nodeName().isEmpty()) {
log.raftProtocolUnavailable("transport.node-name is not set.");
return;
}
if (transportCfg.raftMembers().isEmpty()) {
log.raftProtocolUnavailable("transport.raft-members is not set.");
return;
}
// HACK!
// TODO improve JGroups code so we have access to the key stored
byte[] key = org.jgroups.util.Util.stringToBytes("raft-id");
byte[] value = org.jgroups.util.Util.stringToBytes(transportCfg.nodeName());
if (connectChannel) {
channel.addAddressGenerator(() -> ExtendedUUID.randomUUID(channel.getName()).put(key, value));
} else {
org.jgroups.Address addr = channel.getAddress();
if (addr instanceof ExtendedUUID) {
if (!Arrays.equals(((ExtendedUUID) addr).get(key), value)) {
log.raftProtocolUnavailable("non-managed JGroups channel does not have 'raft-id' set.");
return;
}
}
}
insertForkIfMissing();
raftManager = new JGroupsRaftManager(configuration, channel);
raftManager.start();
log.raftProtocolAvailable();
}
}
private void insertForkIfMissing() {
if (findFork(channel) != null) {
return;
}
ProtocolStack protocolStack = channel.getProtocolStack();
RELAY2 relay2 = findRelay2();
if (relay2 != null) {
protocolStack.insertProtocolInStack(new FORK(), relay2, ProtocolStack.Position.BELOW);
} else {
protocolStack.addProtocol(new FORK());
}
}
private void setXSiteViewListener(RouteStatusListener listener) {
RELAY2 relay2 = findRelay2();
if (relay2 != null) {
relay2.setRouteStatusListener(listener);
// if a node join, and is a site master, to a running cluster, it does not get any site up/down event.
// there is a chance to get a duplicated log entry but it does not matter.
Collection<String> view = getSitesView();
if (view != null && !view.isEmpty()) {
XSITE.receivedXSiteClusterView(view);
}
}
}
/**
* When overwriting this method, it allows third-party libraries to create a new behavior like: After {@link
* JChannel} has been created and before it is connected.
*/
protected void startJGroupsChannelIfNeeded() {
String clusterName = configuration.transport().clusterName();
if (log.isDebugEnabled()) {
log.debugf("JGroups protocol stack: %s\n", channel.getProtocolStack().printProtocolSpec(true));
}
String stack = configuration.transport().stack();
if (stack != null) {
CLUSTER.startingJGroupsChannel(clusterName, stack);
} else if (!(channel instanceof ForkChannel)) {
CLUSTER.startingJGroupsChannel(clusterName);
}
if (connectChannel) {
try {
channel.connect(clusterName);
} catch (Exception e) {
throw new CacheException("Unable to start JGroups Channel", e);
}
}
registerMBeansIfNeeded(clusterName);
if (!connectChannel) {
// the channel was already started externally, we need to initialize our member list
receiveClusterView(channel.getView());
}
if (!(channel instanceof ForkChannel)) {
CLUSTER.localAndPhysicalAddress(clusterName, getAddress(), getPhysicalAddresses());
}
}
// This needs to stay as a separate method to allow for substitution for Substrate
private void registerMBeansIfNeeded(String clusterName) {
try {
// Normally this would be done by CacheManagerJmxRegistration but
// the channel is not started when the cache manager starts but
// when first cache starts, so it's safer to do it here.
if (jmxRegistration.enabled()) {
ObjectName namePrefix = new ObjectName(jmxRegistration.getDomain() + ":" + ObjectNameKeys.MANAGER + "=" + ObjectName.quote(configuration.cacheManagerName()));
JmxConfigurator.registerChannel(channel, jmxRegistration.getMBeanServer(), namePrefix, clusterName, true);
}
} catch (Exception e) {
throw new CacheException("Channel connected, but unable to register MBeans", e);
}
}
private void waitForInitialNodes() {
int initialClusterSize = configuration.transport().initialClusterSize();
if (initialClusterSize <= 1)
return;
long timeout = configuration.transport().initialClusterTimeout();
long remainingNanos = TimeUnit.MILLISECONDS.toNanos(timeout);
viewUpdateLock.lock();
try {
while (channel != null && channel.getView().getMembers().size() < initialClusterSize &&
remainingNanos > 0) {
log.debugf("Waiting for %d nodes, current view has %d", initialClusterSize,
channel.getView().getMembers().size());
remainingNanos = viewUpdateCondition.awaitNanos(remainingNanos);
}
} catch (InterruptedException e) {
CLUSTER.interruptedWaitingForCoordinator(e);
Thread.currentThread().interrupt();
} finally {
viewUpdateLock.unlock();
}
if (remainingNanos <= 0) {
throw CLUSTER.timeoutWaitingForInitialNodes(initialClusterSize, channel.getView().getMembers());
}
log.debugf("Initial cluster size of %d nodes reached", initialClusterSize);
}
// This is per CM, so the CL in use should be the CM CL
private void buildChannel() {
FileLookup fileLookup = FileLookupFactory.newInstance();
// in order of preference - we first look for an external JGroups file, then a set of XML
// properties, and finally the legacy JGroups String properties.
String cfg;
if (props != null) {
if (props.containsKey(CHANNEL_LOOKUP)) {
String channelLookupClassName = props.getProperty(CHANNEL_LOOKUP);
try {
JGroupsChannelLookup lookup = Util.getInstance(channelLookupClassName, configuration.classLoader());
channel = lookup.getJGroupsChannel(props);
connectChannel = lookup.shouldConnect();
disconnectChannel = lookup.shouldDisconnect();
closeChannel = lookup.shouldClose();
} catch (ClassCastException e) {
CLUSTER.wrongTypeForJGroupsChannelLookup(channelLookupClassName, e);
throw new CacheException(e);
} catch (Exception e) {
CLUSTER.errorInstantiatingJGroupsChannelLookup(channelLookupClassName, e);
throw new CacheException(e);
}
}
if (channel == null && props.containsKey(CHANNEL_CONFIGURATOR)) {
channelFromConfigurator((JGroupsChannelConfigurator) props.get(CHANNEL_CONFIGURATOR));
}
if (channel == null && props.containsKey(CONFIGURATION_FILE)) {
cfg = props.getProperty(CONFIGURATION_FILE);
Collection<URL> confs = Collections.emptyList();
try {
confs = fileLookup.lookupFileLocations(cfg, configuration.classLoader());
} catch (IOException io) {
//ignore, we check confs later for various states
}
if (confs.isEmpty()) {
throw CLUSTER.jgroupsConfigurationNotFound(cfg);
} else if (confs.size() > 1) {
CLUSTER.ambiguousConfigurationFiles(Util.toStr(confs));
}
try {
URL url = confs.iterator().next();
channel = new JChannel(url.openStream());
} catch (Exception e) {
throw CLUSTER.errorCreatingChannelFromConfigFile(cfg, e);
}
}
if (channel == null && props.containsKey(CONFIGURATION_XML)) {
cfg = props.getProperty(CONFIGURATION_XML);
try {
channel = new JChannel(new ByteArrayInputStream(cfg.getBytes()));
} catch (Exception e) {
throw CLUSTER.errorCreatingChannelFromXML(cfg, e);
}
}
if (channel == null && props.containsKey(CONFIGURATION_STRING)) {
cfg = props.getProperty(CONFIGURATION_STRING);
try {
channel = new JChannel(new ByteArrayInputStream(cfg.getBytes()));
} catch (Exception e) {
throw CLUSTER.errorCreatingChannelFromConfigString(cfg, e);
}
}
if (channel == null && configuration.transport().stack() != null) {
channelFromConfigurator(configuration.transport().jgroups().configurator(configuration.transport().stack()));
}
}
if (channel == null) {
CLUSTER.unableToUseJGroupsPropertiesProvided(props);
try (InputStream is = fileLookup.lookupFileLocation(DEFAULT_JGROUPS_CONFIGURATION_FILE, configuration.classLoader()).openStream()) {
channel = new JChannel(is);
} catch (Exception e) {
throw CLUSTER.errorCreatingChannelFromConfigFile(DEFAULT_JGROUPS_CONFIGURATION_FILE, e);
}
}
if (props != null && props.containsKey(SOCKET_FACTORY) && !props.containsKey(CHANNEL_CONFIGURATOR)) {
Protocol protocol = channel.getProtocolStack().getTopProtocol();
protocol.setSocketFactory((SocketFactory) props.get(SOCKET_FACTORY));
}
}
private void channelFromConfigurator(JGroupsChannelConfigurator configurator) {
if (props.containsKey(SOCKET_FACTORY)) {
SocketFactory socketFactory = (SocketFactory) props.get(SOCKET_FACTORY);
if (socketFactory instanceof NamedSocketFactory) {
((NamedSocketFactory) socketFactory).setName(configuration.transport().clusterName());
}
configurator.setSocketFactory(socketFactory);
}
configurator.addChannelListener(this);
try {
channel = configurator.createChannel(configuration.transport().clusterName());
} catch (Exception e) {
throw CLUSTER.errorCreatingChannelFromConfigurator(configurator.getProtocolStackString(), e);
}
}
protected void receiveClusterView(View newView) {
// The first view is installed before returning from JChannel.connect
// So we need to set the local address here
if (address == null) {
org.jgroups.Address jgroupsAddress = channel.getAddress();
this.address = fromJGroupsAddress(jgroupsAddress);
if (log.isTraceEnabled()) {
String uuid = (jgroupsAddress instanceof org.jgroups.util.UUID) ?
((org.jgroups.util.UUID) jgroupsAddress).toStringLong() : "N/A";
log.tracef("Local address %s, uuid %s", jgroupsAddress, uuid);
}
}
List<List<Address>> subGroups;
if (newView instanceof MergeView) {
if (!(channel instanceof ForkChannel)) {
CLUSTER.receivedMergedView(channel.clusterName(), newView);
}
subGroups = new ArrayList<>();
List<View> jgroupsSubGroups = ((MergeView) newView).getSubgroups();
for (View group : jgroupsSubGroups) {
subGroups.add(fromJGroupsAddressList(group.getMembers()));
}
} else {
if (!(channel instanceof ForkChannel)) {
CLUSTER.receivedClusterView(channel.clusterName(), newView);
}
subGroups = Collections.emptyList();
}
long viewId = newView.getViewId().getId();
List<Address> members = fromJGroupsAddressList(newView.getMembers());
if (members.isEmpty()) {
return;
}
ClusterView oldView = this.clusterView;
// Update every view-related field while holding the lock so that waitForView only returns
// after everything was updated.
CompletableFuture<Void> oldFuture = null;
viewUpdateLock.lock();
try {
// Delta view debug log for large cluster
if (log.isDebugEnabled() && oldView.getMembers() != null) {
List<Address> joined = new ArrayList<>(members);
joined.removeAll(oldView.getMembers());
List<Address> left = new ArrayList<>(oldView.getMembers());
left.removeAll(members);
log.debugf("Joined: %s, Left: %s", joined, left);
}
this.clusterView = new ClusterView((int) viewId, members, address);
// Create a completable future for the new view
oldFuture = nextViewFuture;
nextViewFuture = new CompletableFuture<>();
// Wake up any threads that are waiting to know about who the isCoordinator is
// do it before the notifications, so if a listener throws an exception we can still start
viewUpdateCondition.signalAll();
} finally {
viewUpdateLock.unlock();
// Complete the future for the old view
if (oldFuture != null) {
CompletableFuture<Void> future = oldFuture;
nonBlockingExecutor.execute(() -> future.complete(null));
}
}
// now notify listeners - *after* updating the isCoordinator. - JBCACHE-662
boolean hasNotifier = notifier != null;
if (hasNotifier) {
if (!subGroups.isEmpty()) {
final Address address1 = getAddress();
CompletionStages.join(notifier.notifyMerge(members, oldView.getMembers(), address1, (int) viewId, subGroups));
} else {
CompletionStages.join(notifier.notifyViewChange(members, oldView.getMembers(), getAddress(), (int) viewId));
}
}
// Targets leaving may finish some requests and potentially potentially block for a long time.
// We don't want to block view handling, so we unblock the commands on a separate thread.
nonBlockingExecutor.execute(() -> {
if (requests != null) {
requests.forEach(request -> request.onNewView(clusterView.getMembersSet()));
}
});
JGroupsAddressCache.pruneAddressCache();
}
private static List<Address> fromJGroupsAddressList(List<org.jgroups.Address> list) {
return Collections.unmodifiableList(list.stream()
.map(JGroupsAddressCache::fromJGroupsAddress)
.collect(Collectors.toList()));
}
@Stop
@Override
public void stop() {
running = false;
if (channel != null) {
channel.getProtocolStack().getTransport().unregisterProbeHandler(probeHandler);
}
raftManager.stop();
String clusterName = configuration.transport().clusterName();
try {
if (disconnectChannel && channel != null && channel.isConnected()) {
if (!(channel instanceof ForkChannel)) {
CLUSTER.disconnectJGroups(clusterName);
}
channel.disconnect();
}
if (closeChannel && channel != null && channel.isOpen()) {
channel.close();
}
unregisterMBeansIfNeeded(clusterName);
} catch (Exception toLog) {
CLUSTER.problemClosingChannel(toLog, clusterName);
}
if (requests != null) {
requests.forEach(request -> request.cancel(CONTAINER.cacheManagerIsStopping()));
}
// Don't keep a reference to the channel, but keep the address and physical address
channel = null;
clusterView = new ClusterView(ClusterView.FINAL_VIEW_ID, Collections.emptyList(), null);
CompletableFuture<Void> oldFuture = null;
viewUpdateLock.lock();
try {
// Create a completable future for the new view
oldFuture = nextViewFuture;
nextViewFuture = new CompletableFuture<>();
// Wake up any threads blocked in waitForView()
viewUpdateCondition.signalAll();
} finally {
viewUpdateLock.unlock();
// And finally, complete the future for the old view
if (oldFuture != null) {
oldFuture.complete(null);
}
}
}
// This needs to stay as a separate method to allow for substitution for Substrate
private void unregisterMBeansIfNeeded(String clusterName) throws Exception {
if (jmxRegistration.enabled() && channel != null) {
ObjectName namePrefix = new ObjectName(jmxRegistration.getDomain() + ":" + ObjectNameKeys.MANAGER + "=" + ObjectName.quote(configuration.cacheManagerName()));
JmxConfigurator.unregisterChannel(channel, jmxRegistration.getMBeanServer(), namePrefix, clusterName);
}
}
@Override
public int getViewId() {
if (channel == null)
throw new IllegalLifecycleStateException("The cache has been stopped and invocations are not allowed!");
return clusterView.getViewId();
}
@Override
public CompletableFuture<Void> withView(int expectedViewId) {
ClusterView view = this.clusterView;
if (view.isViewIdAtLeast(expectedViewId))
return CompletableFutures.completedNull();
if (log.isTraceEnabled())
log.tracef("Waiting for view %d, current view is %d", expectedViewId, view.getViewId());
viewUpdateLock.lock();
try {
view = this.clusterView;
if (view.isViewIdAtLeast(ClusterView.FINAL_VIEW_ID)) {
throw new IllegalLifecycleStateException();
} else if (view.isViewIdAtLeast(expectedViewId)) {
return CompletableFutures.completedNull();
} else {
return nextViewFuture.thenCompose(nil -> withView(expectedViewId));
}
} finally {
viewUpdateLock.unlock();
}
}
@Override
public void waitForView(int viewId) throws InterruptedException {
if (channel == null)
return;
long remainingNanos = Long.MAX_VALUE;
viewUpdateLock.lock();
try {
while (channel != null && getViewId() < viewId && remainingNanos > 0) {
log.tracef("Waiting for view %d, current view is %d", viewId, clusterView.getViewId());
remainingNanos = viewUpdateCondition.awaitNanos(remainingNanos);
}
} finally {
viewUpdateLock.unlock();
}
}
@Override
public Log getLog() {
return log;
}
@Override
public Set<String> getSitesView() {
RELAY2 relay2 = findRelay2();
if (relay2 == null) {
return null;
}
List<String> sites = relay2.getCurrentSites();
return sites == null ? Collections.emptySet() : new TreeSet<>(sites);
}
@Override
public boolean isSiteCoordinator() {
RELAY2 relay2 = findRelay2();
return relay2 != null && relay2.isSiteMaster();
}
@Override
public Collection<Address> getRelayNodesAddress() {
RELAY2 relay2 = findRelay2();
if (relay2 == null) {
return Collections.emptyList();
}
return relay2.siteMasters().stream()
.map(JGroupsAddressCache::fromJGroupsAddress)
.collect(Collectors.toList());
}
@Override
public <T> CompletionStage<T> invokeCommand(Address target, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
if (target.equals(address)) {
return CompletableFuture.completedFuture(collector.finish());
}
long requestId = requests.newRequestId();
logRequest(requestId, command, target, "single");
SingleTargetRequest<T> request = new SingleTargetRequest<>(collector, requestId, requests, target);
addRequest(request);
boolean invalidTarget = request.onNewView(clusterView.getMembersSet());
if (!invalidTarget) {
sendCommand(target, command, requestId, deliverOrder, true, false);
}
if (timeout > 0) {
request.setTimeout(timeoutExecutor, timeout, unit);
}
return request;
}
@Override
public <T> CompletionStage<T> invokeCommand(Collection<Address> targets, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
long requestId = requests.newRequestId();
logRequest(requestId, command, targets, "multi");
if (targets.isEmpty()) {
return CompletableFuture.completedFuture(collector.finish());
}
Address excludedTarget = getAddress();
MultiTargetRequest<T> request =
new MultiTargetRequest<>(collector, requestId, requests, targets, excludedTarget);
// Request may be completed due to exclusion of target nodes, so only send it if it isn't complete
if (request.isDone()) {
return request;
}
try {
addRequest(request);
boolean checkView = request.onNewView(clusterView.getMembersSet());
sendCommand(targets, command, requestId, deliverOrder, checkView);
} catch (Throwable t) {
request.cancel(true);
throw t;
}
if (timeout > 0) {
request.setTimeout(timeoutExecutor, timeout, unit);
}
return request;
}
@Override
public <T> CompletionStage<T> invokeCommandOnAll(ReplicableCommand command, ResponseCollector<T> collector,
DeliverOrder deliverOrder, long timeout, TimeUnit unit) {
long requestId = requests.newRequestId();
logRequest(requestId, command, null, "broadcast");
Address excludedTarget = getAddress();
MultiTargetRequest<T> request =
new MultiTargetRequest<>(collector, requestId, requests, clusterView.getMembers(), excludedTarget);
// Request may be completed due to exclusion of target nodes, so only send it if it isn't complete
if (request.isDone()) {
return request;
}
try {
addRequest(request);
request.onNewView(clusterView.getMembersSet());
sendCommandToAll(command, requestId, deliverOrder);
} catch (Throwable t) {
request.cancel(true);
throw t;
}
if (timeout > 0) {
request.setTimeout(timeoutExecutor, timeout, unit);
}
return request;
}
@Override
public <T> CompletionStage<T> invokeCommandOnAll(Collection<Address> requiredTargets, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
long requestId = requests.newRequestId();
logRequest(requestId, command, requiredTargets, "broadcast");
Address excludedTarget = getAddress();
MultiTargetRequest<T> request =
new MultiTargetRequest<>(collector, requestId, requests, requiredTargets, excludedTarget);
// Request may be completed due to exclusion of target nodes, so only send it if it isn't complete
if (request.isDone()) {
return request;
}
try {
addRequest(request);
request.onNewView(clusterView.getMembersSet());
sendCommandToAll(command, requestId, deliverOrder);
} catch (Throwable t) {
request.cancel(true);
throw t;
}
if (timeout > 0) {
request.setTimeout(timeoutExecutor, timeout, unit);
}
return request;
}
@Override
public <T> CompletionStage<T> invokeCommandStaggered(Collection<Address> targets, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
long requestId = requests.newRequestId();
logRequest(requestId, command, targets, "staggered");
StaggeredRequest<T> request =
new StaggeredRequest<>(collector, requestId, requests, targets, getAddress(), command, deliverOrder,
timeout, unit, this);
try {
addRequest(request);
request.onNewView(clusterView.getMembersSet());
request.sendNextMessage();
} catch (Throwable t) {
request.cancel(true);
throw t;
}
return request;
}
@Override
public <T> CompletionStage<T> invokeCommands(Collection<Address> targets,
Function<Address, ReplicableCommand> commandGenerator,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit timeUnit) {
long requestId;
requestId = requests.newRequestId();
Address excludedTarget = getAddress();
MultiTargetRequest<T> request =
new MultiTargetRequest<>(collector, requestId, requests, targets, excludedTarget);
// Request may be completed due to exclusion of target nodes, so only send it if it isn't complete
if (request.isDone()) {
return request;
}
addRequest(request);
boolean checkView = request.onNewView(clusterView.getMembersSet());
try {
for (Address target : targets) {
if (target.equals(excludedTarget))
continue;
ReplicableCommand command = commandGenerator.apply(target);
logRequest(requestId, command, target, "mixed");
sendCommand(target, command, requestId, deliverOrder, true, checkView);
}
} catch (Throwable t) {
request.cancel(true);
throw t;
}
if (timeout > 0) {
request.setTimeout(timeoutExecutor, timeout, timeUnit);
}
return request;
}
@Override
public RaftManager raftManager() {
return raftManager;
}
private void addRequest(AbstractRequest<?> request) {
try {
requests.addRequest(request);
if (!running) {
request.cancel(CONTAINER.cacheManagerIsStopping());
}
} catch (Throwable t) {
// Removes the request and the scheduled task, if necessary
request.cancel(true);
throw t;
}
}
void sendCommand(Address target, ReplicableCommand command, long requestId, DeliverOrder deliverOrder,
boolean noRelay, boolean checkView) {
if (checkView && !clusterView.contains(target))
return;
Message message = new BytesMessage(toJGroupsAddress(target));
marshallRequest(message, command, requestId);
setMessageFlags(message, deliverOrder, noRelay);
send(message);
}
private static org.jgroups.Address toJGroupsAddress(Address address) {
return ((JGroupsAddress) address).getJGroupsAddress();
}
private void marshallRequest(Message message, ReplicableCommand command, long requestId) {
try {
ByteBuffer bytes = marshaller.objectToBuffer(command);
message.setArray(bytes.getBuf(), bytes.getOffset(), bytes.getLength());
addRequestHeader(message, requestId);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Failure to marshal argument(s)", e);
}
}
private static void setMessageFlags(Message message, DeliverOrder deliverOrder, boolean noRelay) {
short flags = encodeDeliverMode(deliverOrder);
if (noRelay) {
flags |= Message.Flag.NO_RELAY.value();
}
message.setFlag(flags, false);
message.setFlag(Message.TransientFlag.DONT_LOOPBACK);
}
private void send(Message message) {
try {
JChannel channel = this.channel;
if (channel != null) {
channel.send(message);
}
} catch (Exception e) {
if (running) {
throw new CacheException(e);
} else {
throw CONTAINER.cacheManagerIsStopping();
}
}
}
private void addRequestHeader(Message message, long requestId) {
// TODO Remove the header and store the request id in the buffer
if (requestId != Request.NO_REQUEST_ID) {
Header header = new RequestCorrelator.Header(REQUEST, requestId, CORRELATOR_ID);
message.putHeader(HEADER_ID, header);
}
}
private static short encodeDeliverMode(DeliverOrder deliverOrder) {
switch (deliverOrder) {
case PER_SENDER:
return REQUEST_FLAGS_PER_SENDER;
case PER_SENDER_NO_FC:
return REQUEST_FLAGS_PER_SENDER_NO_FC;
case NONE:
return REQUEST_FLAGS_UNORDERED;
case NONE_NO_FC:
return REQUEST_FLAGS_UNORDERED_NO_FC;
default:
throw new IllegalArgumentException("Unsupported deliver mode " + deliverOrder);
}
}
/**
* @return The single target's address, or {@code null} if there are multiple targets.
*/
private Address computeSingleTarget(Collection<Address> targets, List<Address> localMembers, int membersSize,
boolean broadcast) {
Address singleTarget;
if (broadcast) {
singleTarget = null;
} else {
if (targets == null) {
// No broadcast means we eliminated the membersSize == 1 and membersSize > 2 possibilities
assert membersSize == 2;
singleTarget = localMembers.get(0).equals(address) ? localMembers.get(1) : localMembers.get(0);
} else if (targets.size() == 1) {
singleTarget = targets.iterator().next();
} else {
singleTarget = null;
}
}
return singleTarget;
}
private CompletableFuture<Map<Address, Response>> performAsyncRemoteInvocation(Collection<Address> recipients,
ReplicableCommand command,
DeliverOrder deliverOrder,
boolean broadcast,
Address singleTarget) {
if (broadcast) {
logCommand(command, "all");
sendCommandToAll(command, Request.NO_REQUEST_ID, deliverOrder);
} else if (singleTarget != null) {
logCommand(command, singleTarget);
sendCommand(singleTarget, command, Request.NO_REQUEST_ID, deliverOrder, true, true);
} else {
logCommand(command, recipients);
sendCommand(recipients, command, Request.NO_REQUEST_ID, deliverOrder, true);
}
return EMPTY_RESPONSES_FUTURE;
}
private CompletableFuture<Map<Address, Response>> performSyncRemoteInvocation(
Collection<Address> targets, ReplicableCommand command, ResponseMode mode, long timeout,
ResponseFilter responseFilter, DeliverOrder deliverOrder, boolean ignoreLeavers, boolean sendStaggeredRequest,
boolean broadcast, Address singleTarget) {
CompletionStage<Map<Address, Response>> request;
if (sendStaggeredRequest) {
FilterMapResponseCollector collector = new FilterMapResponseCollector(responseFilter, false, targets.size());
request = invokeCommandStaggered(targets, command, collector, deliverOrder, timeout, TimeUnit.MILLISECONDS);
} else {
if (singleTarget != null) {
ResponseCollector<Map<Address, Response>> collector =
ignoreLeavers ? SingletonMapResponseCollector.ignoreLeavers() : SingletonMapResponseCollector.validOnly();
request = invokeCommand(singleTarget, command, collector, deliverOrder, timeout, TimeUnit.MILLISECONDS);
} else {
ResponseCollector<Map<Address, Response>> collector;
if (mode == ResponseMode.WAIT_FOR_VALID_RESPONSE) {
collector = new FilterMapResponseCollector(responseFilter, false, targets.size());
} else if (responseFilter != null) {
collector = new FilterMapResponseCollector(responseFilter, true, targets.size());
} else {
collector = MapResponseCollector.ignoreLeavers(ignoreLeavers, targets.size());
}
if (broadcast) {
request = invokeCommandOnAll(command, collector, deliverOrder, timeout, TimeUnit.MILLISECONDS);
} else {
request = invokeCommand(targets, command, collector, deliverOrder, timeout, TimeUnit.MILLISECONDS);
}
}
}
return request.toCompletableFuture();
}
public void sendToAll(ReplicableCommand command, DeliverOrder deliverOrder) {
logCommand(command, "all");
sendCommandToAll(command, Request.NO_REQUEST_ID, deliverOrder);
}
/**
* Send a command to the entire cluster.
*/
private void sendCommandToAll(ReplicableCommand command, long requestId, DeliverOrder deliverOrder) {
Message message = new BytesMessage();
marshallRequest(message, command, requestId);
setMessageFlags(message, deliverOrder, true);
send(message);
}
private void logRequest(long requestId, ReplicableCommand command, Object targets, String type) {
if (log.isTraceEnabled())
log.tracef("%s sending %s request %d to %s: %s", address, type, requestId, targets, command);
}
private void logCommand(ReplicableCommand command, Object targets) {
if (log.isTraceEnabled())
log.tracef("%s sending command to %s: %s", address, targets, command);
}
public JChannel getChannel() {
return channel;
}
private void updateSitesView(Collection<String> sitesUp, Collection<String> sitesDown) {
if (isSiteCoordinator()) {
Set<String> reachableSites = getSitesView();
log.tracef("Sites view changed: up %s, down %s, new view is %s", sitesUp, sitesDown, reachableSites);
XSITE.receivedXSiteClusterView(reachableSites);
}
if (sitesUp.isEmpty()) {
return;
}
if (isCoordinator()) {
globalXSiteAdminOperations.onSitesUp(sitesUp);
} else {
//for the case where the coordinator isn't the site master.
//TODO improve this by checking if the coordinator is a site master or not.
sendTo(getCoordinator(), new XSiteViewNotificationCommand(sitesUp), DeliverOrder.NONE);
}
}
private void siteUnreachable(String site) {
if (unreachableSites.putIfAbsent(site, SiteUnreachableReason.SITE_UNREACHABLE_EVENT) != null) {
// only one thread handling the events. The other threads can be "dropped".
return;
}
try {
cancelRequestsFromSite(site);
} finally {
unreachableSites.remove(site, SiteUnreachableReason.SITE_UNREACHABLE_EVENT);
}
}
private void cancelRequestsFromSite(String site) {
requests.forEach(request -> {
if (request instanceof SingleSiteRequest) {
((SingleSiteRequest<?>) request).sitesUnreachable(site);
}
});
}
/**
* Send a command to multiple targets.
*/
private void sendCommand(Collection<Address> targets, ReplicableCommand command, long requestId,
DeliverOrder deliverOrder, boolean checkView) {
Objects.requireNonNull(targets);
Message message = new BytesMessage();
marshallRequest(message, command, requestId);
setMessageFlags(message, deliverOrder, true);
Message copy = message;
for (Iterator<Address> it = targets.iterator(); it.hasNext(); ) {
Address address = it.next();
if (checkView && !clusterView.contains(address))
continue;
if (address.equals(getAddress()))
continue;
copy.dest(toJGroupsAddress(address));
send(copy);
// Send a different Message instance to each target
if (it.hasNext()) {
copy = copy.copy(true, true);
}
}
}
TimeService getTimeService() {
return timeService;
}
ScheduledExecutorService getTimeoutExecutor() {
return timeoutExecutor;
}
void processMessage(Message message) {
org.jgroups.Address src = message.src();
short flags = message.getFlags();
byte[] buffer = message.getArray();
int offset = message.getOffset();
int length = message.getLength();
RequestCorrelator.Header header = message.getHeader(HEADER_ID);
byte type;
long requestId;
if (header != null) {
type = header.type;
requestId = header.requestId();
} else {
type = SINGLE_MESSAGE;
requestId = Request.NO_REQUEST_ID;
}
if (!running) {
if (log.isTraceEnabled())
log.tracef("Ignoring message received before start or after stop");
if (type == REQUEST) {
sendResponse(src, CacheNotFoundResponse.INSTANCE, requestId, null);
}
return;
}
switch (type) {
case SINGLE_MESSAGE:
case REQUEST:
processRequest(src, flags, buffer, offset, length, requestId);
break;
case RESPONSE:
processResponse(src, buffer, offset, length, requestId);
break;
default:
CLUSTER.invalidMessageType(type, src);
}
}
private void sendResponse(org.jgroups.Address target, Response response, long requestId, ReplicableCommand command) {
if (log.isTraceEnabled())
log.tracef("%s sending response for request %d to %s: %s", getAddress(), requestId, target, response);
ByteBuffer bytes;
JChannel channel = this.channel;
if (channel == null) {
// Avoid NPEs during stop()
return;
}
try {
bytes = marshaller.objectToBuffer(response);
} catch (Throwable t) {
try {
// this call should succeed (all exceptions are serializable)
Exception e = t instanceof Exception ? ((Exception) t) : new CacheException(t);
bytes = marshaller.objectToBuffer(new ExceptionResponse(e));
} catch (Throwable tt) {
if (channel.isConnected()) {
CLUSTER.errorSendingResponse(requestId, target, command);
}
return;
}
}
try {
Message message = new BytesMessage(target).setFlag(REPLY_FLAGS, false);
message.setArray(bytes.getBuf(), bytes.getOffset(), bytes.getLength());
RequestCorrelator.Header header = new RequestCorrelator.Header(RESPONSE, requestId,
CORRELATOR_ID);
message.putHeader(HEADER_ID, header);
channel.send(message);
} catch (Throwable t) {
if (channel.isConnected()) {
CLUSTER.errorSendingResponse(requestId, target, command);
}
}
}
private void processRequest(org.jgroups.Address src, short flags, byte[] buffer, int offset, int length,
long requestId) {
try {
DeliverOrder deliverOrder = decodeDeliverMode(flags);
if (src.equals(((JGroupsAddress) getAddress()).getJGroupsAddress())) {
// DISCARD ignores the DONT_LOOPBACK flag, see https://issues.jboss.org/browse/JGRP-2205
if (log.isTraceEnabled())
log.tracef("Ignoring request %d from self without total order", requestId);
return;
}
ReplicableCommand command = (ReplicableCommand) marshaller.objectFromByteBuffer(buffer, offset, length);
Reply reply;
if (requestId != Request.NO_REQUEST_ID) {
if (log.isTraceEnabled())
log.tracef("%s received request %d from %s: %s", getAddress(), requestId, src, command);
reply = response -> sendResponse(src, response, requestId, command);
} else {
if (log.isTraceEnabled())
log.tracef("%s received command from %s: %s", getAddress(), src, command);
reply = Reply.NO_OP;
}
if (src instanceof SiteAddress) {
String originSite = ((SiteAddress) src).getSite();
XSiteReplicateCommand<?> xsiteCommand = (XSiteReplicateCommand<?>) command;
xsiteCommand.setOriginSite(originSite);
invocationHandler.handleFromRemoteSite(originSite, xsiteCommand, reply, deliverOrder);
} else {
invocationHandler.handleFromCluster(fromJGroupsAddress(src), command, reply, deliverOrder);
}
} catch (Throwable t) {
CLUSTER.errorProcessingRequest(requestId, src, t);
Exception e = t instanceof Exception ? ((Exception) t) : new CacheException(t);
sendResponse(src, new ExceptionResponse(e), requestId, null);
}
}
private void processResponse(org.jgroups.Address src, byte[] buffer, int offset, int length, long requestId) {
try {
Response response;
if (length == 0) {
// Empty buffer signals the ForkChannel with this name is not running on the remote node
response = CacheNotFoundResponse.INSTANCE;
} else {
response = (Response) marshaller.objectFromByteBuffer(buffer, offset, length);
if (response == null) {
response = SuccessfulResponse.SUCCESSFUL_EMPTY_RESPONSE;
}
}
if (log.isTraceEnabled())
log.tracef("%s received response for request %d from %s: %s", getAddress(), requestId, src, response);
Address address = fromJGroupsAddress(src);
requests.addResponse(requestId, address, response);
} catch (Throwable t) {
CLUSTER.errorProcessingResponse(requestId, src, t);
}
}
private DeliverOrder decodeDeliverMode(short flags) {
boolean oob = org.jgroups.util.Util.isFlagSet(flags, Message.Flag.OOB);
return oob ? DeliverOrder.NONE : DeliverOrder.PER_SENDER;
}
private RELAY2 findRelay2() {
return channel.getProtocolStack().findProtocol(RELAY2.class);
}
@Override
public void channelConnected(JChannel channel) {
if (isMetricsEnabled()) {
MetricsCollector mc = metricsCollector.wired();
clusters.computeIfAbsent(channel, c -> {
String name = c.clusterName();
String nodeName;
org.jgroups.Address addr = c.getAddress();
if (addr != null) {
nodeName = addr.toString();
} else {
nodeName = c.getName();
}
Set<Object> metrics = new HashSet<>();
for (Protocol protocol : c.getProtocolStack().getProtocols()) {
Collection<MBeanMetadata.AttributeMetadata> attributes = JGroupsMetricsMetadata.PROTOCOL_METADATA.get(protocol.getClass());
if (attributes != null && !attributes.isEmpty()) {
metrics.addAll(mc.registerMetrics(protocol, attributes, METRICS_PREFIX + name + '_' + protocol.getName().toLowerCase() + '_', null, nodeName));
}
}
return metrics;
});
}
}
@Override
public void channelDisconnected(JChannel channel) {
if (isMetricsEnabled()) {
MetricsCollector mc = metricsCollector.wired();
Set<Object> metrics = clusters.remove(channel);
if (metrics != null) {
for (Object metric : metrics) {
mc.unregisterMetric(metric);
}
}
}
}
@Override
public void channelClosed(JChannel channel) {
// NO-OP
}
private boolean isMetricsEnabled() {
return configuration.metrics().enabled() && metricsCollector.wired() != null;
}
private class ChannelCallbacks implements RouteStatusListener, UpHandler {
@Override
public void sitesUp(String... sites) {
updateSitesView(Arrays.asList(sites), Collections.emptyList());
for (String upSite : sites) {
unreachableSites.remove(upSite, SiteUnreachableReason.SITE_DOWN_EVENT);
}
}
@Override
public void sitesDown(String... sites) {
updateSitesView(Collections.emptyList(), Arrays.asList(sites));
List<String> requestsToCancel = new ArrayList<>(sites.length);
for (String downSite : sites) {
// if there is something stored in the map, do not try to cancel the requests.
if (unreachableSites.put(downSite, SiteUnreachableReason.SITE_DOWN_EVENT) == null) {
requestsToCancel.add(downSite);
}
}
requestsToCancel.forEach(JGroupsTransport.this::cancelRequestsFromSite);
}
@Override
public UpHandler setLocalAddress(org.jgroups.Address a) {
//no-op
return this;
}
@Override
public Object up(Event evt) {
switch (evt.getType()) {
case Event.VIEW_CHANGE:
receiveClusterView(evt.getArg());
break;
case Event.SITE_UNREACHABLE:
SiteMaster site_master = evt.getArg();
String site = site_master.getSite();
siteUnreachable(site);
break;
}
return null;
}
@Override
public Object up(Message msg) {
processMessage(msg);
return null;
}
@Override
public void up(MessageBatch batch) {
batch.forEach(message -> {
// Removed messages are null
if (message == null)
return;
// Regular (non-OOB) messages must be processed in-order
// Normally a batch should either have only OOB or only regular messages,
// but we check for every message to be on the safe side.
processMessage(message);
});
}
}
private enum SiteUnreachableReason {
SITE_DOWN_EVENT,
SITE_UNREACHABLE_EVENT
}
}
| 70,854
| 40.314869
| 170
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/JGroupsAddressCache.java
|
package org.infinispan.remoting.transport.jgroups;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.jgroups.Address;
import org.jgroups.util.ExtendedUUID;
import org.jgroups.util.NameCache;
/**
* Cache JGroupsAddress instances
*
* @author Dan Berindei
* @since 7.0
*/
public class JGroupsAddressCache {
private static final ConcurrentMap<Address, JGroupsAddress> addressCache =
new ConcurrentHashMap<>();
public static org.infinispan.remoting.transport.Address fromJGroupsAddress(Address jgroupsAddress) {
// New entries are rarely added added after startup, but computeIfAbsent synchronizes every time
JGroupsAddress ispnAddress = addressCache.get(jgroupsAddress);
if (ispnAddress != null) {
return ispnAddress;
}
return addressCache.computeIfAbsent(jgroupsAddress, uuid -> {
if (jgroupsAddress instanceof ExtendedUUID) {
return new JGroupsTopologyAwareAddress((ExtendedUUID) jgroupsAddress);
} else {
return new JGroupsAddress(jgroupsAddress);
}
});
}
static void pruneAddressCache() {
// Prune the JGroups addresses & LocalUUIDs no longer in the UUID cache from the our address cache
addressCache.forEach((address, ignore) -> {
if (NameCache.get(address) == null) {
addressCache.remove(address);
}
});
}
}
| 1,439
| 31.727273
| 104
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/JGroupsTopologyAwareAddress.java
|
package org.infinispan.remoting.transport.jgroups;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.InstanceReusingAdvancedExternalizer;
import org.infinispan.marshall.core.Ids;
import org.infinispan.remoting.transport.TopologyAwareAddress;
import org.jgroups.util.ExtendedUUID;
import org.jgroups.util.NameCache;
import org.jgroups.util.Util;
/**
* An encapsulation of a JGroups {@link ExtendedUUID} with a site id, a rack id, and a machine id.
*
* @author Bela Ban
* @since 5.0
*/
public class JGroupsTopologyAwareAddress extends JGroupsAddress implements TopologyAwareAddress {
private static final byte[] SITE_KEY = Util.stringToBytes("site-id");
private static final byte[] RACK_KEY = Util.stringToBytes("rack-id");
private static final byte[] MACHINE_KEY = Util.stringToBytes("machine-id");
public static ExtendedUUID randomUUID(String name, String siteId, String rackId, String machineId) {
ExtendedUUID uuid = ExtendedUUID.randomUUID(name);
if (name != null) {
NameCache.add(uuid, name);
}
addId(uuid, SITE_KEY, siteId);
addId(uuid, RACK_KEY, rackId);
addId(uuid, MACHINE_KEY, machineId);
return uuid;
}
private static void addId(ExtendedUUID uuid, byte[] key, String stringValue) {
if (stringValue != null) {
uuid.put(key, Util.stringToBytes(stringValue));
}
}
public JGroupsTopologyAwareAddress(ExtendedUUID address) {
super(address);
}
@Override
public String getSiteId() {
return getString(SITE_KEY);
}
@Override
public String getRackId() {
return getString(RACK_KEY);
}
@Override
public String getMachineId() {
return getString(MACHINE_KEY);
}
public boolean matches(String siteId, String rackId, String machineId) {
return checkComponent(SITE_KEY, siteId) &&
checkComponent(RACK_KEY, rackId) &&
checkComponent(MACHINE_KEY, machineId);
}
@Override
public boolean isSameSite(TopologyAwareAddress addr) {
if (addr instanceof JGroupsTopologyAwareAddress) {
ExtendedUUID otherUUID = ((JGroupsTopologyAwareAddress) addr).topologyAddress();
return checkComponent(SITE_KEY, otherUUID);
}
return checkComponent(SITE_KEY, addr.getSiteId());
}
@Override
public boolean isSameRack(TopologyAwareAddress addr) {
if (addr instanceof JGroupsTopologyAwareAddress) {
ExtendedUUID otherUUID = ((JGroupsTopologyAwareAddress) addr).topologyAddress();
return checkComponent(SITE_KEY, otherUUID) && checkComponent(RACK_KEY, otherUUID);
}
return checkComponent(SITE_KEY, addr.getSiteId()) && checkComponent(RACK_KEY, addr.getRackId());
}
@Override
public boolean isSameMachine(TopologyAwareAddress addr) {
if (addr instanceof JGroupsTopologyAwareAddress) {
ExtendedUUID otherUUID = ((JGroupsTopologyAwareAddress) addr).topologyAddress();
return checkComponent(SITE_KEY, otherUUID) && checkComponent(RACK_KEY, otherUUID) &&
checkComponent(MACHINE_KEY, otherUUID);
}
return checkComponent(SITE_KEY, addr.getSiteId()) && checkComponent(RACK_KEY, addr.getRackId()) &&
checkComponent(MACHINE_KEY, addr.getMachineId());
}
private boolean checkComponent(byte[] key, ExtendedUUID uuid) {
return checkComponent(key, uuid.get(key));
}
private boolean checkComponent(byte[] key, String stringValue) {
return checkComponent(key, Util.stringToBytes(stringValue));
}
private boolean checkComponent(byte[] key, byte[] expectedValue) {
return Arrays.equals(getBytes(key), expectedValue);
}
private String getString(byte[] key) {
return Util.bytesToString(getBytes(key));
}
private byte[] getBytes(byte[] key) {
return topologyAddress().get(key);
}
private ExtendedUUID topologyAddress() {
return (ExtendedUUID) address;
}
public static final class Externalizer extends InstanceReusingAdvancedExternalizer<JGroupsTopologyAwareAddress> {
public Externalizer() {
super(false);
}
@Override
public void doWriteObject(ObjectOutput output, JGroupsTopologyAwareAddress address) throws IOException {
try {
org.jgroups.util.Util.writeAddress(address.address, output);
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
public JGroupsTopologyAwareAddress doReadObject(ObjectInput unmarshaller) throws IOException, ClassNotFoundException {
try {
org.jgroups.Address jgroupsAddress = (org.jgroups.Address) org.jgroups.util.Util.readAddress(unmarshaller);
// Note: Use org.jgroups.Address, not the concrete UUID class.
// Otherwise applications that only use local caches would have to bundle the JGroups jar,
// because the verifier needs to check the arguments of fromJGroupsAddress
// even if this method is never called.
return (JGroupsTopologyAwareAddress) JGroupsAddressCache.fromJGroupsAddress(jgroupsAddress);
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
public Set<Class<? extends JGroupsTopologyAwareAddress>> getTypeClasses() {
return Collections.singleton(JGroupsTopologyAwareAddress.class);
}
@Override
public Integer getId() {
return Ids.JGROUPS_TOPOLOGY_AWARE_ADDRESS;
}
}
}
| 5,663
| 33.748466
| 124
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/JGroupsStateMachineAdapter.java
|
package org.infinispan.remoting.transport.jgroups;
import java.io.DataInput;
import java.io.DataOutput;
import java.util.Objects;
import org.infinispan.commons.io.ByteBuffer;
import org.infinispan.commons.io.ByteBufferImpl;
import org.infinispan.commons.util.Util;
import org.infinispan.remoting.transport.raft.RaftStateMachine;
import org.jgroups.raft.StateMachine;
/**
* An adapter that converts JGroups {@link StateMachine} calls to {@link RaftStateMachine}.
*
* @since 14.0
*/
class JGroupsStateMachineAdapter<T extends RaftStateMachine> implements StateMachine {
private final T stateMachine;
JGroupsStateMachineAdapter(T stateMachine) {
this.stateMachine = Objects.requireNonNull(stateMachine);
}
@Override
public byte[] apply(byte[] data, int offset, int length, boolean serialize_response) throws Exception {
// serialize_response ignored.
ByteBuffer buffer = stateMachine.apply(ByteBufferImpl.create(data, offset, length));
return buffer == null ? Util.EMPTY_BYTE_ARRAY : buffer.trim();
}
@Override
public void readContentFrom(DataInput in) throws Exception {
stateMachine.readStateFrom(in);
}
@Override
public void writeContentTo(DataOutput out) throws Exception {
stateMachine.writeStateTo(out);
}
T getStateMachine() {
return stateMachine;
}
}
| 1,354
| 27.829787
| 106
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/SuspectException.java
|
package org.infinispan.remoting.transport.jgroups;
import org.infinispan.commons.CacheException;
import org.infinispan.remoting.transport.Address;
/**
* Thrown when a member is suspected during remote method invocation
*
* @author Bela Ban
* @author Galder Zamarreño
* @since 4.0
*/
public class SuspectException extends CacheException {
private static final long serialVersionUID = -2965599037371850141L;
private final Address suspect;
public SuspectException() {
super();
this.suspect = null;
}
public SuspectException(String msg) {
super(msg);
this.suspect = null;
}
public SuspectException(String msg, Address suspect) {
super(msg);
this.suspect = suspect;
}
public SuspectException(String msg, Throwable cause) {
super(msg, cause);
this.suspect = null;
}
public SuspectException(String msg, Address suspect, Throwable cause) {
super(msg, cause);
this.suspect = suspect;
}
public Address getSuspect() {
return suspect;
}
public static boolean isSuspectExceptionInChain(Throwable t) {
Throwable innerThrowable = t;
do {
if (innerThrowable instanceof SuspectException) {
return true;
}
} while ((innerThrowable = innerThrowable.getCause()) != null);
return false;
}
}
| 1,355
| 22.37931
| 74
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/JGroupsRaftManager.java
|
package org.infinispan.remoting.transport.jgroups;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import org.infinispan.commons.io.ByteBuffer;
import org.infinispan.commons.io.ByteBufferImpl;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.remoting.transport.raft.RaftChannel;
import org.infinispan.remoting.transport.raft.RaftChannelConfiguration;
import org.infinispan.remoting.transport.raft.RaftManager;
import org.infinispan.remoting.transport.raft.RaftStateMachine;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.jgroups.JChannel;
import org.jgroups.fork.ForkChannel;
import org.jgroups.protocols.FORK;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.protocols.raft.ELECTION;
import org.jgroups.protocols.raft.FileBasedLog;
import org.jgroups.protocols.raft.InMemoryLog;
import org.jgroups.protocols.raft.NO_DUPES;
import org.jgroups.protocols.raft.RAFT;
import org.jgroups.protocols.raft.REDIRECT;
import org.jgroups.raft.RaftHandle;
import org.jgroups.raft.StateMachine;
import org.jgroups.stack.ProtocolStack;
/**
* A {@link RaftManager} implementation that use JGroups-RAFT protocol.
* <p>
* This implementation uses multiple {@link ForkChannel}, one of each {@link RaftStateMachine} registered, and it
* expects the {@link FORK} protocol to be present in the main {@link JChannel}.
*
* @since 14.0
*/
class JGroupsRaftManager implements RaftManager {
private static final Log log = LogFactory.getLog(JGroupsRaftManager.class);
private final JChannel mainChannel;
private final Collection<String> raftMembers;
private final String raftId;
private final String persistenceDirectory;
private final Map<String, JgroupsRaftChannel<? extends RaftStateMachine>> raftStateMachineMap = new ConcurrentHashMap<>(16);
JGroupsRaftManager(GlobalConfiguration globalConfiguration, JChannel mainChannel) {
if (JGroupsTransport.findFork(mainChannel) == null) {
throw log.forkProtocolRequired();
}
this.mainChannel = mainChannel;
raftMembers = globalConfiguration.transport().raftMembers();
raftId = globalConfiguration.transport().nodeName();
persistenceDirectory = globalConfiguration.globalState().enabled() ?
globalConfiguration.globalState().persistentLocation() :
null;
}
@Override
public <T extends RaftStateMachine> T getOrRegisterStateMachine(String channelName, Supplier<T> supplier, RaftChannelConfiguration configuration) {
Objects.requireNonNull(channelName);
Objects.requireNonNull(supplier);
Objects.requireNonNull(configuration);
//noinspection unchecked
JgroupsRaftChannel<T> raftChannel = (JgroupsRaftChannel<T>) raftStateMachineMap.computeIfAbsent(channelName, s -> createRaftChannel(s, configuration, supplier));
return raftChannel == null ? null : raftChannel.stateMachine();
}
@Override
public boolean isRaftAvailable() {
return true;
}
@Override
public boolean hasLeader(String channelName) {
JgroupsRaftChannel<?> raftChannel = raftStateMachineMap.get(channelName);
return raftChannel != null && raftChannel.raftHandle.leader() != null;
}
@Override
public String raftId() {
return raftId;
}
private <T extends RaftStateMachine> JgroupsRaftChannel<T> createRaftChannel(String name, RaftChannelConfiguration configuration, Supplier<? extends T> supplier) {
ForkChannel forkChannel = null;
try {
forkChannel = createForkChannel(name, configuration);
forkChannel.connect(name);
} catch (Exception e) {
log.errorCreatingForkChannel(name, e);
if (forkChannel != null) {
// disconnect removes channel from FORK protocol
forkChannel.disconnect();
} else {
JGroupsTransport.findFork(mainChannel).remove(name);
}
return null;
}
T stateMachine = supplier.get();
JgroupsRaftChannel<T> raftChannel = new JgroupsRaftChannel<>(name, forkChannel, stateMachine);
stateMachine.init(raftChannel);
return raftChannel;
}
private ForkChannel createForkChannel(String name, RaftChannelConfiguration configuration) throws Exception {
RAFT raftProtocol = new RAFT();
switch (configuration.logMode()) {
case VOLATILE:
raftProtocol
.logClass(InMemoryLog.class.getCanonicalName())
.logPrefix(name + "-" + raftId);
break;
case PERSISTENT:
if (persistenceDirectory == null) {
throw log.raftGlobalStateDisabled();
}
raftProtocol
.logClass(FileBasedLog.class.getCanonicalName())
.logPrefix(Path.of(persistenceDirectory, name, raftId).toAbsolutePath().toString());
break;
default:
throw new IllegalStateException();
}
raftProtocol
.members(raftMembers)
.raftId(raftId);
return new ForkChannel(mainChannel, name, name, new ELECTION(), raftProtocol, new REDIRECT());
}
/**
* Inserts the {@link NO_DUPES} protocol in the main {@link JChannel}.
* <p>
* The {@link NO_DUPES} protocol must be set in the main {@link JChannel} below {@link GMS} to detect and reject any
* duplicated members with the same "raft-id".
*/
@Override
public void start() {
// NO_DUPES need to be on the main channel
ProtocolStack protocolStack = mainChannel.getProtocolStack();
if (protocolStack.findProtocol(NO_DUPES.class) != null) {
// already in main channel
return;
}
GMS gms = protocolStack.findProtocol(GMS.class);
if (gms == null) {
// GMS not found, unable to use NO_DUPES
return;
}
protocolStack.insertProtocolInStack(new NO_DUPES(), gms, ProtocolStack.Position.BELOW);
}
@Override
public void stop() {
raftStateMachineMap.values().forEach(JgroupsRaftChannel::disconnect);
raftStateMachineMap.clear();
}
private static class JgroupsRaftChannel<T extends RaftStateMachine> implements RaftChannel {
private final RaftHandle raftHandle;
private final String channelName;
private final JChannel forkedChannel;
JgroupsRaftChannel(String channelName, JChannel forkedChannel, RaftStateMachine stateMachine) {
this.channelName = channelName;
this.forkedChannel = forkedChannel;
raftHandle = new RaftHandle(forkedChannel, new JGroupsStateMachineAdapter<>(stateMachine));
}
@Override
public CompletionStage<ByteBuffer> send(ByteBuffer buffer) {
try {
return raftHandle.setAsync(buffer.getBuf(), buffer.getOffset(), buffer.getLength()).thenApply(ByteBufferImpl::create);
} catch (Exception e) {
return CompletableFuture.failedFuture(e);
}
}
@Override
public String channelName() {
return channelName;
}
@Override
public String raftId() {
return raftHandle.raftId();
}
T stateMachine() {
StateMachine stateMachine = raftHandle.stateMachine();
assert stateMachine instanceof JGroupsStateMachineAdapter;
//noinspection unchecked
return ((JGroupsStateMachineAdapter<T>) stateMachine).getStateMachine();
}
void disconnect() {
// removes the forked channel from FORK
forkedChannel.disconnect();
}
}
}
| 7,817
| 36.052133
| 167
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/RaftUtil.java
|
package org.infinispan.remoting.transport.jgroups;
import org.infinispan.commons.util.Util;
/**
* Utility methods for jgroups-raft
*
* @since 14.0
*/
public enum RaftUtil {
;
private static final boolean RAFT_IN_CLASSPATH;
private static final String RAFT_CLASS = "org.jgroups.protocols.raft.RAFT";
static {
boolean raftFound = true;
try {
Util.loadClassStrict(RAFT_CLASS, JGroupsRaftManager.class.getClassLoader());
} catch (ClassNotFoundException e) {
raftFound = false;
}
RAFT_IN_CLASSPATH = raftFound;
}
public static boolean isRaftAvailable() {
return RAFT_IN_CLASSPATH;
}
}
| 663
| 21.896552
| 85
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/NamedSocketFactory.java
|
package org.infinispan.remoting.transport.jgroups;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import javax.net.ServerSocketFactory;
import org.jgroups.util.SocketFactory;
import org.jgroups.util.Util;
/**
* A {@link SocketFactory} which allows setting a callback to configure the sockets using a supplied name.
*
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 13.0
**/
public class NamedSocketFactory implements SocketFactory {
private final Supplier<javax.net.SocketFactory> socketFactory;
private final Supplier<ServerSocketFactory> serverSocketFactory;
private String name;
private BiConsumer<String, Socket> socketConfigurator = (c, s) -> {};
private BiConsumer<String, ServerSocket> serverSocketConfigurator = (c, s) -> {};
public NamedSocketFactory(Supplier<javax.net.SocketFactory> socketFactory, Supplier<ServerSocketFactory> serverSocketFactory) {
this.socketFactory = socketFactory;
this.serverSocketFactory = serverSocketFactory;
}
NamedSocketFactory(NamedSocketFactory original, String name) {
this.socketFactory = original.socketFactory;
this.serverSocketFactory = original.serverSocketFactory;
this.socketConfigurator = original.socketConfigurator;
this.serverSocketConfigurator = original.serverSocketConfigurator;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private Socket configureSocket(Socket socket) {
socketConfigurator.accept(name, socket);
return socket;
}
private ServerSocket configureSocket(ServerSocket socket) {
serverSocketConfigurator.accept(name, socket);
return socket;
}
@Override
public Socket createSocket(String s) throws IOException {
return configureSocket(socketFactory.get().createSocket());
}
@Override
public Socket createSocket(String s, String host, int port) throws IOException {
return configureSocket(socketFactory.get().createSocket(host, port));
}
@Override
public Socket createSocket(String s, InetAddress host, int port) throws IOException {
return configureSocket(socketFactory.get().createSocket(host, port));
}
@Override
public Socket createSocket(String s, String host, int port, InetAddress localHost, int localPort) throws IOException {
return configureSocket(socketFactory.get().createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(String s, InetAddress host, int port, InetAddress localHost, int localPort) throws IOException {
return configureSocket(socketFactory.get().createSocket(host, port, localHost, localPort));
}
@Override
public ServerSocket createServerSocket(String s) throws IOException {
return configureSocket(serverSocketFactory.get().createServerSocket());
}
@Override
public ServerSocket createServerSocket(String s, int port) throws IOException {
return configureSocket(serverSocketFactory.get().createServerSocket(port));
}
@Override
public ServerSocket createServerSocket(String s, int port, int backlog) throws IOException {
return configureSocket(serverSocketFactory.get().createServerSocket(port, backlog));
}
@Override
public ServerSocket createServerSocket(String s, int port, int backlog, InetAddress bindAddress) throws IOException {
return configureSocket(serverSocketFactory.get().createServerSocket(port, backlog, bindAddress));
}
public DatagramSocket createDatagramSocket(String service_name) throws SocketException {
return new DatagramSocket();
}
public DatagramSocket createDatagramSocket(String service_name, SocketAddress bindaddr) throws SocketException {
return new DatagramSocket(bindaddr);
}
public DatagramSocket createDatagramSocket(String service_name, int port) throws SocketException {
return new DatagramSocket(port);
}
public DatagramSocket createDatagramSocket(String service_name, int port, InetAddress laddr) throws SocketException {
return new DatagramSocket(port, laddr);
}
public MulticastSocket createMulticastSocket(String service_name) throws IOException {
return new MulticastSocket();
}
public MulticastSocket createMulticastSocket(String service_name, int port) throws IOException {
return new MulticastSocket(port);
}
public MulticastSocket createMulticastSocket(String service_name, SocketAddress bindaddr) throws IOException {
return new MulticastSocket(bindaddr);
}
@Override
public void close(Socket socket) throws IOException {
Util.close(socket);
}
@Override
public void close(ServerSocket serverSocket) throws IOException {
Util.close(serverSocket);
}
@Override
public void close(DatagramSocket datagramSocket) {
Util.close(datagramSocket);
}
}
| 5,197
| 33.423841
| 130
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/jgroups/ThreadPoolProbeHandler.java
|
package org.infinispan.remoting.transport.jgroups;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.infinispan.executors.LazyInitializingBlockingTaskAwareExecutorService;
import org.infinispan.util.concurrent.BlockingTaskAwareExecutorServiceImpl;
import org.jgroups.stack.DiagnosticsHandler;
/**
* A probe handler for {@link org.jgroups.tests.Probe} protocol is JGroups.
* <p>
* It contains a single key and returns the information about the remote thread pool executor service.
*
* @author Pedro Ruivo
* @since 9.0
*/
class ThreadPoolProbeHandler implements DiagnosticsHandler.ProbeHandler {
private static final String KEY = "ispn-remote";
private volatile ExecutorService executor;
@Override
public Map<String, String> handleProbe(String... keys) {
if (keys == null || keys.length == 0) {
return null;
}
ThreadPoolExecutor exec = extract(executor);
if (exec == null) {
return null;
}
Map<String, String> map = new HashMap<>();
for (String key : keys) {
switch (key) {
case KEY:
map.put("active-thread", String.valueOf(exec.getActiveCount()));
map.put("min-thread", String.valueOf(exec.getCorePoolSize()));
map.put("max-thread", String.valueOf(exec.getMaximumPoolSize()));
map.put("current-pool-size", String.valueOf(exec.getPoolSize()));
map.put("largest-pool-size", String.valueOf(exec.getLargestPoolSize()));
map.put("keep-alive", String.valueOf(exec.getKeepAliveTime(TimeUnit.MILLISECONDS)));
map.put("queue-size", String.valueOf(exec.getQueue().size()));
break;
}
}
return map.isEmpty() ? null : map;
}
@Override
public String[] supportedKeys() {
return new String[]{KEY};
}
void updateThreadPool(ExecutorService executorService) {
if (executorService != null) {
this.executor = executorService;
}
}
private static ThreadPoolExecutor extract(ExecutorService service) {
if (service instanceof ThreadPoolExecutor) {
return (ThreadPoolExecutor) service;
} else if (service instanceof BlockingTaskAwareExecutorServiceImpl) {
return extract(((BlockingTaskAwareExecutorServiceImpl) service).getExecutorService());
} else if (service instanceof LazyInitializingBlockingTaskAwareExecutorService) {
return extract(((LazyInitializingBlockingTaskAwareExecutorService) service).getExecutorService());
}
return null; //we don't know how to handle the remaining cases.
}
}
| 2,766
| 35.407895
| 107
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/MultiTargetRequest.java
|
package org.infinispan.remoting.transport.impl;
import static org.infinispan.util.logging.Log.CLUSTER;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.infinispan.commons.util.Util;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.transport.AbstractRequest;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollector;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import net.jcip.annotations.GuardedBy;
/**
* Request implementation that waits for responses from multiple target nodes.
*
* @author Dan Berindei
* @since 9.1
*/
public class MultiTargetRequest<T> extends AbstractRequest<T> {
private static final Log log = LogFactory.getLog(MultiTargetRequest.class);
@GuardedBy("responseCollector")
private final Address[] targets;
@GuardedBy("responseCollector")
private int missingResponses;
public MultiTargetRequest(ResponseCollector<T> responseCollector, long requestId, RequestRepository repository,
Collection<Address> targets, Address excluded) {
super(requestId, responseCollector, repository);
this.targets = new Address[targets.size()];
int i = 0;
for (Address target : targets) {
if (excluded == null || !excluded.equals(target)) {
this.targets[i++] = target;
}
}
this.missingResponses = i;
if (missingResponses == 0)
complete(responseCollector.finish());
}
protected int getTargetsSize() {
return targets.length;
}
/**
* @return target {@code i}, or {@code null} if a response was already added for target {@code i}.
*/
protected Address getTarget(int i) {
return targets[i];
}
@Override
public void onResponse(Address sender, Response response) {
try {
boolean isDone = false;
T result;
synchronized (responseCollector) {
if (missingResponses <= 0) {
// The request is completed, nothing to do
return;
}
boolean validSender = false;
for (int i = 0; i < targets.length; i++) {
Address target = targets[i];
if (target != null && target.equals(sender)) {
validSender = true;
targets[i] = null;
missingResponses--;
break;
}
}
if (!validSender) {
// A broadcast may be sent to nodes added to the cluster view after the request was created,
// so we should just ignore responses from unexpected senders.
if (log.isTraceEnabled())
log.tracef("Ignoring unexpected response to request %d from %s: %s", requestId, sender, response);
return;
}
result = responseCollector.addResponse(sender, response);
if (result != null) {
isDone = true;
// Make sure to ignore any other responses
missingResponses = 0;
} else if (missingResponses <= 0) {
isDone = true;
result = responseCollector.finish();
}
}
// Complete the request outside the lock, in case it has to run blocking callbacks
if (isDone) {
complete(result);
}
} catch (Throwable t) {
completeExceptionally(t);
}
}
@Override
public boolean onNewView(Set<Address> members) {
boolean targetRemoved = false;
try {
boolean isDone = false;
T result = null;
synchronized (responseCollector) {
if (missingResponses <= 0) {
// The request is completed, must not modify ResponseObject.
return false;
}
for (int i = 0; i < targets.length; i++) {
Address target = targets[i];
if (target != null && !members.contains(target)) {
targets[i] = null;
missingResponses--;
targetRemoved = true;
if (log.isTraceEnabled()) log.tracef("Target %s of request %d left the cluster view", target, requestId);
result = responseCollector.addResponse(target, CacheNotFoundResponse.INSTANCE);
if (result != null) {
isDone = true;
break;
}
}
}
// No more targets remaining
if (!isDone && missingResponses <= 0) {
result = responseCollector.finish();
isDone = true;
}
}
// Complete the request outside the lock, in case it has to run blocking callbacks
if (isDone) {
complete(result);
}
} catch (Throwable t) {
completeExceptionally(t);
}
return targetRemoved;
}
@Override
protected void onTimeout() {
synchronized (responseCollector) {
if (missingResponses <= 0) {
// The request is already completed.
return;
}
// Don't add more responses to the collector after this
this.missingResponses = 0;
}
String targetsWithoutResponses = Arrays.stream(targets)
.filter(Objects::nonNull)
.map(Object::toString)
.collect(Collectors.joining(","));
completeExceptionally(CLUSTER.requestTimedOut(requestId, targetsWithoutResponses, Util.prettyPrintTime(getTimeoutMs())));
}
}
| 5,916
| 33.005747
| 127
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/FilterMapResponseCollector.java
|
package org.infinispan.remoting.transport.impl;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.rpc.ResponseFilter;
import org.infinispan.remoting.rpc.ResponseMode;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollectors;
import org.infinispan.remoting.transport.ValidResponseCollector;
import org.infinispan.remoting.transport.jgroups.JGroupsTransport;
/**
* Response collector supporting {@link JGroupsTransport#invokeRemotelyAsync(Collection, ReplicableCommand, ResponseMode, long, ResponseFilter, DeliverOrder, boolean)}.
*
* <p>This class is not thread-safe by itself. It expects an {@link org.infinispan.remoting.transport.AbstractRequest}
* to handle synchronization.</p>
*/
public class FilterMapResponseCollector extends ValidResponseCollector<Map<Address, Response>> {
private final HashMap<Address, Response> map;
private final ResponseFilter filter;
private final boolean waitForAll;
public FilterMapResponseCollector(ResponseFilter filter, boolean waitForAll, int expectedSize) {
this.map = new HashMap<>(expectedSize);
this.filter = filter;
this.waitForAll = waitForAll;
}
@Override
protected Map<Address, Response> addValidResponse(Address sender, ValidResponse response) {
boolean isDone;
if (filter != null) {
boolean isAcceptable = filter.isAcceptable(response, sender);
// We don't need to call needMoreResponses() with ResponseMode.WAIT_FOR_VALID_RESPONSE
isDone = waitForAll ? !filter.needMoreResponses() : isAcceptable;
} else {
isDone = !waitForAll;
}
map.put(sender, response);
return isDone ? map : null;
}
@Override
protected Map<Address, Response> addTargetNotFound(Address sender) {
// Even without a filter, we don't complete the request on invalid responses like CacheNotFoundResponse
map.put(sender, CacheNotFoundResponse.INSTANCE);
return null;
}
@Override
protected Map<Address, Response> addException(Address sender, Exception exception) {
throw ResponseCollectors.wrapRemoteException(sender, exception);
}
@Override
public Map<Address, Response> finish() {
return map;
}
}
| 2,587
| 37.626866
| 168
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/XSiteResponseImpl.java
|
package org.infinispan.remoting.transport.impl;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import org.infinispan.commons.time.TimeService;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.transport.XSiteResponse;
import org.infinispan.xsite.XSiteBackup;
/**
* Default implementation of {@link XSiteResponse}.
* <p>
* It implements {@link BiConsumer} in order to be notified when the {@link org.infinispan.remoting.transport.jgroups.SingleSiteRequest}
* is completed.
*
* @author Pedro Ruivo
* @since 10.0
*/
public class XSiteResponseImpl<O> extends CompletableFuture<O> implements XSiteResponse<O>, BiConsumer<ValidResponse, Throwable> {
private final long sendTimeNanos;
private final TimeService timeService;
private final XSiteBackup xSiteBackup;
private volatile long durationNanos;
public XSiteResponseImpl(TimeService timeService, XSiteBackup xSiteBackup) {
this.sendTimeNanos = timeService.time();
this.timeService = timeService;
this.xSiteBackup = xSiteBackup;
}
@Override
public void whenCompleted(XSiteResponseCompleted xSiteResponseCompleted) {
this.whenComplete((aVoid, throwable) -> xSiteResponseCompleted
.onCompleted(xSiteBackup, sendTimeNanos, durationNanos, throwable));
}
@Override
public void accept(ValidResponse response, Throwable throwable) {
durationNanos = timeService.timeDuration(sendTimeNanos, TimeUnit.NANOSECONDS);
if (throwable != null) {
completeExceptionally(throwable);
} else {
//noinspection unchecked
complete((O) response.getResponseValue());
}
}
}
| 1,745
| 32.576923
| 136
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/RequestRepository.java
|
package org.infinispan.remoting.transport.impl;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* @author Dan Berindei
* @since 9.0
*/
public class RequestRepository {
private static final Log log = LogFactory.getLog(RequestRepository.class);
private final ConcurrentHashMap<Long, Request<?>> requests;
private final AtomicLong nextRequestId = new AtomicLong(1);
public RequestRepository() {
requests = new ConcurrentHashMap<>();
}
public long newRequestId() {
long requestId = nextRequestId.getAndIncrement();
// Make sure NO_REQUEST_ID is never used for a request
if (requestId == Request.NO_REQUEST_ID) {
requestId = nextRequestId.getAndIncrement();
}
return requestId;
}
public void addRequest(Request<?> request) {
long requestId = request.getRequestId();
Request existingRequest = requests.putIfAbsent(requestId, request);
if (existingRequest != null) {
throw new IllegalStateException("Duplicate request id " + requestId);
}
}
public void addResponse(long requestId, Address sender, Response response) {
Request<?> request = requests.get(requestId);
if (request == null) {
if (log.isTraceEnabled())
log.tracef("Ignoring response for non-existent request %d from %s: %s", requestId, sender, response);
return;
}
request.onResponse(sender, response);
}
public void removeRequest(long requestId) {
requests.remove(requestId);
}
public void forEach(Consumer<Request<?>> consumer) {
requests.forEach((id, request) -> consumer.accept(request));
}
}
| 1,927
| 30.096774
| 113
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/PassthroughMapResponseCollector.java
|
package org.infinispan.remoting.transport.impl;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollector;
/**
* Receive responses from multiple nodes, without checking that the responses are valid.
*
* @author Dan Berindei
* @since 9.1
*/
public class PassthroughMapResponseCollector implements ResponseCollector<Map<Address, Response>> {
private Map<Address, Response> map;
public PassthroughMapResponseCollector(int expectedSize) {
map = new HashMap<>(expectedSize);
}
@Override
public Map<Address, Response> addResponse(Address sender, Response response) {
map.put(sender, response);
return null;
}
@Override
public Map<Address, Response> finish() {
return map;
}
}
| 882
| 24.970588
| 99
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/SingleResponseCollector.java
|
package org.infinispan.remoting.transport.impl;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollectors;
import org.infinispan.remoting.transport.ValidSingleResponseCollector;
/**
* Response collector for a single response.
*
* Throws a {@link org.infinispan.remoting.transport.jgroups.SuspectException} if the node leaves
* or has already left the cluster.
*
* @author Dan Berindei
* @since 9.2
*/
public class SingleResponseCollector extends ValidSingleResponseCollector<ValidResponse> {
private static final SingleResponseCollector VALID_ONLY = new SingleResponseCollector();
public static SingleResponseCollector validOnly() {
return VALID_ONLY;
}
@Override
protected ValidResponse withValidResponse(Address sender, ValidResponse response) {
return response;
}
@Override
protected ValidResponse targetNotFound(Address sender) {
throw ResponseCollectors.remoteNodeSuspected(sender);
}
}
| 1,058
| 30.147059
| 97
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/Request.java
|
package org.infinispan.remoting.transport.impl;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.transport.Address;
/**
* A remote command invocation request.
*
* @author Dan Berindei
* @since 9.1
*/
public interface Request<T> extends CompletionStage<T> {
long NO_REQUEST_ID = 0;
/**
* @return The unique request id.
*/
long getRequestId();
/**
* Called when a response is received for this response.
*/
void onResponse(Address sender, Response response);
/**
* Called when the node received a new cluster view.
*
* @return {@code true} if any of the request targets is not in the view.
*/
boolean onNewView(Set<Address> members);
/**
* Complete the request with an exception and release its resources.
*/
void cancel(Exception cancellationException);
}
| 934
| 22.375
| 76
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/MapResponseCollector.java
|
package org.infinispan.remoting.transport.impl;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commons.util.Experimental;
import org.infinispan.remoting.RemoteException;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.rpc.ResponseFilter;
import org.infinispan.remoting.rpc.ResponseMode;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollectors;
import org.infinispan.remoting.transport.ValidResponseCollector;
import org.infinispan.remoting.transport.jgroups.JGroupsTransport;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* Response collector supporting {@link JGroupsTransport#invokeRemotelyAsync(Collection, ReplicableCommand, ResponseMode, long, ResponseFilter, DeliverOrder, boolean)}.
*
* @author Dan Berindei
* @since 9.2
*/
@Experimental
public abstract class MapResponseCollector extends ValidResponseCollector<Map<Address, Response>> {
private static final int DEFAULT_EXPECTED_SIZE = 4;
protected final HashMap<Address, Response> map;
private Exception exception;
public static MapResponseCollector validOnly(int expectedSize) {
return new ValidOnly(expectedSize);
}
public static MapResponseCollector validOnly() {
return new ValidOnly(DEFAULT_EXPECTED_SIZE);
}
public static MapResponseCollector ignoreLeavers(int expectedSize) {
return new IgnoreLeavers(expectedSize);
}
public static MapResponseCollector ignoreLeavers() {
return new IgnoreLeavers(DEFAULT_EXPECTED_SIZE);
}
public static MapResponseCollector ignoreLeavers(boolean ignoreLeavers, int expectedSize) {
return ignoreLeavers ? ignoreLeavers(expectedSize) : validOnly(expectedSize);
}
public static MapResponseCollector ignoreLeavers(boolean ignoreLeavers) {
return ignoreLeavers ? ignoreLeavers() : validOnly();
}
private MapResponseCollector(int expectedSize) {
this.map = new HashMap<>(expectedSize);
}
@Override
protected Map<Address, Response> addException(Address sender, Exception exception) {
recordException(ResponseCollectors.wrapRemoteException(sender, exception));
return null;
}
protected void recordException(Exception e) {
if (this.exception == null) {
this.exception = e;
} else if (this.exception instanceof RemoteException) {
this.exception.addSuppressed(e);
}
}
@Override
protected Map<Address, Response> addValidResponse(Address sender, ValidResponse response) {
map.put(sender, response);
return null;
}
@Override
public Map<Address, Response> finish() {
if (exception != null) {
throw CompletableFutures.asCompletionException(exception);
}
return map;
}
private static class ValidOnly extends MapResponseCollector {
ValidOnly(int expectedSize) {
super(expectedSize);
}
@Override
protected Map<Address, Response> addTargetNotFound(Address sender) {
recordException(ResponseCollectors.remoteNodeSuspected(sender));
return null;
}
}
private static class IgnoreLeavers extends MapResponseCollector {
IgnoreLeavers(int expectedSize) {
super(expectedSize);
}
@Override
protected Map<Address, Response> addTargetNotFound(Address sender) {
map.put(sender, CacheNotFoundResponse.INSTANCE);
return null;
}
}
}
| 3,754
| 31.652174
| 168
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/SingleTargetRequest.java
|
package org.infinispan.remoting.transport.impl;
import static org.infinispan.util.logging.Log.CLUSTER;
import java.util.Objects;
import java.util.Set;
import org.infinispan.commons.util.Util;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.transport.AbstractRequest;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollector;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import net.jcip.annotations.GuardedBy;
/**
* Request implementation that waits for a response from a single target node.
*
* @author Dan Berindei
* @since 9.1
*/
public class SingleTargetRequest<T> extends AbstractRequest<T> {
private static final Log log = LogFactory.getLog(SingleTargetRequest.class);
// Only changes from non-null to null
private Address target;
public SingleTargetRequest(ResponseCollector<T> wrapper, long requestId, RequestRepository repository, Address target) {
super(requestId, wrapper, repository);
this.target = target;
}
@Override
public void onResponse(Address sender, Response response) {
try {
T result;
synchronized (responseCollector) {
if (target != null && !target.equals(sender)) {
log.tracef("Received unexpected response to request %d from %s, target is %s", requestId, sender, target);
}
result = addResponse(sender, response);
}
complete(result);
} catch (Exception e) {
completeExceptionally(e);
}
}
@Override
public boolean onNewView(Set<Address> members) {
try {
T result;
synchronized (responseCollector) {
boolean targetIsMissing = target != null && !members.contains(target);
if (!targetIsMissing) {
return false;
}
result = addResponse(target, CacheNotFoundResponse.INSTANCE);
}
complete(result);
} catch (Exception e) {
completeExceptionally(e);
}
return true;
}
@GuardedBy("responseCollector")
private T addResponse(Address sender, Response response) {
target = null;
T result = responseCollector.addResponse(sender, response);
if (result == null) {
result = responseCollector.finish();
}
return result;
}
@Override
protected void onTimeout() {
// The target might be null
String targetString = Objects.toString(target);
completeExceptionally(CLUSTER.requestTimedOut(requestId, targetString, Util.prettyPrintTime(getTimeoutMs())));
}
}
| 2,732
| 29.707865
| 123
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/VoidResponseCollector.java
|
package org.infinispan.remoting.transport.impl;
import org.infinispan.remoting.RemoteException;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollectors;
import org.infinispan.remoting.transport.ValidResponseCollector;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* Response collector that discards successful responses and returns {@code null}.
*
* <p>Throws an exception if it receives at least one exception response, or if
* a node is suspected and {@code ignoreLeavers == true}.
*
* @author Dan Berindei
* @since 9.2
*/
public class VoidResponseCollector extends ValidResponseCollector<Void> {
//note: can't be a singleton since it has state (exception field)
private final boolean ignoreLeavers;
private Exception exception;
public static VoidResponseCollector validOnly() {
return new VoidResponseCollector(false);
}
public static VoidResponseCollector ignoreLeavers() {
return new VoidResponseCollector(true);
}
private VoidResponseCollector(boolean ignoreLeavers) {
this.ignoreLeavers = ignoreLeavers;
}
@Override
protected Void addTargetNotFound(Address sender) {
if (!ignoreLeavers) {
recordException(ResponseCollectors.remoteNodeSuspected(sender));
}
return null;
}
@Override
protected Void addException(Address sender, Exception exception) {
recordException(ResponseCollectors.wrapRemoteException(sender, exception));
return null;
}
private void recordException(Exception e) {
if (this.exception == null) {
this.exception = e;
} else if (this.exception instanceof RemoteException) {
this.exception.addSuppressed(e);
}
}
@Override
protected Void addValidResponse(Address sender, ValidResponse response) {
return null;
}
@Override
public Void finish() {
if (exception != null) {
throw CompletableFutures.asCompletionException(exception);
}
return null;
}
}
| 2,116
| 28.402778
| 82
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/PassthroughSingleResponseCollector.java
|
package org.infinispan.remoting.transport.impl;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollector;
/**
* RPC to a single node, without any validity checks.
*
* @author Dan Berindei
* @since 9.1
*/
public class PassthroughSingleResponseCollector implements ResponseCollector<Response> {
public static final PassthroughSingleResponseCollector INSTANCE = new PassthroughSingleResponseCollector();
// No need for new instances
private PassthroughSingleResponseCollector() {}
@Override
public Response addResponse(Address sender, Response response) {
return response;
}
@Override
public Response finish() {
return null;
}
}
| 778
| 25.862069
| 110
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/EmptyRaftManager.java
|
package org.infinispan.remoting.transport.impl;
import java.util.function.Supplier;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.remoting.transport.raft.RaftChannelConfiguration;
import org.infinispan.remoting.transport.raft.RaftManager;
import org.infinispan.remoting.transport.raft.RaftStateMachine;
/**
* A NO-OP implementation of {@link RaftManager}.
* <p>
* This implementation is used when RAFT is not supported by the {@link Transport}.
*
* @since 14.0
*/
public enum EmptyRaftManager implements RaftManager {
INSTANCE;
@Override
public <T extends RaftStateMachine> T getOrRegisterStateMachine(String channelName, Supplier<T> supplier, RaftChannelConfiguration configuration) {
return null;
}
@Override
public boolean isRaftAvailable() {
return false;
}
@Override
public boolean hasLeader(String channelName) {
return false;
}
@Override
public String raftId() {
return null;
}
@Override
public void start() {
}
@Override
public void stop() {
}
}
| 1,081
| 20.215686
| 150
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/SiteUnreachableXSiteResponse.java
|
package org.infinispan.remoting.transport.impl;
import static org.infinispan.util.logging.Log.CLUSTER;
import java.util.concurrent.CompletableFuture;
import org.infinispan.commons.time.TimeService;
import org.infinispan.remoting.transport.SiteAddress;
import org.infinispan.remoting.transport.XSiteResponse;
import org.infinispan.remoting.transport.jgroups.SuspectException;
import org.infinispan.xsite.XSiteBackup;
/**
* A {@link XSiteResponse} which is competed with a {@link SuspectException}.
*
* @since 14.0
*/
public class SiteUnreachableXSiteResponse<T> extends CompletableFuture<T> implements XSiteResponse<T> {
private final XSiteBackup backup;
private final long sendTimeNanos;
private final SuspectException exception;
public SiteUnreachableXSiteResponse(XSiteBackup backup, TimeService timeService) {
this.backup = backup;
this.sendTimeNanos = timeService.time();
this.exception = CLUSTER.remoteNodeSuspected(new SiteAddress(backup.getSiteName()));
completeExceptionally(exception);
}
@Override
public void whenCompleted(XSiteResponseCompleted xSiteResponseCompleted) {
xSiteResponseCompleted.onCompleted(backup, sendTimeNanos, -1, exception);
}
@Override
public String toString() {
return "SiteUnreachableXSiteResponse{" +
"backup=" + backup +
", sendTimeNanos=" + sendTimeNanos +
'}';
}
}
| 1,420
| 31.295455
| 103
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/impl/SingletonMapResponseCollector.java
|
package org.infinispan.remoting.transport.impl;
import static org.infinispan.util.logging.Log.CLUSTER;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.rpc.ResponseFilter;
import org.infinispan.remoting.rpc.ResponseMode;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ValidSingleResponseCollector;
import org.infinispan.remoting.transport.jgroups.JGroupsTransport;
/**
* Response collector supporting {@link JGroupsTransport#invokeRemotelyAsync(Collection, ReplicableCommand, ResponseMode, long, ResponseFilter, DeliverOrder, boolean)}.
*
* @author Dan Berindei
* @since 9.2
*/
public class SingletonMapResponseCollector
extends ValidSingleResponseCollector<Map<Address, Response>> {
private static final SingletonMapResponseCollector VALID_ONLY = new SingletonMapResponseCollector(false);
private static final SingletonMapResponseCollector IGNORE_LEAVERS = new SingletonMapResponseCollector(true);
private final boolean ignoreLeavers;
public static SingletonMapResponseCollector validOnly() {
return VALID_ONLY;
}
public static SingletonMapResponseCollector ignoreLeavers() {
return IGNORE_LEAVERS;
}
private SingletonMapResponseCollector(boolean ignoreLeavers) {
this.ignoreLeavers = ignoreLeavers;
}
@Override
protected Map<Address, Response> withValidResponse(Address sender, ValidResponse response) {
return Collections.singletonMap(sender, response);
}
@Override
protected Map<Address, Response> targetNotFound(Address sender) {
if (!ignoreLeavers) {
throw CLUSTER.remoteNodeSuspected(sender);
}
return Collections.singletonMap(sender, CacheNotFoundResponse.INSTANCE);
}
}
| 2,084
| 34.948276
| 168
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/raft/package-info.java
|
/**
* RAFT interfaces for internal usage.
*
* @api.private
*/
package org.infinispan.remoting.transport.raft;
| 114
| 15.428571
| 47
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/raft/RaftManager.java
|
package org.infinispan.remoting.transport.raft;
import java.util.function.Supplier;
import org.infinispan.commons.api.Lifecycle;
/**
* Use this class to create and register {@link RaftStateMachine}.
* <p>
* Each {@link RaftStateMachine} is identified by its name and they are independent of each other; each {@link
* RaftStateMachine} has it own {@link RaftChannel}.
*
* @since 14.0
*/
public interface RaftManager extends Lifecycle {
/**
* Register a {@link RaftStateMachine}.
* <p>
* If the RAFT protocol is not supported, this method return {@code null}. If a {@link RaftStateMachine} already
* exists with name {@code channelName}, the existing instance is returned.
* <p>
* If {@link #isRaftAvailable()} return {@code false}, this method always returns {@code null}.
*
* @param channelName The name identifying the {@link RaftStateMachine}.
* @param supplier The factory to create a new instance of {@link RaftStateMachine}.
* @param configuration The {@link RaftChannelConfiguration} for the {@link RaftChannel}.
* @param <T> The concrete {@link RaftStateMachine} implementation.
* @return The {@link RaftStateMachine} instance of {@code null} if unable to create or configure the {@link
* RaftChannel}.
*/
<T extends RaftStateMachine> T getOrRegisterStateMachine(String channelName, Supplier<T> supplier, RaftChannelConfiguration configuration);
/**
* @return {@code true} if the RAFT protocol is available to be used, {@code false} otherwise.
*/
boolean isRaftAvailable();
/**
* Check if a RAFT leader is elected for the {@link RaftStateMachine} with name {@code channelName}.
*
* @param channelName The name identifying the {@link RaftStateMachine}.
* @return {@code true} if the leader exists, {@code false} otherwise.
*/
boolean hasLeader(String channelName);
/**
* @return This node raft-id.
*/
String raftId();
}
| 1,975
| 37
| 142
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/raft/RaftStateMachine.java
|
package org.infinispan.remoting.transport.raft;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.infinispan.commons.io.ByteBuffer;
/**
* A state machine interface.
*
* @since 14.0
*/
public interface RaftStateMachine {
/**
* Initializes this instance with the {@link RaftChannel} to be used to send the data.
*
* @param raftChannel The {@link RaftChannel} instance.
*/
void init(RaftChannel raftChannel);
/**
* Applies the data from the RAFT protocol.
* <p>
* The RAFT protocol ensures that this method is invoked in the same order in all the members.
*
* @param buffer The data.
* @return A {@link ByteBuffer} with the response.
* @throws Exception If it fails to apply the data in {@link ByteBuffer}.
*/
ByteBuffer apply(ByteBuffer buffer) throws Exception;
/**
* Discards current state and reads the state from {@link DataInput}.
* <p>
* There are 2 scenarios where this method may be invoked:
* <p>
* 1. when this node starts, it may receive the state from the RAFT leader. 2. when this node starts, it reads the
* persisted snapshot if available.
*
* @param dataInput The {@link DataInput} with the snapshot.
* @throws IOException If an I/O error happens.
*/
void readStateFrom(DataInput dataInput) throws IOException;
/**
* Writes the current state into the {@link DataOutput}.
* <p>
* This method is invoked to truncate the RAFT logs.
*
* @param dataOutput The {@link DataOutput} to store the snapshot.
* @throws IOException If an I/O error happens.
*/
void writeStateTo(DataOutput dataOutput) throws IOException;
}
| 1,718
| 28.637931
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/raft/RaftChannel.java
|
package org.infinispan.remoting.transport.raft;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import org.infinispan.commons.io.ByteBuffer;
/**
* A channel abstraction to invoke commands on the RAFT channel.
*
* @since 14.0
*/
public interface RaftChannel {
/**
* Sends a {@link ByteBuffer} to the RAFT channel to be ordered by the RAFT leader.
* <p>
* After the RAFT leader commits, {@link RaftStateMachine#apply(ByteBuffer)} is invoked with the {@link ByteBuffer}
* and its return value used to complete the {@link CompletionStage}.
*
* @param buffer The data to send.
* @return A {@link CompletionStage} which is completed with the {@link RaftStateMachine#apply(ByteBuffer)} response.
*/
CompletionStage<ByteBuffer> send(ByteBuffer buffer);
/**
* @return The channel name used to register the {@link RaftStateMachine} via {@link
* RaftManager#getOrRegisterStateMachine(String, Supplier, RaftChannelConfiguration)}.
*/
String channelName();
/**
* @return The node's raft-id.
*/
String raftId();
}
| 1,113
| 29.108108
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/remoting/transport/raft/RaftChannelConfiguration.java
|
package org.infinispan.remoting.transport.raft;
import java.util.Objects;
/**
* A configuration object to configure {@link RaftChannel}.
*
* @since 14.0
*/
public final class RaftChannelConfiguration {
private final RaftLogMode logMode;
private RaftChannelConfiguration(RaftLogMode logMode) {
this.logMode = logMode;
}
/**
* @return The {@link RaftLogMode}.
* @see RaftLogMode
*/
public RaftLogMode logMode() {
return logMode;
}
@Override
public String toString() {
return "RaftChannelConfiguration{" +
"logMode=" + logMode +
'}';
}
public static class Builder {
private RaftLogMode logMode = RaftLogMode.PERSISTENT;
/**
* Sets the RAFT log mode.
* <p>
* The log mode can be {@link RaftLogMode#PERSISTENT} (default) or {@link RaftLogMode#VOLATILE}.
*
* @param logMode The log mode.
* @return This instance.
* @see RaftLogMode
*/
public Builder logMode(RaftLogMode logMode) {
this.logMode = Objects.requireNonNull(logMode);
return this;
}
/**
* @return The {@link RaftChannelConfiguration} created.
*/
public RaftChannelConfiguration build() {
return new RaftChannelConfiguration(logMode);
}
}
public enum RaftLogMode {
/**
* The RAFT log entries are stored in memory only.
* <p>
* It improves the performance, but it can cause data lost.
*/
VOLATILE,
/**
* The RAFT log entries are persisted before applying to the {@link RaftStateMachine}.
* <p>
* This is the default option.
*/
PERSISTENT
}
}
| 1,723
| 21.986667
| 102
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/filter/package-info.java
|
/**
* Provides capabilities around filtering and converting entries that are found in the cache or cache store/loader.
* @api.public
*/
package org.infinispan.filter;
| 170
| 27.5
| 115
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/filter/CompositeKeyValueFilter.java
|
package org.infinispan.filter;
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.factories.ComponentRegistry;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.marshall.core.Ids;
import org.infinispan.metadata.Metadata;
/**
* Allows AND-composing several key/value filters.
*
* @author wburns
* @since 7.0
*/
@Scope(Scopes.NONE)
public class CompositeKeyValueFilter<K, V> implements KeyValueFilter<K, V> {
private final KeyValueFilter<? super K, ? super V> filters[];
public CompositeKeyValueFilter(KeyValueFilter<? super K, ? super V>... filters) {
this.filters = filters;
}
@Override
public boolean accept(K key, V value, Metadata metadata) {
for (KeyValueFilter<? super K, ? super V> filter : filters) {
if (!filter.accept(key, value, metadata)) {
return false;
}
}
return true;
}
@Inject
protected void injectDependencies(ComponentRegistry cr) {
for (KeyValueFilter<? super K, ? super V> f : filters) {
cr.wireDependencies(f);
}
}
public static class Externalizer extends AbstractExternalizer<CompositeKeyValueFilter> {
@Override
public Set<Class<? extends CompositeKeyValueFilter>> getTypeClasses() {
return Collections.singleton(CompositeKeyValueFilter.class);
}
@Override
public void writeObject(ObjectOutput output, CompositeKeyValueFilter object) throws IOException {
UnsignedNumeric.writeUnsignedInt(output, object.filters.length);
for (KeyValueFilter filter : object.filters) {
output.writeObject(filter);
}
}
@Override
public CompositeKeyValueFilter readObject(ObjectInput input) throws IOException, ClassNotFoundException {
int filtersSize = UnsignedNumeric.readUnsignedInt(input);
KeyValueFilter[] filters = new KeyValueFilter[filtersSize];
for (int i = 0; i < filtersSize; ++i) {
filters[i] = (KeyValueFilter)input.readObject();
}
return new CompositeKeyValueFilter(filters);
}
@Override
public Integer getId() {
return Ids.COMPOSITE_KEY_VALUE_FILTER;
}
}
}
| 2,519
| 30.898734
| 111
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/filter/KeyValueFilter.java
|
package org.infinispan.filter;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.metadata.Metadata;
import net.jcip.annotations.ThreadSafe;
/**
* A filter for keys with their values.
*
* @author William Burns
* @since 7.0
*/
@ThreadSafe
public interface KeyValueFilter<K, V> {
/**
* @param key key to test
* @param value value to use (could be null for the case of removal)
* @param metadata metadata
* @return true if the given key is accepted by this filter.
*/
boolean accept(K key, V value, Metadata metadata);
/**
* @return The desired data format to be used in the {@link #accept(Object, Object, Metadata)} operation.
* If null, the filter will receive data as it's stored.
*/
default MediaType format() {
return MediaType.APPLICATION_OBJECT;
}
}
| 843
| 25.375
| 108
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/filter/AbstractKeyValueFilterConverter.java
|
package org.infinispan.filter;
import org.infinispan.metadata.Metadata;
/**
* This is a base class that should be used when implementing a KeyValueFilterConverter that provides default
* implementations for the {@link org.infinispan.filter.KeyValueFilter#accept(Object, Object, org.infinispan.metadata.Metadata)}
* and {@link org.infinispan.filter.Converter#convert(Object, Object, org.infinispan.metadata.Metadata)} methods so they just call the
* {@link org.infinispan.filter.KeyValueFilterConverter#filterAndConvert(Object, Object, org.infinispan.metadata.Metadata)}
* method and then do the right thing.
*
* @author wburns
* @since 7.0
*/
public abstract class AbstractKeyValueFilterConverter<K, V, C> implements KeyValueFilterConverter<K, V, C> {
@Override
public final C convert(K key, V value, Metadata metadata) {
return filterAndConvert(key, value, metadata);
}
@Override
public final boolean accept(K key, V value, Metadata metadata) {
return filterAndConvert(key, value, metadata) != null;
}
}
| 1,047
| 39.307692
| 134
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/filter/KeyValueFilterConverterFactory.java
|
package org.infinispan.filter;
/**
* Factory for {@link org.infinispan.filter.KeyValueFilterConverter} instances
*
* @author gustavonalle
* @since 8.0
*/
public interface KeyValueFilterConverterFactory<K, V, C> {
KeyValueFilterConverter<K, V, C> getFilterConverter();
}
| 281
| 19.142857
| 78
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/filter/Converter.java
|
package org.infinispan.filter;
import org.infinispan.metadata.Metadata;
/**
* Converter that can be used to transform a given entry to a different value. This is especially useful to reduce
* overall payload of given data that is sent for the given event when a notification is send to a cluster listener as
* this will have to be serialized and sent across the network when the cluster listener is not local to the node who
* owns the given key.
*
* @author William Burns
* @since 7.0
*/
public interface Converter<K, V, C> {
C convert(K key, V value, Metadata metadata);
}
| 589
| 33.705882
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/filter/AcceptAllKeyValueFilter.java
|
package org.infinispan.filter;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.marshall.core.Ids;
import org.infinispan.metadata.Metadata;
/**
* A key value filter that accepts all entries found.
* <p>
* <b>This filter should be used carefully as it may cause the operation to perform very slowly
* as all entries are accepted.</b>
*
* @author wburns
* @since 7.0
*/
public final class AcceptAllKeyValueFilter implements KeyValueFilter<Object, Object> {
private AcceptAllKeyValueFilter() {
}
private static class StaticHolder {
private static final AcceptAllKeyValueFilter INSTANCE = new AcceptAllKeyValueFilter();
}
public static AcceptAllKeyValueFilter getInstance() {
return StaticHolder.INSTANCE;
}
@Override
public boolean accept(Object key, Object value, Metadata metadata) {
return true;
}
public static final class Externalizer extends AbstractExternalizer<AcceptAllKeyValueFilter> {
@Override
public Set<Class<? extends AcceptAllKeyValueFilter>> getTypeClasses() {
return Collections.singleton(AcceptAllKeyValueFilter.class);
}
@Override
public void writeObject(ObjectOutput output, AcceptAllKeyValueFilter object) {
}
@Override
public AcceptAllKeyValueFilter readObject(ObjectInput input) {
return AcceptAllKeyValueFilter.getInstance();
}
@Override
public Integer getId() {
return Ids.ACCEPT_ALL_KEY_VALUE_FILTER;
}
}
}
| 1,643
| 26.4
| 97
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/filter/CacheFilters.java
|
package org.infinispan.filter;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.infinispan.CacheStream;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.util.Util;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.container.entries.NullCacheEntry;
import org.infinispan.container.impl.InternalEntryFactory;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.marshall.core.Ids;
import org.infinispan.metadata.Metadata;
/**
* Static factory class that contains utility methods that can be used for performing proper transformations from
* {@link KeyValueFilter}, {@link Converter} and {@link KeyValueFilterConverter} to appropriate distributed stream
* instances.
*/
public final class CacheFilters {
private CacheFilters() { }
/**
* Creates a new {@link Predicate} using the provided key value filter as a basis for the operation. This is useful
* for when using {@link Stream#filter(Predicate)} method on distributed streams. The key,
* value and metadata are all used to determine if the predicate returns true or not.
* @param filter the filter to utilize
* @param <K> key type
* @param <V> value type
* @return predicate based on the filter
*/
public static <K, V> Predicate<CacheEntry<K, V>> predicate(KeyValueFilter<? super K, ? super V> filter) {
return new KeyValueFilterAsPredicate<>(filter);
}
/**
* Creates a new {@link Function} using the provided converter as a basis for the operation. This is useful
* for when using {@link Stream#map(Function)} method on distributed streams. The key,
* value and metadata are all used to determine the converted value.
* @param converter the converter to utilize
* @param <K> key type
* @param <V> value type
* @param <C> converted value type
* @return function based on the converter
*/
public static <K, V, C> Function<CacheEntry<K, V>, CacheEntry<K, C>> function(
Converter<? super K, ? super V, C> converter) {
return new ConverterAsCacheEntryFunction<>(converter);
}
/**
* Creates a new {@link Function} using the provided filter convert. The {@link KeyValueFilterConverter#filterAndConvert(Object, Object, Metadata)}
* is invoked for every passed in CacheEntry. When a null value is returned from the filter converter instead of
* a null {@link CacheEntry} being returned, we instead return the {@link NullCacheEntry} as a sign of it. This
* allows this {@link Function} to be used in cases when a null value cannot be returned, such as reactive streams.
* <p>
* The {@link #notNullCacheEntryPredicate()} can be used to filter these values if needed.
* @param filterConverter the filter converter to utilize
* @param <K> key type
* @param <V> value type
* @param <C> converted value type
* @return function based on the filter converter
*/
public static <K, V, C> Function<CacheEntry<K, V>, CacheEntry<K, C>> converterToFunction(KeyValueFilterConverter<? super K, ? super V, C> filterConverter) {
return new FilterConverterAsCacheEntryFunction<>(filterConverter);
}
/**
* Provides a predicate that can be used to filter out null cache entry objects as well as placeholder "null" entries
* of {@link NullCacheEntry} that can be returned from methods such as {@link #converterToFunction(KeyValueFilterConverter)}.
* @param <K> entry key type
* @param <V> entry value type
* @return a predicate to filter null entries
*/
public static <K, V> Predicate<CacheEntry<K, V>> notNullCacheEntryPredicate() {
return NotNullCacheEntryPredicate.SINGLETON;
}
public static <K, V, C> CacheStream<K> filterAndConvertToKey(CacheStream<CacheEntry<K, V>> stream,
KeyValueFilterConverter<? super K, ? super V, C> filterConverter) {
// Have to use flatMap instead of map/filter as reactive streams spec doesn't allow null values
return stream.flatMap(new FilterConverterAsKeyFunction(filterConverter));
}
public static <K, V, C> CacheStream<C> filterAndConvertToValue(CacheStream<CacheEntry<K, V>> stream,
KeyValueFilterConverter<? super K, ? super V, C> filterConverter) {
// Have to use flatMap instead of map/filter as reactive streams spec doesn't allow null values
return stream.flatMap(new FilterConverterAsValueFunction(filterConverter));
}
/**
* Adds needed intermediate operations to the provided stream, returning a possibly new stream as a result of the
* operations. This method keeps the contract of filter and conversion being performed in only 1 call as the
* {@link KeyValueFilterConverter} was designed to do. The key,
* value and metadata are all used to determine whether the value is returned and the converted value.
* @param stream stream to perform the operations on
* @param filterConverter converter to apply
* @param <K>
* @param <V>
* @param <C>
* @return
*/
public static <K, V, C> Stream<CacheEntry<K, C>> filterAndConvert(Stream<CacheEntry<K, V>> stream,
KeyValueFilterConverter<? super K, ? super V, C> filterConverter) {
return stream.map(converterToFunction(filterConverter))
.filter(notNullCacheEntryPredicate());
}
public static <K, V, C> CacheStream<CacheEntry<K, C>> filterAndConvert(CacheStream<CacheEntry<K, V>> stream,
KeyValueFilterConverter<? super K, ? super V, C> filterConverter) {
return stream.map(converterToFunction(filterConverter))
.filter(notNullCacheEntryPredicate());
}
@Scope(Scopes.NONE)
static class NotNullCacheEntryPredicate<K, V> implements Predicate<CacheEntry<K, V>> {
private static final NotNullCacheEntryPredicate SINGLETON = new NotNullCacheEntryPredicate();
@Override
public boolean test(CacheEntry<K, V> kvCacheEntry) {
return kvCacheEntry != null && kvCacheEntry != NullCacheEntry.getInstance();
}
}
@Scope(Scopes.NONE)
static final class FilterConverterAsCacheEntryFunction<K, V, C> implements Function<CacheEntry<K, V>, CacheEntry<K, C>> {
private final KeyValueFilterConverter<? super K, ? super V, C> filterConverter;
private InternalEntryFactory factory;
FilterConverterAsCacheEntryFunction(KeyValueFilterConverter<? super K, ? super V, C> filterConverter) {
this.filterConverter = Objects.requireNonNull(filterConverter);
}
@Inject
public void inject(InternalEntryFactory factory, ComponentRegistry registry) {
this.factory = factory;
registry.wireDependencies(filterConverter);
}
@Override
public CacheEntry<K, C> apply(CacheEntry<K, V> kvCacheEntry) {
K key = kvCacheEntry.getKey();
V value = kvCacheEntry.getValue();
Metadata metadata = kvCacheEntry.getMetadata();
C converted = filterConverter.filterAndConvert(key, value, metadata);
if (converted == null) {
return NullCacheEntry.getInstance();
} else if (value == converted) {
return (CacheEntry<K, C>) kvCacheEntry;
}
return factory.create(key, converted, metadata);
}
}
@Scope(Scopes.NONE)
static final class KeyValueFilterAsPredicate<K, V> implements Predicate<CacheEntry<K, V>> {
private final KeyValueFilter<? super K, ? super V> filter;
public KeyValueFilterAsPredicate(KeyValueFilter<? super K, ? super V> filter) {
Objects.requireNonNull(filter);
this.filter = filter;
}
@Override
public boolean test(CacheEntry<K, V> kvCacheEntry) {
return filter.accept(kvCacheEntry.getKey(), kvCacheEntry.getValue(), kvCacheEntry.getMetadata());
}
@Inject
public void inject(ComponentRegistry registry) {
registry.wireDependencies(filter);
}
}
@Scope(Scopes.NONE)
static final class ConverterAsCacheEntryFunction<K, V, C> implements Function<CacheEntry<K, V>, CacheEntry<K, C>> {
private final Converter<? super K, ? super V, C> converter;
private InternalEntryFactory factory;
public ConverterAsCacheEntryFunction(Converter<? super K, ? super V, C> converter) {
Objects.requireNonNull(converter);
this.converter = converter;
}
@Inject
public void inject(InternalEntryFactory factory, ComponentRegistry registry) {
this.factory = factory;
registry.wireDependencies(converter);
}
@Override
public CacheEntry<K, C> apply(CacheEntry<K, V> kvCacheEntry) {
K key = kvCacheEntry.getKey();
V value = kvCacheEntry.getValue();
Metadata metadata = kvCacheEntry.getMetadata();
C converted = converter.convert(key, value, metadata);
if (value == converted) {
return (CacheEntry<K, C>) kvCacheEntry;
}
return factory.create(key, converted, metadata);
}
}
@Scope(Scopes.NONE)
static final class FilterConverterAsKeyFunction<K, V> implements Function<CacheEntry<K, V>, Stream<K>> {
private final KeyValueFilterConverter<? super K, ? super V, ?> converter;
public FilterConverterAsKeyFunction(KeyValueFilterConverter<? super K, ? super V, ? super K> converter) {
Objects.requireNonNull(converter);
this.converter = converter;
}
@Inject
public void inject(ComponentRegistry registry) {
registry.wireDependencies(converter);
}
@Override
public Stream<K> apply(CacheEntry<K, V> entry) {
Object converted = converter.filterAndConvert(entry.getKey(), entry.getValue(), entry.getMetadata());
if (converted == null) {
return Stream.empty();
}
return Stream.of(entry.getKey());
}
}
@Scope(Scopes.NONE)
static final class FilterConverterAsValueFunction<K, V, C> implements Function<CacheEntry<K, V>, Stream<C>> {
private final KeyValueFilterConverter<? super K, ? super V, C> converter;
public FilterConverterAsValueFunction(KeyValueFilterConverter<? super K, ? super V, C> converter) {
Objects.requireNonNull(converter);
this.converter = converter;
}
@Inject
public void inject(ComponentRegistry registry) {
registry.wireDependencies(converter);
}
@Override
public Stream<C> apply(CacheEntry<K, V> entry) {
C converted = converter.filterAndConvert(entry.getKey(), entry.getValue(), entry.getMetadata());
if (converted == null) {
return Stream.empty();
}
return Stream.of(converted);
}
}
public static final class CacheFiltersExternalizer implements AdvancedExternalizer<Object> {
private static final int KEY_VALUE_FILTER_PREDICATE = 0;
private static final int CONVERTER_FUNCTION = 1;
private static final int FILTER_CONVERTER_FUNCTION = 2;
private static final int FILTER_CONVERTER_VALUE_FUNCTION = 3;
private static final int NOT_NULL_CACHE_ENTRY_PREDICATE = 4;
private static final int FILTER_CONVERTER_KEY_FUNCTION = 5;
private final Map<Class<?>, Integer> objects = new HashMap<>();
public CacheFiltersExternalizer() {
objects.put(KeyValueFilterAsPredicate.class, KEY_VALUE_FILTER_PREDICATE);
objects.put(ConverterAsCacheEntryFunction.class, CONVERTER_FUNCTION);
objects.put(FilterConverterAsCacheEntryFunction.class, FILTER_CONVERTER_FUNCTION);
objects.put(FilterConverterAsKeyFunction.class, FILTER_CONVERTER_KEY_FUNCTION);
objects.put(FilterConverterAsValueFunction.class, FILTER_CONVERTER_VALUE_FUNCTION);
objects.put(NotNullCacheEntryPredicate.class, NOT_NULL_CACHE_ENTRY_PREDICATE);
}
@Override
public Set<Class<?>> getTypeClasses() {
return Util.asSet(KeyValueFilterAsPredicate.class, ConverterAsCacheEntryFunction.class,
FilterConverterAsCacheEntryFunction.class, FilterConverterAsKeyFunction.class,
FilterConverterAsValueFunction.class, NotNullCacheEntryPredicate.class);
}
@Override
public Integer getId() {
return Ids.CACHE_FILTERS;
}
@Override
public void writeObject(ObjectOutput output, Object object) throws IOException {
int number = objects.getOrDefault(object.getClass(), -1);
output.writeByte(number);
switch (number) {
case KEY_VALUE_FILTER_PREDICATE:
output.writeObject(((KeyValueFilterAsPredicate) object).filter);
break;
case CONVERTER_FUNCTION:
output.writeObject(((ConverterAsCacheEntryFunction) object).converter);
break;
case FILTER_CONVERTER_FUNCTION:
output.writeObject(((FilterConverterAsCacheEntryFunction) object).filterConverter);
break;
case FILTER_CONVERTER_KEY_FUNCTION:
output.writeObject(((FilterConverterAsKeyFunction) object).converter);
break;
case FILTER_CONVERTER_VALUE_FUNCTION:
output.writeObject(((FilterConverterAsValueFunction) object).converter);
break;
case NOT_NULL_CACHE_ENTRY_PREDICATE:
break;
default:
throw new IllegalArgumentException("Type " + number + " is not supported!");
}
}
@Override
public Object readObject(ObjectInput input) throws IOException, ClassNotFoundException {
int number = input.readUnsignedByte();
switch (number) {
case KEY_VALUE_FILTER_PREDICATE:
return new KeyValueFilterAsPredicate((KeyValueFilter) input.readObject());
case CONVERTER_FUNCTION:
return new ConverterAsCacheEntryFunction((Converter) input.readObject());
case FILTER_CONVERTER_FUNCTION:
return new FilterConverterAsCacheEntryFunction((KeyValueFilterConverter) input.readObject());
case FILTER_CONVERTER_KEY_FUNCTION:
return new FilterConverterAsKeyFunction((KeyValueFilterConverter) input.readObject());
case FILTER_CONVERTER_VALUE_FUNCTION:
return new FilterConverterAsValueFunction((KeyValueFilterConverter) input.readObject());
case NOT_NULL_CACHE_ENTRY_PREDICATE:
return NotNullCacheEntryPredicate.SINGLETON;
default:
throw new IllegalArgumentException("Found invalid number " + number);
}
}
}
}
| 15,049
| 42.371758
| 159
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/filter/NamedFactory.java
|
package org.infinispan.filter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface NamedFactory {
String name();
}
| 309
| 22.846154
| 44
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.