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/commands/functional/AbstractWriteKeyCommand.java
|
package org.infinispan.commands.functional;
import static org.infinispan.commons.util.Util.toStr;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.write.AbstractDataWriteCommand;
import org.infinispan.commands.write.ValueMatcher;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.impl.Params;
import org.infinispan.metadata.impl.PrivateMetadata;
public abstract class AbstractWriteKeyCommand<K, V> extends AbstractDataWriteCommand implements FunctionalCommand<K, V> {
Params params;
ValueMatcher valueMatcher;
boolean successful = true;
DataConversion keyDataConversion;
DataConversion valueDataConversion;
PrivateMetadata internalMetadata;
public AbstractWriteKeyCommand(Object key, ValueMatcher valueMatcher, int segment,
CommandInvocationId id, Params params,
DataConversion keyDataConversion,
DataConversion valueDataConversion) {
super(key, segment, params.toFlagsBitSet(), id);
this.valueMatcher = valueMatcher;
this.params = params;
this.keyDataConversion = keyDataConversion;
this.valueDataConversion = valueDataConversion;
}
public AbstractWriteKeyCommand() {
// No-op
}
@Override
public void init(ComponentRegistry componentRegistry) {
componentRegistry.wireDependencies(keyDataConversion);
componentRegistry.wireDependencies(valueDataConversion);
}
@Override
public ValueMatcher getValueMatcher() {
return valueMatcher;
}
@Override
public void setValueMatcher(ValueMatcher valueMatcher) {
this.valueMatcher = valueMatcher;
}
@Override
public boolean isSuccessful() {
return successful;
}
@Override
public Params getParams() {
return params;
}
@Override
public void fail() {
successful = false;
}
@Override
public String toString() {
return getClass().getSimpleName() +
" {key=" + toStr(key) +
", flags=" + printFlags() +
", commandInvocationId=" + commandInvocationId +
", params=" + params +
", valueMatcher=" + valueMatcher +
", successful=" + successful +
"}";
}
@Override
public DataConversion getKeyDataConversion() {
return keyDataConversion;
}
@Override
public DataConversion getValueDataConversion() {
return valueDataConversion;
}
@Override
public PrivateMetadata getInternalMetadata() {
return internalMetadata;
}
@Override
public void setInternalMetadata(PrivateMetadata internalMetadata) {
this.internalMetadata = internalMetadata;
}
}
| 2,814
| 27.15
| 121
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/ReadOnlyManyCommand.java
|
package org.infinispan.commands.functional;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Function;
import org.infinispan.commands.AbstractTopologyAffectedCommand;
import org.infinispan.commands.LocalCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView.ReadEntryView;
import org.infinispan.functional.impl.Params;
public class ReadOnlyManyCommand<K, V, R> extends AbstractTopologyAffectedCommand implements LocalCommand {
public static final int COMMAND_ID = 63;
protected Collection<?> keys;
protected Function<ReadEntryView<K, V>, R> f;
protected Params params;
protected DataConversion keyDataConversion;
protected DataConversion valueDataConversion;
public ReadOnlyManyCommand(Collection<?> keys,
Function<ReadEntryView<K, V>, R> f,
Params params,
DataConversion keyDataConversion,
DataConversion valueDataConversion) {
this.keys = keys;
this.f = f;
this.params = params;
this.keyDataConversion = keyDataConversion;
this.valueDataConversion = valueDataConversion;
this.setFlagsBitSet(params.toFlagsBitSet());
}
public ReadOnlyManyCommand() {
}
public ReadOnlyManyCommand(ReadOnlyManyCommand c) {
this.keys = c.keys;
this.f = c.f;
this.params = c.params;
this.setFlagsBitSet(c.getFlagsBitSet());
this.keyDataConversion = c.keyDataConversion;
this.valueDataConversion = c.valueDataConversion;
}
@Override
public void init(ComponentRegistry componentRegistry) {
componentRegistry.wireDependencies(keyDataConversion);
componentRegistry.wireDependencies(valueDataConversion);
}
public Collection<?> getKeys() {
return keys;
}
public void setKeys(Collection<?> keys) {
this.keys = keys;
}
public final ReadOnlyManyCommand<K, V, R> withKeys(Collection<?> keys) {
setKeys(keys);
return this;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallCollection(keys, output);
output.writeObject(f);
Params.writeObject(output, params);
DataConversion.writeTo(output, keyDataConversion);
DataConversion.writeTo(output, valueDataConversion);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
this.keys = MarshallUtil.unmarshallCollection(input, ArrayList::new);
this.f = (Function<ReadEntryView<K, V>, R>) input.readObject();
this.params = Params.readObject(input);
this.setFlagsBitSet(params.toFlagsBitSet());
keyDataConversion = DataConversion.readFrom(input);
valueDataConversion = DataConversion.readFrom(input);
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitReadOnlyManyCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.OWNER;
}
public DataConversion getKeyDataConversion() {
return keyDataConversion;
}
public DataConversion getValueDataConversion() {
return valueDataConversion;
}
public Params getParams() {
return params;
}
public Function<ReadEntryView<K, V>, R> getFunction() {
return f;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ReadOnlyManyCommand{");
sb.append(", keys=").append(keys);
sb.append(", f=").append(f.getClass().getName());
sb.append(", keyDataConversion=").append(keyDataConversion);
sb.append(", valueDataConversion=").append(valueDataConversion);
sb.append('}');
return sb.toString();
}
}
| 4,280
| 29.578571
| 107
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/Mutations.java
|
package org.infinispan.commands.functional;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import org.infinispan.commands.functional.functions.InjectableComponent;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView;
/**
* Helper class for marshalling, also hiding implementations of {@link Mutation} from the interface.
*/
final class Mutations {
private Mutations() {
}
// No need to occupy externalizer ids when we have a limited set of options
static <K, V, T, R> void writeTo(ObjectOutput output, Mutation<K, V, R> mutation) throws IOException {
BaseMutation bm = (BaseMutation) mutation;
DataConversion.writeTo(output, bm.keyDataConversion);
DataConversion.writeTo(output, bm.valueDataConversion);
byte type = mutation.type();
output.writeByte(type);
switch (type) {
case ReadWrite.TYPE:
output.writeObject(((ReadWrite<K, V, ?>) mutation).f);
break;
case ReadWriteWithValue.TYPE:
ReadWriteWithValue<K, V, T, R> rwwv = (ReadWriteWithValue<K, V, T, R>) mutation;
output.writeObject(rwwv.argument);
output.writeObject(rwwv.f);
break;
case Write.TYPE:
output.writeObject(((Write<K, V>) mutation).f);
break;
case WriteWithValue.TYPE:
WriteWithValue<K, V, T> wwv = (WriteWithValue<K, V, T>) mutation;
output.writeObject(wwv.argument);
output.writeObject(wwv.f);
break;
}
}
static <K, V, T> Mutation<K, V, ?> readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
DataConversion keyDataConversion = DataConversion.readFrom(input);
DataConversion valueDataConversion = DataConversion.readFrom(input);
switch (input.readByte()) {
case ReadWrite.TYPE:
return new ReadWrite<>(keyDataConversion, valueDataConversion, (Function<EntryView.ReadWriteEntryView<K, V>, T>) input.readObject());
case ReadWriteWithValue.TYPE:
return new ReadWriteWithValue<>(keyDataConversion, valueDataConversion, input.readObject(), (BiFunction<V, EntryView.ReadWriteEntryView<K, V>, T>) input.readObject());
case Write.TYPE:
return new Write<>(keyDataConversion, valueDataConversion, (Consumer<EntryView.WriteEntryView<K, V>>) input.readObject());
case WriteWithValue.TYPE:
return new WriteWithValue<>(keyDataConversion, valueDataConversion, input.readObject(), (BiConsumer<T, EntryView.WriteEntryView<K, V>>) input.readObject());
default:
throw new IllegalStateException("Unknown type of mutation, broken input?");
}
}
static abstract class BaseMutation<K, V, R> implements Mutation<K, V, R> {
protected final DataConversion keyDataConversion;
protected final DataConversion valueDataConversion;
BaseMutation(DataConversion keyDataConversion, DataConversion valueDataConversion) {
this.keyDataConversion = keyDataConversion;
this.valueDataConversion = valueDataConversion;
}
public DataConversion keyDataConversion() {
return keyDataConversion;
}
public DataConversion valueDataConversion() {
return valueDataConversion;
}
@Override
public void inject(ComponentRegistry registry) {
registry.wireDependencies(keyDataConversion);
registry.wireDependencies(valueDataConversion);
}
}
static class ReadWrite<K, V, R> extends BaseMutation<K, V, R> {
static final byte TYPE = 0;
private final Function<EntryView.ReadWriteEntryView<K, V>, R> f;
public ReadWrite(DataConversion keyDataConversion, DataConversion valueDataConversion, Function<EntryView.ReadWriteEntryView<K, V>, R> f) {
super(keyDataConversion, valueDataConversion);
this.f = f;
}
@Override
public void inject(ComponentRegistry registry) {
super.inject(registry);
if(f instanceof InjectableComponent) {
((InjectableComponent) f).inject(registry);
}
}
@Override
public byte type() {
return TYPE;
}
@Override
public R apply(EntryView.ReadWriteEntryView<K, V> view) {
return f.apply(view);
}
}
static class ReadWriteWithValue<K, V, T, R> extends BaseMutation<K, V, R> {
static final byte TYPE = 1;
private final Object argument;
private final BiFunction<T, EntryView.ReadWriteEntryView<K, V>, R> f;
public ReadWriteWithValue(DataConversion keyDataConversion, DataConversion valueDataConversion, Object argument, BiFunction<T, EntryView.ReadWriteEntryView<K, V>, R> f) {
super(keyDataConversion, valueDataConversion);
this.argument = argument;
this.f = f;
}
@Override
public byte type() {
return TYPE;
}
@Override
public R apply(EntryView.ReadWriteEntryView<K, V> view) {
return f.apply((T) valueDataConversion.fromStorage(argument), view);
}
}
static class Write<K, V> extends BaseMutation<K, V, Void> {
static final byte TYPE = 2;
private final Consumer<EntryView.WriteEntryView<K, V>> f;
public Write(DataConversion keyDataConversion, DataConversion valueDataConversion, Consumer<EntryView.WriteEntryView<K, V>> f) {
super(keyDataConversion, valueDataConversion);
this.f = f;
}
@Override
public byte type() {
return TYPE;
}
@Override
public Void apply(EntryView.ReadWriteEntryView<K, V> view) {
f.accept(view);
return null;
}
}
static class WriteWithValue<K, V, T> extends BaseMutation<K, V, Void> {
static final byte TYPE = 3;
private final Object argument;
private final BiConsumer<T, EntryView.WriteEntryView<K, V>> f;
public WriteWithValue(DataConversion keyDataConversion, DataConversion valueDataConversion, Object argument, BiConsumer<T, EntryView.WriteEntryView<K, V>> f) {
super(keyDataConversion, valueDataConversion);
this.argument = argument;
this.f = f;
}
@Override
public byte type() {
return TYPE;
}
@Override
public Void apply(EntryView.ReadWriteEntryView<K, V> view) {
f.accept((T) valueDataConversion.fromStorage(argument), view);
return null;
}
}
}
| 6,739
| 35.236559
| 179
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/ReadWriteKeyCommand.java
|
package org.infinispan.commands.functional;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.function.Function;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.functional.functions.InjectableComponent;
import org.infinispan.commands.write.ValueMatcher;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView.ReadWriteEntryView;
import org.infinispan.functional.impl.Params;
import org.infinispan.metadata.impl.PrivateMetadata;
// TODO: the command does not carry previous values to backup, so it can cause
// the values on primary and backup owners to diverge in case of topology change
public final class ReadWriteKeyCommand<K, V, R> extends AbstractWriteKeyCommand<K, V> {
public static final byte COMMAND_ID = 50;
private Function<ReadWriteEntryView<K, V>, R> f;
public ReadWriteKeyCommand(Object key, Function<ReadWriteEntryView<K, V>, R> f, int segment,
CommandInvocationId id, ValueMatcher valueMatcher, Params params,
DataConversion keyDataConversion,
DataConversion valueDataConversion) {
super(key, valueMatcher, segment, id, params, keyDataConversion, valueDataConversion);
this.f = f;
}
public ReadWriteKeyCommand() {
// No-op, for marshalling
}
@Override
public void init(ComponentRegistry componentRegistry) {
super.init(componentRegistry);
if (f instanceof InjectableComponent)
((InjectableComponent) f).inject(componentRegistry);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
output.writeObject(f);
MarshallUtil.marshallEnum(valueMatcher, output);
UnsignedNumeric.writeUnsignedInt(output, segment);
Params.writeObject(output, params);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
CommandInvocationId.writeTo(output, commandInvocationId);
DataConversion.writeTo(output, keyDataConversion);
DataConversion.writeTo(output, valueDataConversion);
output.writeObject(internalMetadata);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
f = (Function<ReadWriteEntryView<K, V>, R>) input.readObject();
valueMatcher = MarshallUtil.unmarshallEnum(input, ValueMatcher::valueOf);
segment = UnsignedNumeric.readUnsignedInt(input);
params = Params.readObject(input);
setFlagsBitSet(input.readLong());
commandInvocationId = CommandInvocationId.readFrom(input);
keyDataConversion = DataConversion.readFrom(input);
valueDataConversion = DataConversion.readFrom(input);
internalMetadata = (PrivateMetadata) input.readObject();
}
@Override
public boolean isConditional() {
return true;
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitReadWriteKeyCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.OWNER;
}
@Override
public Mutation<K, V, ?> toMutation(Object key) {
return new Mutations.ReadWrite<>(keyDataConversion, valueDataConversion, f);
}
public Function<ReadWriteEntryView<K, V>, R> getFunction() {
return f;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ReadWriteKeyCommand{");
sb.append("key=").append(toStr(key));
sb.append(", f=").append(f.getClass().getName());
sb.append(", flags=").append(printFlags());
sb.append(", commandInvocationId=").append(commandInvocationId);
sb.append(", topologyId=").append(getTopologyId());
sb.append(", params=").append(params);
sb.append(", valueMatcher=").append(valueMatcher);
sb.append(", successful=").append(successful);
sb.append(", keyDataConversion=").append(keyDataConversion);
sb.append(", valueDataConversion=").append(valueDataConversion);
sb.append('}');
return sb.toString();
}
}
| 4,640
| 36.128
| 95
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/ReadOnlyKeyCommand.java
|
package org.infinispan.commands.functional;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.function.Function;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.functional.functions.InjectableComponent;
import org.infinispan.commands.read.AbstractDataCommand;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView.ReadEntryView;
import org.infinispan.functional.impl.EntryViews;
import org.infinispan.functional.impl.Params;
import org.infinispan.functional.impl.StatsEnvelope;
public class ReadOnlyKeyCommand<K, V, R> extends AbstractDataCommand {
public static final int COMMAND_ID = 62;
protected Function<ReadEntryView<K, V>, R> f;
protected Params params;
protected DataConversion keyDataConversion;
protected DataConversion valueDataConversion;
public ReadOnlyKeyCommand(Object key, Function<ReadEntryView<K, V>, R> f, int segment, Params params,
DataConversion keyDataConversion,
DataConversion valueDataConversion) {
super(key, segment, EnumUtil.EMPTY_BIT_SET);
this.f = f;
this.params = params;
this.keyDataConversion = keyDataConversion;
this.valueDataConversion = valueDataConversion;
this.setFlagsBitSet(params.toFlagsBitSet());
}
public ReadOnlyKeyCommand() {
}
@Override
public void init(ComponentRegistry componentRegistry) {
componentRegistry.wireDependencies(keyDataConversion);
componentRegistry.wireDependencies(valueDataConversion);
if (f instanceof InjectableComponent)
((InjectableComponent) f).inject(componentRegistry);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
output.writeObject(f);
UnsignedNumeric.writeUnsignedInt(output, segment);
Params.writeObject(output, params);
DataConversion.writeTo(output, keyDataConversion);
DataConversion.writeTo(output, valueDataConversion);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
f = (Function<ReadEntryView<K, V>, R>) input.readObject();
segment = UnsignedNumeric.readUnsignedInt(input);
params = Params.readObject(input);
this.setFlagsBitSet(params.toFlagsBitSet());
keyDataConversion = DataConversion.readFrom(input);
valueDataConversion = DataConversion.readFrom(input);
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitReadOnlyKeyCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.OWNER;
}
/**
* Apply function on entry without any data
*/
public Object performOnLostData() {
return StatsEnvelope.create(f.apply(EntryViews.noValue((K) key, keyDataConversion)), true);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ReadOnlyKeyCommand{");
sb.append(", key=").append(key);
sb.append(", f=").append(f.getClass().getName());
sb.append(", keyDataConversion=").append(keyDataConversion);
sb.append(", valueDataConversion=").append(valueDataConversion);
sb.append('}');
return sb.toString();
}
public Function<ReadEntryView<K, V>, R> getFunction() {
return f;
}
public DataConversion getKeyDataConversion() {
return keyDataConversion;
}
public DataConversion getValueDataConversion() {
return valueDataConversion;
}
public Params getParams() {
return params;
}
}
| 3,997
| 32.041322
| 104
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/ReadWriteManyEntriesCommand.java
|
package org.infinispan.commands.functional;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.functional.functions.InjectableComponent;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView.ReadWriteEntryView;
import org.infinispan.functional.impl.Params;
// TODO: the command does not carry previous values to backup, so it can cause
// the values on primary and backup owners to diverge in case of topology change
public final class ReadWriteManyEntriesCommand<K, V, T, R> extends AbstractWriteManyCommand<K, V> {
public static final byte COMMAND_ID = 53;
private Map<?, ?> arguments;
private BiFunction<T, ReadWriteEntryView<K, V>, R> f;
boolean isForwarded = false;
public ReadWriteManyEntriesCommand(Map<?, ?> arguments,
BiFunction<T, ReadWriteEntryView<K, V>, R> f,
Params params,
CommandInvocationId commandInvocationId,
DataConversion keyDataConversion,
DataConversion valueDataConversion) {
super(commandInvocationId, params, keyDataConversion, valueDataConversion);
this.arguments = arguments;
this.f = f;
}
public ReadWriteManyEntriesCommand(ReadWriteManyEntriesCommand command) {
super(command);
this.arguments = command.arguments;
this.f = command.f;
}
public ReadWriteManyEntriesCommand() {
}
@Override
public void init(ComponentRegistry componentRegistry) {
super.init(componentRegistry);
if (f instanceof InjectableComponent)
((InjectableComponent) f).inject(componentRegistry);
}
public BiFunction<T, ReadWriteEntryView<K, V>, R> getBiFunction() {
return f;
}
public Map<?, ?> getArguments() {
return arguments;
}
public void setArguments(Map<?, ?> arguments) {
this.arguments = arguments;
this.internalMetadataMap.keySet().retainAll(arguments.keySet());
}
public final ReadWriteManyEntriesCommand<K, V, T, R> withArguments(Map<?, ?> entries) {
setArguments(entries);
return this;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
CommandInvocationId.writeTo(output, commandInvocationId);
MarshallUtil.marshallMap(arguments, output);
output.writeObject(f);
output.writeBoolean(isForwarded);
Params.writeObject(output, params);
output.writeInt(topologyId);
output.writeLong(flags);
DataConversion.writeTo(output, keyDataConversion);
DataConversion.writeTo(output, valueDataConversion);
MarshallUtil.marshallMap(internalMetadataMap, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
commandInvocationId = CommandInvocationId.readFrom(input);
// We use LinkedHashMap in order to guarantee the same order of iteration
arguments = MarshallUtil.unmarshallMap(input, LinkedHashMap::new);
f = (BiFunction<T, ReadWriteEntryView<K, V>, R>) input.readObject();
isForwarded = input.readBoolean();
params = Params.readObject(input);
topologyId = input.readInt();
flags = input.readLong();
keyDataConversion = DataConversion.readFrom(input);
valueDataConversion = DataConversion.readFrom(input);
this.internalMetadataMap = MarshallUtil.unmarshallMap(input, ConcurrentHashMap::new);
}
public boolean isForwarded() {
return isForwarded;
}
public void setForwarded(boolean forwarded) {
isForwarded = forwarded;
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitReadWriteManyEntriesCommand(ctx, this);
}
@Override
public boolean isSuccessful() {
return true;
}
@Override
public boolean isConditional() {
return false;
}
@Override
public Collection<?> getAffectedKeys() {
return arguments.keySet();
}
public LoadType loadType() {
return LoadType.OWNER;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ReadWriteManyEntriesCommand{");
sb.append("arguments=").append(arguments);
sb.append(", f=").append(f.getClass().getName());
sb.append(", isForwarded=").append(isForwarded);
sb.append(", keyDataConversion=").append(keyDataConversion);
sb.append(", valueDataConversion=").append(valueDataConversion);
sb.append('}');
return sb.toString();
}
@Override
public Collection<?> getKeysToLock() {
return arguments.keySet();
}
@Override
public Mutation<K, V, ?> toMutation(Object key) {
return new Mutations.ReadWriteWithValue(keyDataConversion, valueDataConversion, arguments.get(key), f);
}
}
| 5,541
| 31.409357
| 109
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/AbstractWriteManyCommand.java
|
package org.infinispan.commands.functional;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.write.ValueMatcher;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.impl.Params;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.util.concurrent.locks.RemoteLockCommand;
public abstract class AbstractWriteManyCommand<K, V> implements WriteCommand, FunctionalCommand<K, V>, RemoteLockCommand {
CommandInvocationId commandInvocationId;
boolean isForwarded = false;
int topologyId = -1;
Params params;
// TODO: this is used for the non-modifying read-write commands. Move required flags to Params
// and make sure that ClusteringDependentLogic checks them.
long flags;
DataConversion keyDataConversion;
DataConversion valueDataConversion;
Map<Object, PrivateMetadata> internalMetadataMap;
protected AbstractWriteManyCommand(CommandInvocationId commandInvocationId,
Params params,
DataConversion keyDataConversion,
DataConversion valueDataConversion) {
this.commandInvocationId = commandInvocationId;
this.params = params;
this.flags = params.toFlagsBitSet();
this.keyDataConversion = keyDataConversion;
this.valueDataConversion = valueDataConversion;
this.internalMetadataMap = new ConcurrentHashMap<>();
}
protected AbstractWriteManyCommand(AbstractWriteManyCommand<K, V> command) {
this.commandInvocationId = command.commandInvocationId;
this.topologyId = command.topologyId;
this.params = command.params;
this.flags = command.flags;
this.internalMetadataMap = new ConcurrentHashMap<>(command.internalMetadataMap);
this.keyDataConversion = command.keyDataConversion;
this.valueDataConversion = command.valueDataConversion;
}
protected AbstractWriteManyCommand() {
}
@Override
public void init(ComponentRegistry componentRegistry) {
componentRegistry.wireDependencies(keyDataConversion);
componentRegistry.wireDependencies(valueDataConversion);
}
@Override
public int getTopologyId() {
return topologyId;
}
@Override
public void setTopologyId(int topologyId) {
this.topologyId = topologyId;
}
public boolean isForwarded() {
return isForwarded;
}
public void setForwarded(boolean forwarded) {
isForwarded = forwarded;
}
@Override
public ValueMatcher getValueMatcher() {
return ValueMatcher.MATCH_ALWAYS;
}
@Override
public void setValueMatcher(ValueMatcher valueMatcher) {
// No-op
}
@Override
public boolean isSuccessful() {
return true;
}
@Override
public boolean isConditional() {
return false;
}
@Override
public void fail() {
throw new UnsupportedOperationException();
}
@Override
public long getFlagsBitSet() {
return flags;
}
@Override
public void setFlagsBitSet(long bitSet) {
this.flags = bitSet;
}
@Override
public Params getParams() {
return params;
}
public void setParams(Params params) {
this.params = params;
}
@Override
public Object getKeyLockOwner() {
return commandInvocationId;
}
@Override
public CommandInvocationId getCommandInvocationId() {
return commandInvocationId;
}
@Override
public boolean hasZeroLockAcquisition() {
return hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT);
}
@Override
public boolean hasSkipLocking() {
return hasAnyFlag(FlagBitSets.SKIP_LOCKING);
}
@Override
public DataConversion getKeyDataConversion() {
return keyDataConversion;
}
@Override
public DataConversion getValueDataConversion() {
return valueDataConversion;
}
@Override
public PrivateMetadata getInternalMetadata(Object key) {
return internalMetadataMap.get(key);
}
@Override
public void setInternalMetadata(Object key, PrivateMetadata internalMetadata) {
this.internalMetadataMap.put(key, internalMetadata);
}
}
| 4,426
| 26.32716
| 122
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/TxReadOnlyKeyCommand.java
|
package org.infinispan.commands.functional;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView;
import org.infinispan.functional.impl.Params;
public class TxReadOnlyKeyCommand<K, V, R> extends ReadOnlyKeyCommand<K, V, R> {
public static final byte COMMAND_ID = 64;
private List<Mutation<K, V, ?>> mutations;
public TxReadOnlyKeyCommand() {
}
public TxReadOnlyKeyCommand(Object key, Function<EntryView.ReadEntryView<K, V>, R> f, List<Mutation<K, V, ?>> mutations,
int segment, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion) {
super(key, f, segment, params, keyDataConversion, valueDataConversion);
this.mutations = mutations;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
super.writeTo(output);
MarshallUtil.marshallCollection(mutations, output, Mutations::writeTo);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
super.readFrom(input);
mutations = MarshallUtil.unmarshallCollection(input, ArrayList::new, Mutations::readFrom);
}
@Override
public void init(ComponentRegistry componentRegistry) {
super.init(componentRegistry);
// This may be called from parent's constructor when mutations are not initialized yet
if (mutations != null) {
for (Mutation<?, ?, ?> m : mutations) {
m.inject(componentRegistry);
}
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("TxReadOnlyKeyCommand{");
sb.append("key=").append(key);
sb.append(", f=").append(f);
sb.append(", mutations=").append(mutations);
sb.append(", params=").append(params);
sb.append(", keyDataConversion=").append(keyDataConversion);
sb.append(", valueDataConversion=").append(valueDataConversion);
sb.append('}');
return sb.toString();
}
public List<Mutation<K, V, ?>> getMutations() {
return mutations;
}
}
| 2,458
| 31.786667
| 130
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/functions/InjectableComponent.java
|
package org.infinispan.commands.functional.functions;
import org.infinispan.factories.ComponentRegistry;
public interface InjectableComponent {
void inject(ComponentRegistry registry);
}
| 192
| 23.125
| 53
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/functions/MergeFunction.java
|
package org.infinispan.commands.functional.functions;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.Collections;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.infinispan.cache.impl.BiFunctionMapper;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.marshall.Ids;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView;
import org.infinispan.metadata.Metadata;
import org.infinispan.util.UserRaisedFunctionalException;
public class MergeFunction<K, V> implements Function<EntryView.ReadWriteEntryView<K, V>, V>, InjectableComponent, Serializable {
private BiFunction<? super V, ? super V, ? extends V> remappingFunction;
private V value;
private Metadata metadata;
public MergeFunction(V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, Metadata metadata) {
this.remappingFunction = remappingFunction;
this.value = value;
this.metadata = metadata;
}
@Override
public V apply(EntryView.ReadWriteEntryView<K, V> entry) {
try {
V merged = value;
if (entry.find().isPresent()) {
V t = entry.get();
if (remappingFunction instanceof BiFunctionMapper) {
BiFunctionMapper mapper = (BiFunctionMapper) this.remappingFunction;
Object toStorage = mapper.getValueDataConversion().toStorage(t);
merged = remappingFunction.apply((V) toStorage, value);
} else {
merged = remappingFunction.apply(t, value);
}
}
if (merged == null) {
entry.set(merged);
} else if (remappingFunction instanceof BiFunctionMapper) {
BiFunctionMapper mapper = (BiFunctionMapper) this.remappingFunction;
Object fromStorage = mapper.getValueDataConversion().fromStorage(merged);
entry.set((V) fromStorage, metadata);
} else {
entry.set(merged, metadata);
}
return merged;
} catch (Exception ex) {
throw new UserRaisedFunctionalException(ex);
}
}
@Override
public void inject(ComponentRegistry registry) {
registry.wireDependencies(this);
registry.wireDependencies(remappingFunction);
}
public static class Externalizer implements AdvancedExternalizer<MergeFunction> {
@Override
public Set<Class<? extends MergeFunction>> getTypeClasses() {
return Collections.singleton(MergeFunction.class);
}
@Override
public Integer getId() {
return Ids.MERGE_FUNCTION_MAPPER;
}
@Override
public void writeObject(ObjectOutput output, MergeFunction object) throws IOException {
output.writeObject(object.value);
output.writeObject(object.remappingFunction);
output.writeObject(object.metadata);
}
@Override
public MergeFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new MergeFunction(input.readObject(),
(BiFunction) input.readObject(),
(Metadata) input.readObject());
}
}
}
| 3,313
| 34.634409
| 128
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/package-info.java
|
/**
* @api.public
*/
package org.infinispan.partitionhandling;
| 65
| 12.2
| 41
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/PartitionHandling.java
|
package org.infinispan.partitionhandling;
/**
* @author Ryan Emerson
* @since 9.1
*/
public enum PartitionHandling {
/**
* If the partition does not have all owners for a given segment, both reads and writes are denied for all keys in that segment.
*/
DENY_READ_WRITES,
/**
* Allows reads for a given key if it exists in this partition, but only allows writes if this partition contains all owners of a segment.
*/
ALLOW_READS,
/**
* Allow entries on each partition to diverge, with conflicts resolved during merge.
*/
ALLOW_READ_WRITES {
@Override
public AvailabilityMode startingAvailability() {
return AvailabilityMode.AVAILABLE;
}
};
public AvailabilityMode startingAvailability() {
return AvailabilityMode.DEGRADED_MODE;
}
}
| 822
| 24.71875
| 142
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/AvailabilityException.java
|
package org.infinispan.partitionhandling;
import org.infinispan.commons.CacheException;
/**
* Thrown when a partition happened and the key that an operation tries to access is not available.
*/
public class AvailabilityException extends CacheException {
public AvailabilityException() {
}
public AvailabilityException(Throwable cause) {
super(cause);
}
public AvailabilityException(String msg) {
super(msg);
}
public AvailabilityException(String msg, Throwable cause) {
super(msg, cause);
}
}
| 542
| 21.625
| 99
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/AvailabilityMode.java
|
package org.infinispan.partitionhandling;
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.marshall.MarshallUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.marshall.core.Ids;
/**
* @author Mircea Markus
* @author Dan Berindei
* @since 7.0
*/
public enum AvailabilityMode {
/**
* Regular operation mode
*/
AVAILABLE,
/**
* Data can not be safely accessed because of a network split or successive nodes leaving.
*/
DEGRADED_MODE;
public AvailabilityMode min(AvailabilityMode other) {
if (this == DEGRADED_MODE || other == DEGRADED_MODE)
return DEGRADED_MODE;
return AVAILABLE;
}
private static final AvailabilityMode[] CACHED_VALUES = values();
public static AvailabilityMode valueOf(int ordinal) {
return CACHED_VALUES[ordinal];
}
public static final class Externalizer extends AbstractExternalizer<AvailabilityMode> {
@Override
public Integer getId() {
return Ids.AVAILABILITY_MODE;
}
@Override
public Set<Class<? extends AvailabilityMode>> getTypeClasses() {
return Util.asSet(AvailabilityMode.class);
}
@Override
public void writeObject(ObjectOutput output, AvailabilityMode AvailabilityMode) throws IOException {
MarshallUtil.marshallEnum(AvailabilityMode, output);
}
@Override
public AvailabilityMode readObject(ObjectInput input) throws IOException {
return MarshallUtil.unmarshallEnum(input, AvailabilityMode::valueOf);
}
}
}
| 1,698
| 25.546875
| 106
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/impl/AvailablePartitionHandlingManager.java
|
package org.infinispan.partitionhandling.impl;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.container.versioning.IncrementableEntryVersion;
import org.infinispan.partitionhandling.AvailabilityMode;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheTopology;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* {@link PartitionHandlingManager} implementation when the cluster is always available.
*
* @author Pedro Ruivo
* @since 8.0
*/
public class AvailablePartitionHandlingManager implements PartitionHandlingManager {
private AvailablePartitionHandlingManager() {
}
public static AvailablePartitionHandlingManager getInstance() {
return SingletonHolder.INSTANCE;
}
@Override
public AvailabilityMode getAvailabilityMode() {
return AvailabilityMode.AVAILABLE;
}
@Override
public CompletionStage<Void> setAvailabilityMode(AvailabilityMode availabilityMode) {
/*no-op*/
return CompletableFutures.completedNull();
}
@Override
public void checkWrite(Object key) {/*no-op*/}
@Override
public void checkRead(Object key, long flagBitSet) {/*no-op*/}
@Override
public void checkClear() {/*no-op*/}
@Override
public void checkBulkRead() {/*no-op*/}
@Override
public CacheTopology getLastStableTopology() {
return null;
}
@Override
public boolean addPartialRollbackTransaction(GlobalTransaction globalTransaction, Collection<Address> affectedNodes,
Collection<Object> lockedKeys) {
return false;
}
@Override
public boolean addPartialCommit2PCTransaction(GlobalTransaction globalTransaction, Collection<Address> affectedNodes,
Collection<Object> lockedKeys, Map<Object, IncrementableEntryVersion> newVersions) {
return false;
}
@Override
public boolean addPartialCommit1PCTransaction(GlobalTransaction globalTransaction, Collection<Address> affectedNodes,
Collection<Object> lockedKeys, List<WriteCommand> modifications) {
return false;
}
@Override
public boolean isTransactionPartiallyCommitted(GlobalTransaction globalTransaction) {
return false;
}
@Override
public Collection<GlobalTransaction> getPartialTransactions() {
return Collections.emptyList();
}
@Override
public boolean canRollbackTransactionAfterOriginatorLeave(GlobalTransaction globalTransaction) {
return true;
}
@Override
public void onTopologyUpdate(CacheTopology cacheTopology) {/*no-op*/}
private static class SingletonHolder {
private static final AvailablePartitionHandlingManager INSTANCE = new AvailablePartitionHandlingManager();
}
}
| 3,061
| 29.929293
| 133
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/impl/PreferConsistencyStrategy.java
|
package org.infinispan.partitionhandling.impl;
import static org.infinispan.partitionhandling.impl.AvailabilityStrategy.ownersConsistentHash;
import static org.infinispan.util.logging.events.Messages.MESSAGES;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.partitionhandling.AvailabilityMode;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheJoinInfo;
import org.infinispan.topology.CacheStatusResponse;
import org.infinispan.topology.CacheTopology;
import org.infinispan.topology.PersistentUUIDManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.util.logging.events.EventLogCategory;
import org.infinispan.util.logging.events.EventLogManager;
public class PreferConsistencyStrategy implements AvailabilityStrategy {
private static final Log log = LogFactory.getLog(PreferConsistencyStrategy.class);
private final EventLogManager eventLogManager;
private final PersistentUUIDManager persistentUUIDManager;
private final LostDataCheck lostDataCheck;
public PreferConsistencyStrategy(EventLogManager eventLogManager, PersistentUUIDManager persistentUUIDManager, LostDataCheck lostDataCheck) {
this.eventLogManager = eventLogManager;
this.persistentUUIDManager = persistentUUIDManager;
this.lostDataCheck = lostDataCheck;
}
@Override
public void onJoin(AvailabilityStrategyContext context, Address joiner) {
if (context.getAvailabilityMode() != AvailabilityMode.AVAILABLE) {
log.debugf("Cache %s not available (%s), postponing rebalance for joiner %s", context.getCacheName(),
context.getAvailabilityMode(), joiner);
return;
}
context.queueRebalance(context.getExpectedMembers());
}
@Override
public void onGracefulLeave(AvailabilityStrategyContext context, Address leaver) {
CacheTopology currentTopology = context.getCurrentTopology();
List<Address> newMembers = new ArrayList<>(currentTopology.getMembers());
newMembers.remove(leaver);
if (newMembers.isEmpty()) {
log.debugf("The last node of cache %s left", context.getCacheName());
context.updateCurrentTopology(newMembers);
return;
}
if (context.getAvailabilityMode() != AvailabilityMode.AVAILABLE) {
log.debugf("Cache %s is not available, ignoring graceful leaver %s", context.getCacheName(), leaver);
return;
}
if (lostDataCheck.test(context.getStableTopology().getCurrentCH(), newMembers)) {
eventLogManager.getEventLogger().context(context.getCacheName()).warn(EventLogCategory.CLUSTER, MESSAGES.enteringDegradedModeGracefulLeaver(leaver));
context.updateAvailabilityMode(newMembers, AvailabilityMode.DEGRADED_MODE, true);
return;
}
updateMembersAndRebalance(context, newMembers, newMembers);
}
@Override
public void onClusterViewChange(AvailabilityStrategyContext context, List<Address> clusterMembers) {
CacheTopology currentTopology = context.getCurrentTopology();
List<Address> newMembers = new ArrayList<>(currentTopology.getMembers());
if (!newMembers.retainAll(clusterMembers)) {
log.debugf("Cache %s did not lose any members, ignoring view change", context.getCacheName());
return;
}
if (context.getAvailabilityMode() != AvailabilityMode.AVAILABLE) {
log.debugf("Cache %s is not available, updating the actual members only", context.getCacheName());
context.updateAvailabilityMode(newMembers, context.getAvailabilityMode(), false);
return;
}
// We could keep track of the members that left gracefully and avoid entering degraded mode in some cases.
// But the information about graceful leavers would be lost when the coordinator changes anyway, making
// the results of the strategy harder to reason about.
CacheTopology stableTopology = context.getStableTopology();
List<Address> stableMembers = stableTopology.getMembers();
// Ignore members without any segments (e.g. zero-capacity nodes)
stableMembers.removeIf(a -> stableTopology.getCurrentCH().getSegmentsForOwner(a).isEmpty());
List<Address> lostMembers = new ArrayList<>(stableMembers);
lostMembers.removeAll(newMembers);
if (lostDataCheck.test(stableTopology.getCurrentCH(), newMembers)) {
eventLogManager.getEventLogger().context(context.getCacheName()).error(EventLogCategory.CLUSTER, MESSAGES.enteringDegradedModeLostData(lostMembers));
context.updateAvailabilityMode(newMembers, AvailabilityMode.DEGRADED_MODE, true);
return;
}
if (isMinorityPartition(stableMembers, lostMembers)) {
eventLogManager.getEventLogger().context(context.getCacheName()).error(EventLogCategory.CLUSTER, MESSAGES.enteringDegradedModeMinorityPartition(newMembers, lostMembers, stableMembers));
context.updateAvailabilityMode(newMembers, AvailabilityMode.DEGRADED_MODE, true);
return;
}
// We got back to available mode (e.g. because there was a merge before, but the merge coordinator didn't
// finish installing the merged topology).
updateMembersAndRebalance(context, newMembers, newMembers);
}
protected boolean isMinorityPartition(List<Address> stableMembers, List<Address> lostMembers) {
return lostMembers.size() >= Math.ceil(stableMembers.size() / 2d);
}
@Override
public void onPartitionMerge(AvailabilityStrategyContext context, Map<Address, CacheStatusResponse> statusResponseMap) {
// Because of the majority check in onAbruptLeave, we assume that at most one partition was able to evolve
// and install new cache topologies. The other(s) would have entered degraded mode, and they would keep
// the original topology.
int maxTopologyId = 0;
int maxRebalanceId = 0;
CacheTopology maxStableTopology = null;
CacheTopology maxActiveTopology = null;
Set<CacheTopology> degradedTopologies = new HashSet<>();
CacheTopology maxDegradedTopology = null;
CacheJoinInfo joinInfo = null;
for (CacheStatusResponse response : statusResponseMap.values()) {
CacheTopology partitionStableTopology = response.getStableTopology();
if (partitionStableTopology == null) {
// The node hasn't properly joined yet.
continue;
}
if (maxStableTopology == null || maxStableTopology.getTopologyId() < partitionStableTopology.getTopologyId()) {
maxStableTopology = partitionStableTopology;
joinInfo = response.getCacheJoinInfo();
}
CacheTopology partitionTopology = response.getCacheTopology();
if (partitionTopology == null) {
// The node hasn't properly joined yet.
continue;
}
if (partitionTopology.getTopologyId() > maxTopologyId) {
maxTopologyId = partitionTopology.getTopologyId();
}
if (partitionTopology.getRebalanceId() > maxRebalanceId) {
maxRebalanceId = partitionTopology.getRebalanceId();
}
if (response.getAvailabilityMode() == AvailabilityMode.AVAILABLE) {
if (maxActiveTopology == null || maxActiveTopology.getTopologyId() < partitionTopology.getTopologyId()) {
maxActiveTopology = partitionTopology;
}
} else if (response.getAvailabilityMode() == AvailabilityMode.DEGRADED_MODE) {
degradedTopologies.add(partitionTopology);
if (maxDegradedTopology == null || maxDegradedTopology.getTopologyId() < partitionTopology.getTopologyId()) {
maxDegradedTopology = partitionTopology;
}
} else {
eventLogManager.getEventLogger().context(context.getCacheName()).error(EventLogCategory.CLUSTER, MESSAGES.unexpectedAvailabilityMode(context.getAvailabilityMode(), response.getCacheTopology()));
}
}
if (maxStableTopology != null) {
log.tracef("Max stable partition topology: %s", maxStableTopology);
}
if (maxActiveTopology != null) {
log.tracef("Max active partition topology: %s", maxActiveTopology);
}
if (maxDegradedTopology != null) {
log.tracef("Max degraded partition topology: %s, all degraded: %s", maxDegradedTopology, degradedTopologies);
}
List<Address> expectedMembers = context.getExpectedMembers();
List<Address> actualMembers = new ArrayList<>(expectedMembers);
CacheTopology mergedTopology;
AvailabilityMode mergedAvailabilityMode;
if (maxActiveTopology != null) {
log.debugf("One of the partitions is available, using that partition's topology");
mergedTopology = maxActiveTopology;
mergedAvailabilityMode = AvailabilityMode.AVAILABLE;
} else if (!degradedTopologies.isEmpty()) {
log.debugf("No active partitions, so all the partitions must be in degraded mode.");
// Once a partition enters degraded mode its CH won't change, but it could be that a partition managed to
// rebalance before losing another member and entering degraded mode.
mergedTopology = maxDegradedTopology;
if (maxStableTopology != null) {
actualMembers.retainAll(maxStableTopology.getMembers());
} else {
actualMembers.retainAll(mergedTopology.getMembers());
}
mergedAvailabilityMode = AvailabilityMode.DEGRADED_MODE;
} else {
log.debugf("No current topology, recovered only joiners for cache %s. Skipping availability update.", context.getCacheName());
return;
}
// Increment the topology id so that it's bigger than any topology that might have been sent by the old
// coordinator.
// +1 is enough because nodes wait for the new JGroups view before answering the
// status request, and then they can't process topology updates from the old view.
// Also cancel any pending rebalance by removing the pending CH, because we don't recover the rebalance
// confirmation status (yet).
AvailabilityMode newAvailabilityMode = computeAvailabilityAfterMerge(context, maxStableTopology, actualMembers);
if (mergedTopology != null) {
boolean resolveConflicts = context.resolveConflictsOnMerge() && actualMembers.size() > 1 && newAvailabilityMode == AvailabilityMode.AVAILABLE;
if (resolveConflicts) {
// Record all distinct read owners and hashes
Set<ConsistentHash> distinctHashes = new HashSet<>();
for (CacheStatusResponse response : statusResponseMap.values()) {
CacheTopology cacheTopology = response.getCacheTopology();
if (cacheTopology != null) {
ConsistentHash readCH = ownersConsistentHash(cacheTopology, joinInfo.getConsistentHashFactory());
if (readCH != null && !readCH.getMembers().isEmpty()) {
distinctHashes.add(readCH);
}
}
}
ConsistentHash preferredHash = ownersConsistentHash(mergedTopology, joinInfo.getConsistentHashFactory());
ConsistentHash conflictHash = context.calculateConflictHash(preferredHash, distinctHashes, expectedMembers);
mergedTopology = new CacheTopology(++maxTopologyId, maxRebalanceId + 1, conflictHash, null,
CacheTopology.Phase.CONFLICT_RESOLUTION, actualMembers, persistentUUIDManager.mapAddresses(actualMembers));
// Update the currentTopology and try to resolve conflicts
context.updateTopologiesAfterMerge(mergedTopology, maxStableTopology, mergedAvailabilityMode);
context.queueConflictResolution(mergedTopology, new HashSet<>(preferredHash.getMembers()));
return;
}
// There's no pendingCH, therefore the topology is in stable phase
actualMembers.retainAll(mergedTopology.getMembers());
mergedTopology = new CacheTopology(maxTopologyId + 1, mergedTopology.getRebalanceId(),
mergedTopology.getCurrentCH(), null,
CacheTopology.Phase.NO_REBALANCE, actualMembers,
persistentUUIDManager.mapAddresses(actualMembers));
}
context.updateTopologiesAfterMerge(mergedTopology, maxStableTopology, mergedAvailabilityMode);
// It shouldn't be possible to recover from unavailable mode without user action
if (newAvailabilityMode == AvailabilityMode.DEGRADED_MODE) {
log.debugf("After merge, cache %s is staying in degraded mode", context.getCacheName());
context.updateAvailabilityMode(actualMembers, newAvailabilityMode, true);
} else { // AVAILABLE
log.debugf("After merge, cache %s has recovered and is entering available mode", context.getCacheName());
updateMembersAndRebalance(context, actualMembers, context.getExpectedMembers());
}
}
private AvailabilityMode computeAvailabilityAfterMerge(AvailabilityStrategyContext context,
CacheTopology maxStableTopology, List<Address> newMembers) {
if (maxStableTopology != null) {
List<Address> stableMembers = maxStableTopology.getMembers();
List<Address> lostMembers = new ArrayList<>(stableMembers);
lostMembers.removeAll(context.getExpectedMembers());
if (lostDataCheck.test(maxStableTopology.getCurrentCH(), newMembers)) {
eventLogManager.getEventLogger().context(context.getCacheName()).error(EventLogCategory.CLUSTER, MESSAGES.keepingDegradedModeAfterMergeDataLost(newMembers, lostMembers, stableMembers));
return AvailabilityMode.DEGRADED_MODE;
}
if (lostMembers.size() >= Math.ceil(stableMembers.size() / 2d)) {
eventLogManager.getEventLogger().context(context.getCacheName()).warn(EventLogCategory.CLUSTER, MESSAGES.keepingDegradedModeAfterMergeMinorityPartition(newMembers, lostMembers,
stableMembers));
return AvailabilityMode.DEGRADED_MODE;
}
}
return AvailabilityMode.AVAILABLE;
}
@Override
public void onRebalanceEnd(AvailabilityStrategyContext context) {
// We may have a situation where 2 nodes leave in sequence, and the rebalance for the first leave only finishes
// after the second node left (and we entered degraded mode).
// For now, we ignore the rebalance and we keep the cache in degraded mode.
// Don't need to queue another rebalance, if we need another rebalance it's already in the queue
}
@Override
public void onManualAvailabilityChange(AvailabilityStrategyContext context, AvailabilityMode newAvailabilityMode) {
List<Address> actualMembers = context.getCurrentTopology().getActualMembers();
List<Address> newMembers = context.getExpectedMembers();
if (newAvailabilityMode == AvailabilityMode.AVAILABLE) {
// Update the topology to remove leavers - the current topology may not have been updated for a while
context.updateCurrentTopology(actualMembers);
context.updateAvailabilityMode(actualMembers, newAvailabilityMode, false);
// Then queue a rebalance to include the joiners as well
context.queueRebalance(newMembers);
} else {
context.updateAvailabilityMode(actualMembers, newAvailabilityMode, true);
}
}
private void updateMembersAndRebalance(AvailabilityStrategyContext context, List<Address> actualMembers,
List<Address> newMembers) {
// Change the availability mode if needed
context.updateAvailabilityMode(actualMembers, AvailabilityMode.AVAILABLE, false);
// Update the topology to remove leavers - in case there is a rebalance in progress, or rebalancing is disabled
context.updateCurrentTopology(newMembers);
// Then queue a rebalance to include the joiners as well
context.queueRebalance(context.getExpectedMembers());
}
}
| 16,331
| 52.723684
| 206
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/impl/AvailabilityStrategyContext.java
|
package org.infinispan.partitionhandling.impl;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.infinispan.configuration.cache.PartitionHandlingConfiguration;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.distribution.ch.ConsistentHashFactory;
import org.infinispan.partitionhandling.AvailabilityMode;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheJoinInfo;
import org.infinispan.topology.CacheTopology;
/**
* Contains information about the current state of the cache.
*
* Also allows {@link AvailabilityStrategy} to proceed with a rebalance, a membership update, or an availability mode change.
*
* Implementations should not use blocking calls.
*
* @author Mircea Markus
* @author Dan Berindei
*/
public interface AvailabilityStrategyContext {
String getCacheName();
CacheJoinInfo getJoinInfo();
Map<Address, Float> getCapacityFactors();
/**
* @return The current cache topology.
*/
CacheTopology getCurrentTopology();
/**
* Whenever a new cache topology without a {@code pendingCH} and with at least {@code numOwners} owners for each
* segment is installed, and the cache is {@link AvailabilityMode#AVAILABLE}, the current cache topology is marked
* as the stable topology.
*
* The same happens when a rebalance is scheduled to start, but it doesn't do anything because the current
* topology is already balanced.
*
* @return The last stable cache topology. May be {@code null}.
*/
CacheTopology getStableTopology();
/**
* @return The current availability mode.
*/
AvailabilityMode getAvailabilityMode();
/**
* The members of the cache.
*
* Includes nodes which have tried to join the cache but are not yet part of the current {@code CacheTopology}.
* Does not include nodes which have left the cluster (either gracefully or abruptly) but are still in the
* current topology.
*/
List<Address> getExpectedMembers();
/**
* Queue (or start) a rebalance.
*
* Use the configured {@link ConsistentHashFactory} to create a new balanced consistent hash
* with the given members.
*
* If there is no rebalance in progress, start a rebalance right away.
* If there is a rebalance in progress, queue another rebalance.
* If there is a rebalance in the queue as well, it will be replaced with the new one.
* If {@code newConsistentHash == null}, remove any queued rebalance.
*/
void queueRebalance(List<Address> newMembers);
/**
* Use the configured {@link ConsistentHashFactory} to create a new CH
* with the given {@code members}, but do not start a rebalance.
* Members missing from the current topology are ignored.
*/
void updateCurrentTopology(List<Address> newMembers);
/**
* Enter a new availability mode.
*/
void updateAvailabilityMode(List<Address> actualMembers, AvailabilityMode mode, boolean cancelRebalance);
/**
* Updates both the stable and the current topologies.
*
* Does not install the current topology on the cache members.
*/
void updateTopologiesAfterMerge(CacheTopology currentTopology, CacheTopology stableTopology,
AvailabilityMode availabilityMode);
/**
* @return true if {@link PartitionHandlingConfiguration#mergePolicy()} != null
*/
boolean resolveConflictsOnMerge();
/**
* @param preferredHash the base consistent hash
* @param distinctHashes a set of all hashes to be utilised as part of the conflict resolution hash
* @param actualMembers a set of all valid addresses
* @return the hash to be utilised as a pending CH during Phase.CONFLICT_RESOLUTION
*/
ConsistentHash calculateConflictHash(ConsistentHash preferredHash, Set<ConsistentHash> distinctHashes, List<Address> actualMembers);
/**
* Initiates conflict resolution using the conflictTopology, which should have already been broadcast via
* {@link this#updateTopologiesAfterMerge(CacheTopology, CacheTopology, AvailabilityMode)}
*
* @param conflictTopology the topology to use during conflict resolution
* @param preferredNodes the addresses that belong to the preferred partition as determined by the {@link AvailabilityStrategy}
*/
void queueConflictResolution(CacheTopology conflictTopology, Set<Address> preferredNodes);
/**
* If CR is in progress, then this method cancels the current CR and starts a new CR phase with an updated topology
* based upon newMembers and the previously queued CR topology
*
* @param newMembers the latest members of the current view
* @return true if conflict resolution was restarted due to the newMembers
*/
boolean restartConflictResolution(List<Address> newMembers);
}
| 4,836
| 36.496124
| 135
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/impl/PreferAvailabilityStrategy.java
|
package org.infinispan.partitionhandling.impl;
import static org.infinispan.partitionhandling.impl.AvailabilityStrategy.ownersConsistentHash;
import static org.infinispan.util.logging.events.Messages.MESSAGES;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.infinispan.commons.util.InfinispanCollections;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.partitionhandling.AvailabilityMode;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheStatusResponse;
import org.infinispan.topology.CacheTopology;
import org.infinispan.topology.PersistentUUIDManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.util.logging.events.EventLogCategory;
import org.infinispan.util.logging.events.EventLogManager;
public class PreferAvailabilityStrategy implements AvailabilityStrategy {
private static final Log log = LogFactory.getLog(PreferAvailabilityStrategy.class);
private final EventLogManager eventLogManager;
private final PersistentUUIDManager persistentUUIDManager;
private final LostDataCheck lostDataCheck;
public PreferAvailabilityStrategy(EventLogManager eventLogManager, PersistentUUIDManager persistentUUIDManager, LostDataCheck lostDataCheck) {
this.eventLogManager = eventLogManager;
this.persistentUUIDManager = persistentUUIDManager;
this.lostDataCheck = lostDataCheck;
}
@Override
public void onJoin(AvailabilityStrategyContext context, Address joiner) {
context.queueRebalance(context.getExpectedMembers());
}
@Override
public void onGracefulLeave(AvailabilityStrategyContext context, Address leaver) {
CacheTopology currentTopology = context.getCurrentTopology();
List<Address> newMembers = new ArrayList<>(currentTopology.getMembers());
newMembers.remove(leaver);
if (newMembers.isEmpty()) {
log.debugf("The last node of cache %s left", context.getCacheName());
context.updateCurrentTopology(newMembers);
return;
}
if (context.getStableTopology() != null && lostDataCheck.test(context.getStableTopology().getCurrentCH(), newMembers)) {
eventLogManager.getEventLogger().context(context.getCacheName()).warn(EventLogCategory.CLUSTER, MESSAGES.lostDataBecauseOfGracefulLeaver(leaver));
}
// We have to do this in case rebalancing is disabled, or there is another rebalance in progress
context.updateCurrentTopology(newMembers);
// If CR is already in progress we have to restart it and a rebalance will occur once CR completes
if (!context.restartConflictResolution(newMembers)) {
context.queueRebalance(newMembers);
}
}
@Override
public void onClusterViewChange(AvailabilityStrategyContext context, List<Address> clusterMembers) {
CacheTopology currentTopology = context.getCurrentTopology();
List<Address> newMembers = new ArrayList<>(currentTopology.getMembers());
if (!newMembers.retainAll(clusterMembers)) {
if (log.isTraceEnabled()) log.tracef("Cache %s did not lose any members, skipping rebalance", context.getCacheName());
return;
}
checkForLostData(context.getCacheName(), context.getStableTopology(), newMembers);
if (!context.restartConflictResolution(newMembers)) {
// We have to do the update in case rebalancing is disabled, or there is another rebalance in progress
context.updateCurrentTopology(newMembers);
context.queueRebalance(newMembers);
}
}
private void checkForLostData(String cacheName, CacheTopology stableTopology, List<Address> newMembers) {
List<Address> stableMembers = stableTopology.getMembers();
List<Address> lostMembers = new ArrayList<>(stableMembers);
lostMembers.removeAll(newMembers);
if (lostDataCheck.test(stableTopology.getCurrentCH(), newMembers)) {
eventLogManager.getEventLogger().context(cacheName).fatal(EventLogCategory.CLUSTER, MESSAGES.lostDataBecauseOfAbruptLeavers(lostMembers));
} else if (lostMembers.size() >= Math.ceil(stableMembers.size() / 2d)) {
eventLogManager.getEventLogger().context(cacheName).warn(EventLogCategory.CLUSTER, MESSAGES.minorityPartition(newMembers, lostMembers, stableMembers));
}
}
@Override
public void onPartitionMerge(AvailabilityStrategyContext context,
Map<Address, CacheStatusResponse> statusResponseMap) {
String cacheName = context.getCacheName();
List<Address> newMembers = context.getExpectedMembers();
List<Partition> partitions = computePartitions(statusResponseMap, cacheName);
if (partitions.size() == 0) {
log.debugf("No current topology, recovered only joiners for cache %s", cacheName);
context.updateCurrentTopology(newMembers);
// Then start a rebalance with the expected members
context.queueRebalance(newMembers);
return;
}
if (partitions.size() == 1) {
// Single partition, only the coordinator changed
// Usually this means the old coordinator left the cluster, but the other nodes are all alive
Partition p = partitions.get(0);
log.debugf("Recovered a single partition for cache %s: %s", cacheName, p.topology);
// Cancel any pending rebalance and only use the read CH,
// because we don't recover the rebalance confirmation status (yet).
List<Address> survivingMembers = new ArrayList<>(newMembers);
if (survivingMembers.retainAll(p.readCH.getMembers())) {
checkForLostData(cacheName, p.stableTopology, survivingMembers);
}
CacheTopology mergedTopology = new CacheTopology(p.topology.getTopologyId() + 1,
p.topology.getRebalanceId() + 1,
p.readCH, null, null,
CacheTopology.Phase.NO_REBALANCE,
survivingMembers,
persistentUUIDManager.mapAddresses(survivingMembers));
context.updateTopologiesAfterMerge(mergedTopology, p.stableTopology, null);
if (survivingMembers.isEmpty()) {
// No surviving members, use the expected members instead
survivingMembers = newMembers;
}
// Remove leavers first
if (!survivingMembers.equals(p.topology.getMembers())) {
context.updateCurrentTopology(survivingMembers);
}
// Then start a rebalance with the expected members
context.queueRebalance(newMembers);
return;
}
// Merge with multiple topologies that are not clear descendants of each other
Partition preferredPartition = selectPreferredPartition(partitions);
// Increment the topology id so that it's bigger than any topology that might have been sent by the old
// coordinator. +1 is enough because there nodes wait for the new JGroups view before answering the status
// request, and after they have the new view they can't process topology updates with the old view id.
int mergeTopologyId = 0;
int mergeRebalanceId = 0;
for (Partition p : partitions) {
CacheTopology topology = p.topology;
if (mergeTopologyId <= topology.getTopologyId()) {
mergeTopologyId = topology.getTopologyId() + 1;
}
if (mergeRebalanceId <= topology.getRebalanceId()) {
mergeRebalanceId = topology.getRebalanceId() + 1;
}
}
// Record all distinct read owners and hashes for conflict resolution
Set<Address> possibleOwners = new HashSet<>();
Set<ConsistentHash> distinctHashes = new HashSet<>();
for (Partition p : partitions) {
possibleOwners.addAll(p.readCH.getMembers());
distinctHashes.add(p.readCH);
}
// Remove nodes that have not yet fully rejoined the cluster
possibleOwners.retainAll(newMembers);
boolean resolveConflicts = context.resolveConflictsOnMerge() && possibleOwners.size() > 1;
if (log.isTraceEnabled()) {
log.tracef("Cache %s, resolveConflicts=%s, newMembers=%s, possibleOwners=%s, preferredTopology=%s, " +
"mergeTopologyId=%s",
cacheName, resolveConflicts, newMembers, possibleOwners, preferredPartition.topology,
mergeTopologyId);
}
List<Address> actualMembers = new ArrayList<>(newMembers);
CacheTopology mergedTopology;
if (resolveConflicts) {
actualMembers.retainAll(possibleOwners);
// Start conflict resolution by using the preferred topology's read CH as a base
// And the union of all distinct consistent hashes as the source
ConsistentHash conflictHash = context.calculateConflictHash(preferredPartition.readCH, distinctHashes, actualMembers);
mergedTopology = new CacheTopology(mergeTopologyId, mergeRebalanceId, conflictHash,
null, CacheTopology.Phase.CONFLICT_RESOLUTION,
actualMembers, persistentUUIDManager.mapAddresses(actualMembers));
} else {
actualMembers.retainAll(preferredPartition.readCH.getMembers());
for (Partition p : partitions) {
if (p != preferredPartition) {
log.ignoringCacheTopology(p.senders, p.topology);
}
}
// Cancel any pending rebalance and only use the read CH,
// because we don't recover the rebalance confirmation status (yet).
mergedTopology = new CacheTopology(mergeTopologyId, mergeRebalanceId, preferredPartition.readCH, null,
CacheTopology.Phase.NO_REBALANCE, actualMembers,
persistentUUIDManager.mapAddresses(actualMembers));
}
context.updateTopologiesAfterMerge(mergedTopology, preferredPartition.stableTopology, null);
// First update the CHs to remove any nodes that left from the current topology
if (!actualMembers.containsAll(preferredPartition.readCH.getMembers())) {
checkForLostData(cacheName, preferredPartition.stableTopology, actualMembers);
}
assert !actualMembers.isEmpty();
// Initialize the cache with the joiners
context.updateCurrentTopology(actualMembers);
if (resolveConflicts) {
context.queueConflictResolution(mergedTopology, new HashSet<>(preferredPartition.readCH.getMembers()));
} else {
// Then start a rebalance with the merged members
context.queueRebalance(newMembers);
}
}
private Partition selectPreferredPartition(List<Partition> partitions) {
Partition preferredPartition = null;
for (Partition p : partitions) {
// TODO Investigate comparing the number of segments owned by the senders +
// the number of the number of segments for partition(senders includes owner) agrees
if (!p.isConflictResolutionOnly() && p.isPreferable(preferredPartition)) {
preferredPartition = p;
}
}
assert preferredPartition != null;
return preferredPartition;
}
/**
* Ignore the AvailabilityStrategyContext and only compute the preferred topology for testing.
*
* @return The preferred topology, or {@code null} if there is no preferred topology.
*/
public CacheTopology computePreferredTopology(Map<Address, CacheStatusResponse> statusResponseMap) {
List<Partition> partitions = computePartitions(statusResponseMap, "");
return partitions.size() != 0 ? selectPreferredPartition(partitions).topology : null;
}
private List<Partition> computePartitions(Map<Address, CacheStatusResponse> statusResponseMap,
String cacheName) {
// The topology is not updated atomically across the cluster, so even members of the same partition
// can report different topologies
List<Partition> partitions = new ArrayList<>();
for (Map.Entry<Address, CacheStatusResponse> e : statusResponseMap.entrySet()) {
Address sender = e.getKey();
CacheStatusResponse response = e.getValue();
CacheTopology topology = response.getCacheTopology();
if (topology == null || !topology.getMembers().contains(sender)) {
// The node hasn't properly joined yet, so it can't be part of a partition
continue;
}
ConsistentHash readCH = ownersConsistentHash(topology, response.getCacheJoinInfo().getConsistentHashFactory());
Partition p = new Partition(sender, topology, response.getStableTopology(), readCH, statusResponseMap.keySet());
if (p.actualMembers.isEmpty()) {
// None of the members of this partition have send status responses, ignore it
continue;
}
partitions.add(p);
}
// Sort partitions in reverse topology id order to simplify the algorithm
partitions.sort((p1, p2) -> p2.topology.getTopologyId() - p1.topology.getTopologyId());
for (int i = 0; i < partitions.size(); i++) {
Partition referencePartition = partitions.get(i);
if (log.isTraceEnabled())
log.tracef("Cache %s keeping partition from %s: %s",
cacheName, referencePartition.senders, referencePartition.topology);
for (int j = i + 1; j < partitions.size(); j++) {
Partition p = partitions.get(j);
// If read owners don't overlap then we clearly have 2 independent partitions
if (!InfinispanCollections.containsAny(p.readCH.getMembers(), referencePartition.readCH.getMembers())) {
continue;
}
// Normally the difference between the topology ids seen by different members is 0 or 1.
// But only rebalance start and phase changes are kept in step,
// topology updates are fire-and-forget, so the difference can be higher
// even when communication between nodes is not interrupted.
boolean fold = false;
int referenceTopologyId = referencePartition.topology.getTopologyId();
int topologyId = p.topology.getTopologyId();
if (topologyId == referenceTopologyId) {
if (p.topology.equals(referencePartition.topology)) {
// The topology is exactly the same, ignore it
if (log.isTraceEnabled())
log.tracef("Cache %s ignoring topology from %s, same as topology from %s: %s",
cacheName, p.senders, referencePartition.senders, p.topology);
fold = true;
} else {
if (log.isTraceEnabled())
log.tracef("Cache %s partition of %s overlaps with partition of %s, with the same topology id",
cacheName, p.senders, referencePartition.senders);
}
} else {
// topologyId < referenceTopologyId
// Small topology differences are expected even between properly communicating nodes,
// but we should consider it a different partition if p's sender might have some entries
// that the other members lost.
// Having a majority doesn't matter, because the lost data check ensures p's sender
// couldn't make any updates without talking to the reference partition's members
if (!lostDataCheck.test(p.readCH, referencePartition.actualMembers)) {
if (log.isTraceEnabled())
log.tracef("Cache %s ignoring compatible old topology from %s: %s",
cacheName, p.senders, p.topology);
fold = true;
} else {
if (log.isTraceEnabled())
log.tracef("Cache %s partition of %s overlaps with partition of %s but possibly holds extra entries",
cacheName, p.senders, referencePartition.senders);
p.setConflictResolutionOnly();
}
}
if (fold) {
referencePartition.senders.addAll(p.senders);
partitions.remove(j);
--j;
}
}
}
return partitions;
}
@Override
public void onRebalanceEnd(AvailabilityStrategyContext context) {
// Do nothing, if we need another rebalance it's already in the queue
}
@Override
public void onManualAvailabilityChange(AvailabilityStrategyContext context, AvailabilityMode newAvailabilityMode) {
// The cache should always be AVAILABLE
}
private static class Partition {
final CacheTopology topology;
final CacheTopology stableTopology;
final ConsistentHash readCH;
final List<Address> actualMembers;
final List<Address> actualReadOwners;
final List<Address> senders = new ArrayList<>();
private boolean conflictResolutionOnly;
Partition(Address sender, CacheTopology topology, CacheTopology stableTopology, ConsistentHash readCH,
Collection<Address> newMembers) {
this.topology = topology;
this.stableTopology = stableTopology;
// The topologies used here do not have a union CH, so CacheTopology.getReadConsistentHash() doesn't work
this.readCH = readCH;
this.actualMembers = new ArrayList<>(topology.getActualMembers());
actualMembers.retainAll(newMembers);
this.actualReadOwners = new ArrayList<>(readCH.getMembers());
actualReadOwners.retainAll(newMembers);
this.senders.add(sender);
}
private boolean isPreferable(Partition other) {
if (other == null) {
return true;
} else if (other.senders.size() < senders.size()) {
return true;
} else if (other.senders.size() == senders.size() &&
other.actualReadOwners.size() < actualReadOwners.size()) {
return true;
} else if (other.senders.size() == senders.size() &&
other.actualReadOwners.size() == actualReadOwners.size() &&
other.actualMembers.size() < actualMembers.size()) {
return true;
} else if (other.topology.getTopologyId() < topology.getTopologyId()) {
// Partitions are already sorted in reverse topology order,
// but we make an explicit check for clarity
return true;
}
return false;
}
boolean isConflictResolutionOnly() {
return conflictResolutionOnly;
}
void setConflictResolutionOnly() {
conflictResolutionOnly = true;
}
}
}
| 19,198
| 46.9975
| 160
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/impl/LostDataCheck.java
|
package org.infinispan.partitionhandling.impl;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.remoting.transport.Address;
import java.util.List;
import java.util.function.BiPredicate;
public interface LostDataCheck extends BiPredicate<ConsistentHash, List<Address>> {
}
| 302
| 26.545455
| 83
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/impl/PartitionHandlingManagerImpl.java
|
package org.infinispan.partitionhandling.impl;
import static org.infinispan.commons.util.EnumUtil.EMPTY_BIT_SET;
import static org.infinispan.util.logging.Log.CONTAINER;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand;
import org.infinispan.commands.tx.TransactionBoundaryCommand;
import org.infinispan.commands.tx.VersionedCommitCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.commons.util.InfinispanCollections;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.container.versioning.IncrementableEntryVersion;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.distribution.DistributionInfo;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.annotations.ComponentName;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.partitionhandling.AvailabilityMode;
import org.infinispan.partitionhandling.PartitionHandling;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.UnsureResponse;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.impl.MapResponseCollector;
import org.infinispan.topology.CacheTopology;
import org.infinispan.topology.LocalTopologyManager;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.locks.LockManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
@Scope(Scopes.NAMED_CACHE)
public class PartitionHandlingManagerImpl implements PartitionHandlingManager {
private static final Log log = LogFactory.getLog(PartitionHandlingManagerImpl.class);
private final Map<GlobalTransaction, TransactionInfo> partialTransactions;
private final PartitionHandling partitionHandling;
private volatile AvailabilityMode availabilityMode;
@ComponentName(KnownComponentNames.CACHE_NAME)
@Inject String cacheName;
@Inject protected DistributionManager distributionManager;
@Inject LocalTopologyManager localTopologyManager;
@Inject CacheNotifier<Object, Object> notifier;
@Inject CommandsFactory commandsFactory;
@Inject RpcManager rpcManager;
@Inject LockManager lockManager;
public PartitionHandlingManagerImpl(Configuration configuration) {
partialTransactions = new ConcurrentHashMap<>();
partitionHandling = configuration.clustering().partitionHandling().whenSplit();
availabilityMode = partitionHandling.startingAvailability();
}
@Override
public AvailabilityMode getAvailabilityMode() {
return availabilityMode;
}
private void updateAvailabilityMode(AvailabilityMode mode) {
log.debugf("Updating availability for cache %s: %s -> %s", cacheName, availabilityMode, mode);
this.availabilityMode = mode;
}
@Override
public CompletionStage<Void> setAvailabilityMode(AvailabilityMode availabilityMode) {
if (availabilityMode != this.availabilityMode) {
return notifier.notifyPartitionStatusChanged(availabilityMode, true)
.thenCompose(ignore -> {
updateAvailabilityMode(availabilityMode);
return notifier.notifyPartitionStatusChanged(availabilityMode, false);
});
} else {
return CompletableFutures.completedNull();
}
}
@Override
public void checkWrite(Object key) {
doCheck(key, true, EMPTY_BIT_SET);
}
@Override
public void checkRead(Object key, long flagBitSet) {
doCheck(key, false, flagBitSet);
}
@Override
public void checkClear() {
if (isBulkOperationForbidden(true)) {
throw CONTAINER.clearDisallowedWhilePartitioned();
}
}
@Override
public void checkBulkRead() {
if (isBulkOperationForbidden(false)) {
throw CONTAINER.partitionDegraded();
}
}
@Override
public CacheTopology getLastStableTopology() {
return localTopologyManager.getStableCacheTopology(cacheName);
}
@Override
public boolean addPartialRollbackTransaction(GlobalTransaction globalTransaction, Collection<Address> affectedNodes, Collection<Object> lockedKeys) {
if (log.isTraceEnabled()) {
log.tracef("Added partially rollback transaction %s", globalTransaction);
}
partialTransactions.put(globalTransaction, new RollbackTransactionInfo(globalTransaction, affectedNodes, lockedKeys));
return true;
}
@Override
public boolean addPartialCommit2PCTransaction(GlobalTransaction globalTransaction, Collection<Address> affectedNodes,
Collection<Object> lockedKeys, Map<Object, IncrementableEntryVersion> newVersions) {
if (log.isTraceEnabled()) {
log.tracef("Added partially committed (2PC) transaction %s", globalTransaction);
}
partialTransactions.put(globalTransaction, new Commit2PCTransactionInfo(globalTransaction, affectedNodes,
lockedKeys, newVersions));
return true;
}
@Override
public boolean addPartialCommit1PCTransaction(GlobalTransaction globalTransaction, Collection<Address> affectedNodes,
Collection<Object> lockedKeys, List<WriteCommand> modifications) {
if (log.isTraceEnabled()) {
log.tracef("Added partially committed (1PC) transaction %s", globalTransaction);
}
partialTransactions.put(globalTransaction, new Commit1PCTransactionInfo(globalTransaction, affectedNodes,
lockedKeys, modifications));
return true;
}
@Override
public boolean isTransactionPartiallyCommitted(GlobalTransaction globalTransaction) {
TransactionInfo transactionInfo = partialTransactions.get(globalTransaction);
// If we are going to commit, we can't release the resources yet
boolean partiallyCommitted = transactionInfo != null && !transactionInfo.isRolledBack();
if (log.isTraceEnabled()) {
log.tracef("Can release resources for transaction %s? %s. Transaction info=%s", globalTransaction,
!partiallyCommitted, transactionInfo);
}
return partiallyCommitted;
}
@Override
public Collection<GlobalTransaction> getPartialTransactions() {
return Collections.unmodifiableCollection(partialTransactions.keySet());
}
@Override
public boolean canRollbackTransactionAfterOriginatorLeave(GlobalTransaction globalTransaction) {
boolean canRollback = availabilityMode == AvailabilityMode.AVAILABLE &&
!getLastStableTopology().getActualMembers().contains(globalTransaction.getAddress());
if (log.isTraceEnabled()) {
log.tracef("Can rollback transaction? %s", canRollback);
}
return canRollback;
}
@Override
public void onTopologyUpdate(CacheTopology cacheTopology) {
if (isTopologyStable(cacheTopology)) {
if (log.isDebugEnabled()) {
log.debugf("On stable topology update. Pending txs: %d", partialTransactions.size());
}
for (TransactionInfo transactionInfo : partialTransactions.values()) {
if (log.isTraceEnabled()) {
log.tracef("Completing transaction %s", transactionInfo.getGlobalTransaction());
}
completeTransaction(transactionInfo, cacheTopology);
}
if (log.isDebugEnabled()) {
log.debug("Finished sending commit commands for partial completed transactions");
}
}
}
private void completeTransaction(final TransactionInfo transactionInfo, CacheTopology cacheTopology) {
List<Address> commitNodes = transactionInfo.getCommitNodes(cacheTopology);
TransactionBoundaryCommand command = transactionInfo.buildCommand(commandsFactory);
command.setTopologyId(cacheTopology.getTopologyId());
CompletionStage<Map<Address, Response>> remoteInvocation = commitNodes != null ?
rpcManager.invokeCommand(commitNodes, command, MapResponseCollector.ignoreLeavers(commitNodes.size()),
rpcManager.getSyncRpcOptions()) :
rpcManager.invokeCommandOnAll(command, MapResponseCollector.ignoreLeavers(),
rpcManager.getSyncRpcOptions());
remoteInvocation.whenComplete((responseMap, throwable) -> {
final boolean trace = log.isTraceEnabled();
final GlobalTransaction globalTransaction = transactionInfo.getGlobalTransaction();
if (throwable != null) {
log.failedPartitionHandlingTxCompletion(globalTransaction, throwable);
return;
}
if (trace) {
log.tracef("Future done for transaction %s. Response are %s", globalTransaction, responseMap);
}
for (Response response : responseMap.values()) {
if (response == UnsureResponse.INSTANCE || response == CacheNotFoundResponse.INSTANCE) {
if (trace) {
log.tracef("Topology changed while completing partial transaction %s", globalTransaction);
}
return;
}
}
if (trace) {
log.tracef("Performing cleanup for transaction %s", globalTransaction);
}
lockManager.unlockAll(transactionInfo.getLockedKeys(), globalTransaction);
partialTransactions.remove(globalTransaction);
TxCompletionNotificationCommand completionCommand =
commandsFactory.buildTxCompletionNotificationCommand(null, globalTransaction);
// A little bit overkill, but the state transfer can happen during a merge and some nodes can receive the
// transaction that aren't in the original affected nodes.
// no side effects.
rpcManager.sendToAll(completionCommand, DeliverOrder.NONE);
});
}
private boolean isTopologyStable(CacheTopology cacheTopology) {
CacheTopology stableTopology = localTopologyManager.getStableCacheTopology(cacheName);
if (log.isTraceEnabled()) {
log.tracef("Check if topology %s is stable. Last stable topology is %s", cacheTopology, stableTopology);
}
return stableTopology != null && stableTopology.equals(cacheTopology);
}
protected void doCheck(Object key, boolean isWrite, long flagBitSet) {
if (log.isTraceEnabled()) log.tracef("Checking availability for key=%s, status=%s", key, availabilityMode);
if (availabilityMode == AvailabilityMode.AVAILABLE)
return;
LocalizedCacheTopology cacheTopology = distributionManager.getCacheTopology();
if (isKeyOperationAllowed(isWrite, flagBitSet, cacheTopology, key)) {
if (log.isTraceEnabled()) log.tracef("Key %s is available.", key);
return;
}
if (log.isTraceEnabled()) log.tracef("Partition is in %s mode, PartitionHandling is set to to %s, access is not allowed for key %s", availabilityMode, partitionHandling, key);
if (EnumUtil.containsAny(flagBitSet, FlagBitSets.FORCE_WRITE_LOCK)) {
throw CONTAINER.degradedModeLockUnavailable(key);
} else {
throw CONTAINER.degradedModeKeyUnavailable(key);
}
}
/**
* Check if a read/write operation is allowed with the actual members
*
* @param isWrite {@code false} for reads, {@code true} for writes
* @param flagBitSet reads with the {@link org.infinispan.context.Flag#FORCE_WRITE_LOCK} are treated as writes
* @param cacheTopology actual members, or {@code null} for bulk operations
* @param key key owners, or {@code null} for bulk operations
* @return {@code true} if the operation is allowed, {@code false} otherwise.
*/
protected boolean isKeyOperationAllowed(boolean isWrite, long flagBitSet,
LocalizedCacheTopology cacheTopology, Object key) {
if (availabilityMode == AvailabilityMode.AVAILABLE)
return true;
assert partitionHandling != PartitionHandling.ALLOW_READ_WRITES :
"ALLOW_READ_WRITES caches should always be AVAILABLE";
List<Address> actualMembers = cacheTopology.getActualMembers();
switch (partitionHandling) {
case ALLOW_READS:
List<Address> owners = getOwners(cacheTopology, key, isWrite);
if (isWrite || EnumUtil.containsAny(flagBitSet, FlagBitSets.FORCE_WRITE_LOCK)) {
// Writes require all the owners to be in the local partition
return actualMembers.containsAll(owners);
} else {
// Reads only require one owner in the local partition
return InfinispanCollections.containsAny(actualMembers, owners);
}
case DENY_READ_WRITES:
if (cacheTopology.getTopologyId() < 0 && cacheTopology.getRebalanceId() < 0) {
return false;
}
// Both reads and writes require all the owners to be in the local partition
return actualMembers.containsAll(getOwners(cacheTopology, key, isWrite));
default:
throw new IllegalStateException("Unsupported partition handling type: " + partitionHandling);
}
}
private boolean isBulkOperationForbidden(boolean isWrite) {
if (availabilityMode == AvailabilityMode.AVAILABLE)
return false;
assert partitionHandling != PartitionHandling.ALLOW_READ_WRITES :
"ALLOW_READ_WRITES caches should always be AVAILABLE";
// We reject bulk writes because some owners are always missing in degraded mode
if (isWrite)
return true;
switch (partitionHandling) {
case ALLOW_READS:
// Bulk reads require only one owner of each segment in the local partition
LocalizedCacheTopology cacheTopology = distributionManager.getCacheTopology();
for (int i = 0; i < cacheTopology.getReadConsistentHash().getNumSegments(); i++) {
List<Address> owners = cacheTopology.getSegmentDistribution(i).readOwners();
if (!InfinispanCollections.containsAny(owners, cacheTopology.getActualMembers()))
return true;
}
return false;
case DENY_READ_WRITES:
return true;
default:
throw new IllegalStateException("Unsupported partition handling type: " + partitionHandling);
}
}
protected PartitionHandling getPartitionHandling() {
return partitionHandling;
}
private List<Address> getOwners(LocalizedCacheTopology cacheTopology, Object key, boolean isWrite) {
DistributionInfo distribution = cacheTopology.getDistribution(key);
return isWrite ? distribution.writeOwners() : distribution.readOwners();
}
private interface TransactionInfo {
boolean isRolledBack();
List<Address> getCommitNodes(CacheTopology stableTopology);
TransactionBoundaryCommand buildCommand(CommandsFactory commandsFactory);
GlobalTransaction getGlobalTransaction();
Collection<Object> getLockedKeys();
}
private static class RollbackTransactionInfo extends BaseTransactionInfo {
protected RollbackTransactionInfo(GlobalTransaction globalTransaction, Collection<Address> affectedNodes, Collection<Object> lockedKeys) {
super(globalTransaction, affectedNodes, lockedKeys);
}
@Override
public boolean isRolledBack() {
return true;
}
@Override
public TransactionBoundaryCommand buildCommand(CommandsFactory commandsFactory) {
return commandsFactory.buildRollbackCommand(getGlobalTransaction());
}
}
private static class Commit2PCTransactionInfo extends BaseTransactionInfo {
private final Map<Object, IncrementableEntryVersion> newVersions;
public Commit2PCTransactionInfo(GlobalTransaction globalTransaction, Collection<Address> affectedNodes,
Collection<Object> lockedKeys, Map<Object, IncrementableEntryVersion> newVersions) {
super(globalTransaction, affectedNodes, lockedKeys);
this.newVersions = newVersions;
}
@Override
public boolean isRolledBack() {
return false;
}
@Override
public TransactionBoundaryCommand buildCommand(CommandsFactory commandsFactory) {
if (newVersions != null) {
VersionedCommitCommand commitCommand = commandsFactory.buildVersionedCommitCommand(getGlobalTransaction());
commitCommand.setUpdatedVersions(newVersions);
return commitCommand;
} else {
return commandsFactory.buildCommitCommand(getGlobalTransaction());
}
}
}
private static class Commit1PCTransactionInfo extends BaseTransactionInfo {
private final List<WriteCommand> modifications;
public Commit1PCTransactionInfo(GlobalTransaction globalTransaction, Collection<Address> affectedNodes, Collection<Object> lockedKeys, List<WriteCommand> modifications) {
super(globalTransaction, affectedNodes, lockedKeys);
this.modifications = modifications;
}
@Override
public boolean isRolledBack() {
return false;
}
@Override
public TransactionBoundaryCommand buildCommand(CommandsFactory commandsFactory) {
return commandsFactory.buildPrepareCommand(getGlobalTransaction(), modifications, true);
}
}
private static abstract class BaseTransactionInfo implements TransactionInfo {
private final GlobalTransaction globalTransaction;
private final Collection<Address> affectedNodes;
private final Collection<Object> lockedKeys;
protected BaseTransactionInfo(GlobalTransaction globalTransaction, Collection<Address> affectedNodes, Collection<Object> lockedKeys) {
this.globalTransaction = globalTransaction;
this.lockedKeys = lockedKeys;
this.affectedNodes = affectedNodes;
}
@Override
public final List<Address> getCommitNodes(CacheTopology stableTopology) {
if (affectedNodes == null) {
return null;
} else {
List<Address> commitNodes = new ArrayList<>(affectedNodes);
commitNodes.retainAll(stableTopology.getActualMembers());
return commitNodes;
}
}
@Override
public final GlobalTransaction getGlobalTransaction() {
return globalTransaction;
}
@Override
public Collection<Object> getLockedKeys() {
return lockedKeys;
}
@Override
public String toString() {
return "TransactionInfo{" +
"globalTransaction=" + globalTransaction + ", " +
"rollback=" + isRolledBack() + ", " +
"affectedNodes=" + affectedNodes +
'}';
}
}
}
| 19,840
| 41.577253
| 181
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/impl/AvailabilityStrategy.java
|
package org.infinispan.partitionhandling.impl;
import java.util.List;
import java.util.Map;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.distribution.ch.ConsistentHashFactory;
import org.infinispan.partitionhandling.AvailabilityMode;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheStatusResponse;
import org.infinispan.topology.CacheTopology;
/**
* Implementations decide what to do when the cache membership changes, either because new nodes joined, nodes left,
* or there was a merge. The decision is then applied by calling one of the {@link AvailabilityStrategyContext} methods.
*
* The strategy can also queue actions until the current rebalance ends, and execute them on
* {@link #onRebalanceEnd(AvailabilityStrategyContext)}.
*
* Method invocations are synchronized, so it's not possible to have concurrent invocations.
*
* @author Mircea Markus
* @author Dan Berindei
* @since 7.0
*/
public interface AvailabilityStrategy {
/**
* Compute the read consistent hash for a topology with a {@code null} union consistent hash.
*/
static ConsistentHash ownersConsistentHash(CacheTopology topology, ConsistentHashFactory chFactory) {
switch (topology.getPhase()) {
case NO_REBALANCE:
return topology.getCurrentCH();
case CONFLICT_RESOLUTION:
case READ_OLD_WRITE_ALL:
return topology.getCurrentCH();
case READ_ALL_WRITE_ALL:
return chFactory.union(topology.getCurrentCH(), topology.getPendingCH());
case READ_NEW_WRITE_ALL:
return topology.getPendingCH();
default:
throw new IllegalStateException();
}
}
/**
* Called when a node joins.
*/
void onJoin(AvailabilityStrategyContext context, Address joiner);
/**
* Called when a node leaves gracefully.
*/
void onGracefulLeave(AvailabilityStrategyContext context, Address leaver);
/**
* Called when the cluster view changed (e.g. because one or more nodes left abruptly).
*/
void onClusterViewChange(AvailabilityStrategyContext context, List<Address> clusterMembers);
/**
* Called when two or more partitions merge, to compute the stable and current cache topologies for the merged
* cluster.
*/
void onPartitionMerge(AvailabilityStrategyContext context, Map<Address, CacheStatusResponse> statusResponseMap);
/**
* Called when a rebalance ends. Can be used to re-assess the state of the cache and apply pending changes.
*/
void onRebalanceEnd(AvailabilityStrategyContext context);
/**
* Called when the administrator manually changes the availability status.
*/
void onManualAvailabilityChange(AvailabilityStrategyContext context, AvailabilityMode newAvailabilityMode);
}
| 2,839
| 35.883117
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/impl/PartitionHandlingInterceptor.java
|
package org.infinispan.partitionhandling.impl;
import static org.infinispan.util.logging.Log.CONTAINER;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.infinispan.commands.DataCommand;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.read.EntrySetCommand;
import org.infinispan.commands.read.GetAllCommand;
import org.infinispan.commands.read.GetCacheEntryCommand;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.commands.read.KeySetCommand;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.ComputeCommand;
import org.infinispan.commands.write.ComputeIfAbsentCommand;
import org.infinispan.commands.write.DataWriteCommand;
import org.infinispan.commands.write.IracPutKeyValueCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.interceptors.InvocationFinallyAction;
import org.infinispan.interceptors.InvocationSuccessAction;
import org.infinispan.partitionhandling.AvailabilityMode;
import org.infinispan.remoting.RpcException;
public class PartitionHandlingInterceptor extends DDAsyncInterceptor {
@Inject PartitionHandlingManager partitionHandlingManager;
private final InvocationFinallyAction<DataCommand> handleDataReadReturn = this::handleDataReadReturn;
private final InvocationFinallyAction<GetAllCommand> handleGetAllCommandReturn = this::handleGetAllCommandReturn;
private final InvocationSuccessAction<VisitableCommand> postTxCommandCheck = this::postTxCommandCheck;
private boolean performPartitionCheck(FlagAffectedCommand command) {
return !command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL | FlagBitSets.SKIP_OWNERSHIP_CHECK | FlagBitSets.PUT_FOR_STATE_TRANSFER | FlagBitSets.STATE_TRANSFER_PROGRESS);
}
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command)
throws Throwable {
return handleSingleWrite(ctx, command);
}
@Override
public Object visitIracPutKeyValueCommand(InvocationContext ctx, IracPutKeyValueCommand command) {
return handleSingleWrite(ctx, command);
}
@Override
public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
return handleSingleWrite(ctx, command);
}
@Override
public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
return handleSingleWrite(ctx, command);
}
@Override
public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable {
return handleSingleWrite(ctx, command);
}
@Override
public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) throws Throwable {
return handleSingleWrite(ctx, command);
}
@Override
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable {
return handleSingleWrite(ctx, command);
}
protected Object handleSingleWrite(InvocationContext ctx, DataWriteCommand command) {
if (performPartitionCheck(command)) {
partitionHandlingManager.checkWrite(command.getKey());
}
return invokeNext(ctx, command);
}
@Override
public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
if (performPartitionCheck(command)) {
for (Object k : command.getAffectedKeys())
partitionHandlingManager.checkWrite(k);
}
return invokeNext(ctx, command);
}
@Override
public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
if (performPartitionCheck(command)) {
partitionHandlingManager.checkClear();
}
return handleDefault(ctx, command);
}
@Override
public Object visitKeySetCommand(InvocationContext ctx, KeySetCommand command) throws Throwable {
if (performPartitionCheck(command)) {
partitionHandlingManager.checkBulkRead();
}
return handleDefault(ctx, command);
}
@Override
public Object visitEntrySetCommand(InvocationContext ctx, EntrySetCommand command) throws Throwable {
if (performPartitionCheck(command)) {
partitionHandlingManager.checkBulkRead();
}
return handleDefault(ctx, command);
}
@Override
public final Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command)
throws Throwable {
return handleDataReadCommand(ctx, command);
}
@Override
public final Object visitGetCacheEntryCommand(InvocationContext ctx, GetCacheEntryCommand command) {
return handleDataReadCommand(ctx, command);
}
private Object handleDataReadCommand(InvocationContext ctx, DataCommand command) {
return invokeNextAndFinally(ctx, command, handleDataReadReturn);
}
private void handleDataReadReturn(InvocationContext rCtx, DataCommand dataCommand, Object rv, Throwable t) {
if (!performPartitionCheck(dataCommand))
return;
if (t != null) {
if (t instanceof RpcException) {
// We must have received an AvailabilityException from one of the owners.
// There is no way to verify the cause here, but there isn't any other way to get an invalid
// get response.
throw CONTAINER.degradedModeKeyUnavailable(dataCommand.getKey());
}
}
// We do the availability check after the read, because the cache may have entered degraded mode
// while we were reading from a remote node.
partitionHandlingManager.checkRead(dataCommand.getKey(), dataCommand.getFlagsBitSet());
}
@Override
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable {
if (!ctx.isOriginLocal()) {
return invokeNext(ctx, command);
}
// Don't send a 2PC prepare at all if the cache is in degraded mode
if (partitionHandlingManager.getAvailabilityMode() != AvailabilityMode.AVAILABLE &&
!command.isOnePhaseCommit() && ctx.hasModifications()) {
for (Object key : ctx.getAffectedKeys()) {
partitionHandlingManager.checkWrite(key);
}
}
return invokeNextThenAccept(ctx, command, postTxCommandCheck);
}
@Override
public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable {
if (!ctx.isOriginLocal()) {
return invokeNext(ctx, command);
}
return invokeNextThenAccept(ctx, command, postTxCommandCheck);
}
protected void postTxCommandCheck(InvocationContext rCtx, VisitableCommand rCommand, Object rv) {
TxInvocationContext ctx = (TxInvocationContext) rCtx;
if (partitionHandlingManager.getAvailabilityMode() != AvailabilityMode.AVAILABLE &&
!partitionHandlingManager.isTransactionPartiallyCommitted(ctx.getGlobalTransaction()) &&
ctx.hasModifications()) {
for (Object key : ctx.getAffectedKeys()) {
partitionHandlingManager.checkWrite(key);
}
}
}
@Override
public Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable {
return invokeNextAndFinally(ctx, command, handleGetAllCommandReturn);
}
private void handleGetAllCommandReturn(InvocationContext rCtx, GetAllCommand getAllCommand, Object rv, Throwable t) {
if (t != null) {
if (t instanceof RpcException && performPartitionCheck(getAllCommand)) {
// We must have received an AvailabilityException from one of the owners.
// There is no way to verify the cause here, but there isn't any other way to get an invalid
// get response.
throw CONTAINER.degradedModeKeysUnavailable(getAllCommand.getKeys());
}
}
if (!performPartitionCheck(getAllCommand))
return;
// We do the availability check after the read, because the cache may have entered degraded mode
// while we were reading from a remote node.
for (Object key : getAllCommand.getKeys()) {
partitionHandlingManager.checkRead(key, getAllCommand.getFlagsBitSet());
}
// TODO Dan: If we retry on CacheNotFoundResponse, we never have to deal with a smaller map here
// Scattered cache throws AllOwnersLostException instead of returning map with only a subset of keys
// because the owners might be unknown even if there's no data loss and then the command has to be retried.
if (t == null && rv instanceof Map) {
// rv could be UnsureResponse
Map<Object, Object> result = ((Map<Object, Object>) rv);
if (result.size() != getAllCommand.getKeys().size()) {
Set<Object> missingKeys = new HashSet<>(getAllCommand.getKeys());
missingKeys.removeAll(result.keySet());
throw CONTAINER.degradedModeKeysUnavailable(missingKeys);
}
}
}
@Override
public Object visitLockControlCommand(TxInvocationContext ctx, LockControlCommand command) throws Throwable {
if (!ctx.isOriginLocal()) return invokeNext(ctx, command);
for (Object key : command.getKeys()) {
partitionHandlingManager.checkWrite(key);
}
return invokeNext(ctx, command);
}
}
| 10,071
| 40.110204
| 173
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/partitionhandling/impl/PartitionHandlingManager.java
|
package org.infinispan.partitionhandling.impl;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.container.versioning.IncrementableEntryVersion;
import org.infinispan.partitionhandling.AvailabilityMode;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheTopology;
import org.infinispan.transaction.xa.GlobalTransaction;
/**
* @author Dan Berindei
* @since 7.0
*/
public interface PartitionHandlingManager {
AvailabilityMode getAvailabilityMode();
CompletionStage<Void> setAvailabilityMode(AvailabilityMode availabilityMode);
void checkWrite(Object key);
void checkRead(Object key, long flagBitSet);
void checkClear();
void checkBulkRead();
@Deprecated //test use only. it can be removed if we update the tests
CacheTopology getLastStableTopology();
/**
* Adds a partially aborted transaction.
* <p/>
* The transaction should be registered when it is not sure if the abort happens successfully in all the affected
* nodes.
*
* @param globalTransaction the global transaction.
* @param affectedNodes the nodes involved in the transaction and they must abort the transaction.
* @param lockedKeys the keys locally locked.
* @return {@code true} if the {@link PartitionHandlingManager} will handle it, {@code false} otherwise.
*/
boolean addPartialRollbackTransaction(GlobalTransaction globalTransaction, Collection<Address> affectedNodes,
Collection<Object> lockedKeys);
/**
* Adds a partially committed transaction.
* <p/>
* The transaction is committed in the second phase and it is register if it is not sure that the transaction was
* committed successfully in all the affected nodes.
*
* @param globalTransaction the global transaction.
* @param affectedNodes the nodes involved in the transaction and they must commit it.
* @param lockedKeys the keys locally locked.
* @param newVersions the updated versions. Only used when versioning is enabled.
* @return {@code true} if the {@link PartitionHandlingManager} will handle it, {@code false} otherwise.
*/
boolean addPartialCommit2PCTransaction(GlobalTransaction globalTransaction, Collection<Address> affectedNodes,
Collection<Object> lockedKeys, Map<Object, IncrementableEntryVersion> newVersions);
/**
* Adds a partially committed transaction.
* <p/>
* The transaction is committed in one phase and it is register if it is not sure that the transaction was committed
* successfully in all the affected nodes.
*
* @param globalTransaction the global transaction.
* @param affectedNodes the nodes involved in the transaction and they must commit it.
* @param lockedKeys the keys locally locked.
* @param modifications the transaction's modification log.
* @return {@code true} if the {@link PartitionHandlingManager} will handle it, {@code false} otherwise.
*/
boolean addPartialCommit1PCTransaction(GlobalTransaction globalTransaction, Collection<Address> affectedNodes,
Collection<Object> lockedKeys, List<WriteCommand> modifications);
/**
* It checks if the transaction resources (for example locks) can be released.
* <p/>
* The transaction resource can't be released when the transaction is partially committed.
*
* @param globalTransaction the transaction.
* @return {@code true} if the resources can be released, {@code false} otherwise.
*/
boolean isTransactionPartiallyCommitted(GlobalTransaction globalTransaction);
/**
* @return a collection of partial committed or aborted transactions.
*/
Collection<GlobalTransaction> getPartialTransactions();
/**
* It checks if the transaction can be aborted when the originator leaves the cluster.
* <p/>
* The only case in which it is not possible to abort is when partition handling is enabled and the originator didn't
* leave gracefully. The transaction will complete when the partition heals.
*
* @param globalTransaction the global transaction.
* @return {@code true} if the transaction can be aborted, {@code false} otherwise.
*/
boolean canRollbackTransactionAfterOriginatorLeave(GlobalTransaction globalTransaction);
/**
* Notifies the {@link PartitionHandlingManager} that the cache topology was update.
* <p/>
* It detects when the partition is merged and tries to complete all the partially completed transactions.
*
* @param cacheTopology the new cache topology.
*/
void onTopologyUpdate(CacheTopology cacheTopology);
}
| 4,886
| 41.495652
| 125
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/BackupSenderImpl.java
|
package org.infinispan.xsite;
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.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import jakarta.transaction.Transaction;
import org.infinispan.Cache;
import org.infinispan.commands.AbstractVisitor;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.functional.ReadWriteKeyValueCommand;
import org.infinispan.commands.functional.ReadWriteManyCommand;
import org.infinispan.commands.functional.ReadWriteManyEntriesCommand;
import org.infinispan.commands.functional.WriteOnlyKeyCommand;
import org.infinispan.commands.functional.WriteOnlyKeyValueCommand;
import org.infinispan.commands.functional.WriteOnlyManyCommand;
import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.ComputeCommand;
import org.infinispan.commands.write.ComputeIfAbsentCommand;
import org.infinispan.commands.write.IracPutKeyValueCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.BackupConfiguration;
import org.infinispan.configuration.cache.BackupFailurePolicy;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.CustomFailurePolicy;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.interceptors.InvocationStage;
import org.infinispan.interceptors.SyncInvocationStage;
import org.infinispan.interceptors.impl.SimpleAsyncInvocationStage;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.remoting.transport.XSiteResponse;
import org.infinispan.transaction.impl.AbstractCacheTransaction;
import org.infinispan.transaction.impl.LocalTransaction;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.util.logging.events.EventLogManager;
import org.infinispan.xsite.status.SiteState;
import org.infinispan.xsite.status.TakeOfflineManager;
import net.jcip.annotations.GuardedBy;
/**
* @author Mircea Markus
* @since 5.2
*/
@Scope(Scopes.NAMED_CACHE)
public class BackupSenderImpl implements BackupSender {
private static final Log log = LogFactory.getLog(BackupSenderImpl.class);
@Inject ComponentRef<Cache<Object,Object>> cache;
@Inject RpcManager rpcManager;
@Inject Configuration config;
@Inject TransactionTable txTable;
@Inject TimeService timeService;
@Inject CommandsFactory commandsFactory;
@Inject EventLogManager eventLogManager;
@Inject GlobalConfiguration globalConfig;
@Inject KeyPartitioner keyPartitioner;
@Inject TakeOfflineManager takeOfflineManager;
private final Map<String, CustomFailurePolicy<Object,Object>> siteFailurePolicy = new HashMap<>();
private String localSiteName;
private String cacheName;
private enum BackupFilter {KEEP_1PC_ONLY, KEEP_2PC_ONLY, KEEP_ALL}
public BackupSenderImpl() {
}
@Start
public void start() {
Transport transport = rpcManager.getTransport();
transport.checkCrossSiteAvailable();
this.cacheName = cache.wired().getName();
this.localSiteName = transport.localSiteName();
config.sites().syncBackupsStream()
.filter(bc -> bc.backupFailurePolicy() == BackupFailurePolicy.CUSTOM)
.forEach(bc -> {
String backupPolicy = bc.failurePolicyClass();
if (backupPolicy == null) {
throw new IllegalStateException("Backup policy class missing for custom failure policy!");
}
CustomFailurePolicy<Object, Object> instance = Util.getInstance(backupPolicy, globalConfig.classLoader());
instance.init(cache.wired());
siteFailurePolicy.put(bc.site(), instance);
});
}
@Override
public InvocationStage backupPrepare(PrepareCommand command, AbstractCacheTransaction cacheTransaction,
Transaction transaction) {
List<WriteCommand> modifications = filterModifications(command.getModifications(),
cacheTransaction.getLookedUpEntries());
if (modifications.isEmpty()) {
return SyncInvocationStage.completedNullStage();
}
PrepareCommand prepare = commandsFactory.buildPrepareCommand(command.getGlobalTransaction(), modifications,
command.isOnePhaseCommit());
//if we run a 2PC then filter out 1PC prepare backup calls as they will happen during the local commit phase.
BackupFilter filter = !prepare.isOnePhaseCommit() ? BackupFilter.KEEP_2PC_ONLY : BackupFilter.KEEP_ALL;
List<XSiteBackup> backups = calculateBackupInfo(filter);
if (backups.isEmpty()) {
return SyncInvocationStage.completedNullStage();
}
return backupCommand(prepare, command, backups, transaction);
}
@Override
public InvocationStage backupWrite(WriteCommand command, WriteCommand originalCommand) {
List<XSiteBackup> xSiteBackups = calculateBackupInfo(BackupFilter.KEEP_ALL);
return backupCommand(command, originalCommand, xSiteBackups, null);
}
@Override
public InvocationStage backupClear(ClearCommand command) {
List<XSiteBackup> xSiteBackups = calculateBackupInfo(BackupFilter.KEEP_ALL);
return backupCommand(command, command, xSiteBackups, null);
}
@Override
public InvocationStage backupCommit(CommitCommand command, Transaction transaction) {
ResponseAggregator aggregator = new ResponseAggregator(command, transaction);
//we have a 2PC: we didn't backup the 1PC stuff during prepare, we need to do it now.
sendTo1PCBackups(command, aggregator);
sendTo2PCBackups(command, aggregator);
return aggregator.freeze();
}
@Override
public InvocationStage backupRollback(RollbackCommand command, Transaction transaction) {
List<XSiteBackup> xSiteBackups = calculateBackupInfo(BackupFilter.KEEP_2PC_ONLY);
return backupCommand(command, command, xSiteBackups, transaction);
}
private InvocationStage backupCommand(VisitableCommand command, VisitableCommand originalCommand,
List<XSiteBackup> xSiteBackups, Transaction transaction) {
XSiteReplicateCommand<Object> xsiteCommand = commandsFactory.buildSingleXSiteRpcCommand(command);
ResponseAggregator aggregator = new ResponseAggregator(originalCommand, transaction);
sendTo(xsiteCommand, xSiteBackups, aggregator);
return aggregator.freeze();
}
private void sendTo(XSiteReplicateCommand<Object> command, Collection<XSiteBackup> xSiteBackups,
ResponseAggregator aggregator) {
for (XSiteBackup backup : xSiteBackups) {
XSiteResponse<Object> cs = rpcManager.invokeXSite(backup, command);
takeOfflineManager.registerRequest(cs);
aggregator.addResponse(backup, cs);
}
}
private void sendTo1PCBackups(CommitCommand command, ResponseAggregator aggregator) {
final LocalTransaction localTx = txTable.getLocalTransaction(command.getGlobalTransaction());
List<WriteCommand> modifications = filterModifications(localTx.getModifications(), localTx.getLookedUpEntries());
if (modifications.isEmpty()) {
return; //nothing to send
}
List<XSiteBackup> xSiteBackups = calculateBackupInfo(BackupFilter.KEEP_1PC_ONLY);
if (xSiteBackups.isEmpty()) {
return; //avoid creating garbage
}
PrepareCommand prepare = commandsFactory.buildPrepareCommand(command.getGlobalTransaction(),
modifications, true);
XSiteReplicateCommand<Object> xsiteCommand = commandsFactory.buildSingleXSiteRpcCommand(prepare);
sendTo(xsiteCommand, xSiteBackups, aggregator);
}
private void sendTo2PCBackups(CommitCommand command, ResponseAggregator aggregator) {
List<XSiteBackup> xSiteBackups = calculateBackupInfo(BackupFilter.KEEP_2PC_ONLY);
if (xSiteBackups.isEmpty()) {
return; //avoid creating garbage
}
XSiteReplicateCommand<Object> xsiteCommand = commandsFactory.buildSingleXSiteRpcCommand(command);
sendTo(xsiteCommand, xSiteBackups, aggregator);
}
private List<XSiteBackup> calculateBackupInfo(BackupFilter backupFilter) {
List<XSiteBackup> backupInfo = new ArrayList<>(2);
Iterator<BackupConfiguration> iterator = config.sites().syncBackupsStream().iterator();
while (iterator.hasNext()){
BackupConfiguration bc = iterator.next();
if (bc.site().equals(localSiteName)) {
log.cacheBackupsDataToSameSite(localSiteName);
continue;
}
boolean is2PC = bc.isTwoPhaseCommit();
if (backupFilter == BackupFilter.KEEP_1PC_ONLY && is2PC) {
continue;
}
if (backupFilter == BackupFilter.KEEP_2PC_ONLY && !is2PC) {
continue;
}
if (takeOfflineManager.getSiteState(bc.site()) == SiteState.OFFLINE) {
log.tracef("The site '%s' is offline, not backing up information to it", bc.site());
continue;
}
XSiteBackup bi = new XSiteBackup(bc.site(), true, bc.replicationTimeout());
backupInfo.add(bi);
}
return backupInfo;
}
private List<WriteCommand> filterModifications(WriteCommand[] modifications, Map<Object, CacheEntry> lookedUpEntries) {
if (modifications == null || modifications.length == 0) {
return Collections.emptyList();
}
return filterModifications(Arrays.asList(modifications), lookedUpEntries);
}
private List<WriteCommand> filterModifications(List<WriteCommand> modifications, Map<Object, CacheEntry> lookedUpEntries) {
if (modifications == null || modifications.isEmpty()) {
return Collections.emptyList();
}
List<WriteCommand> filtered = new ArrayList<>(modifications.size());
Set<Object> filteredKeys = new HashSet<>(modifications.size());
// Note: the result of replication of transaction with flagged operations may be actually different.
// We use last-flag-bit-set wins strategy.
// All we can do is to assume that if the user plays with unsafe flags he won't modify the entry once
// in a replicable and another time in a non-replicable way
for (ListIterator<WriteCommand> it = modifications.listIterator(modifications.size()); it.hasPrevious(); ) {
WriteCommand writeCommand = it.previous();
if (!writeCommand.isSuccessful() || writeCommand.hasAnyFlag(FlagBitSets.SKIP_XSITE_BACKUP)) {
continue;
}
// Note: ClearCommand should be replicated out of transaction
for (Object key : writeCommand.getAffectedKeys()) {
if (filteredKeys.contains(key)) {
continue;
}
CacheEntry entry = lookedUpEntries.get(key);
if (entry == null) {
// Functional commands should always fetch the remote value to originator if xsite is enabled.
throw new IllegalStateException();
}
WriteCommand replicatedCommand;
if (entry.isRemoved()) {
replicatedCommand = commandsFactory.buildRemoveCommand(key, null, keyPartitioner.getSegment(key),
writeCommand.getFlagsBitSet());
} else if (entry.isChanged()) {
replicatedCommand = commandsFactory.buildPutKeyValueCommand(key, entry.getValue(),
keyPartitioner.getSegment(key), entry.getMetadata(), writeCommand.getFlagsBitSet());
} else {
continue;
}
filtered.add(replicatedCommand);
filteredKeys.add(key);
}
}
return filtered;
}
private class ResponseAggregator extends CompletableFuture<Void> implements XSiteResponse.XSiteResponseCompleted {
private final VisitableCommand command;
private final Transaction transaction;
private final AtomicInteger counter;
@GuardedBy("this")
private BackupFailureException exception;
private volatile boolean frozen;
private ResponseAggregator(VisitableCommand command, Transaction transaction) {
this.command = command;
this.transaction = transaction;
this.counter = new AtomicInteger();
}
@Override
public void onCompleted(XSiteBackup backup, long sendTimeNanos, long durationNanos, Throwable throwable) {
if (log.isTraceEnabled()) {
log.tracef("Backup response from site %s completed for command %s. throwable=%s", command, backup,
throwable);
}
if (backup.isSync()) {
if (throwable != null) {
handleException(backup.getSiteName(), throwable);
}
if (counter.decrementAndGet() == 0 && frozen) {
onRequestCompleted();
}
}
}
void addResponse(XSiteBackup backup, XSiteResponse response) {
assert !frozen;
response.whenCompleted(this);
if (backup.isSync()) {
counter.incrementAndGet();
}
}
InvocationStage freeze() {
frozen = true;
if (counter.get() == 0) {
onRequestCompleted();
}
return new SimpleAsyncInvocationStage(this);
}
void handleException(String siteName, Throwable throwable) {
switch (config.sites().getFailurePolicy(siteName)) {
case FAIL:
addException(siteName, throwable);
break;
case CUSTOM:
CustomFailurePolicy<Object,Object> failurePolicy = siteFailurePolicy.get(siteName);
try {
command.acceptVisitor(null, new CustomBackupPolicyInvoker(siteName, failurePolicy, transaction));
} catch (Throwable t) {
addException(siteName, t);
}
break;
case WARN:
log.warnXsiteBackupFailed(cacheName, siteName, throwable);
//fallthrough
default:
break;
}
}
synchronized void addException(String siteName, Throwable throwable) {
if (exception == null) {
exception = new BackupFailureException(cacheName);
}
exception.addFailure(siteName, throwable);
}
private synchronized void onRequestCompleted() {
if (exception != null) {
completeExceptionally(exception);
} else {
complete(null);
}
}
}
private static final class CustomBackupPolicyInvoker extends AbstractVisitor {
private final String site;
private final CustomFailurePolicy<Object, Object> failurePolicy;
private final Transaction tx;
public CustomBackupPolicyInvoker(String site, CustomFailurePolicy<Object, Object> failurePolicy, Transaction tx) {
this.site = site;
this.failurePolicy = failurePolicy;
this.tx = tx;
}
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) {
failurePolicy.handlePutFailure(site, command.getKey(), command.getValue(), command.isPutIfAbsent());
return null;
}
@Override
public Object visitIracPutKeyValueCommand(InvocationContext ctx, IracPutKeyValueCommand command) {
//no-op
return null;
}
@Override
public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) {
failurePolicy.handleRemoveFailure(site, command.getKey(), command.getValue());
return null;
}
@Override
public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) {
failurePolicy.handleReplaceFailure(site, command.getKey(), command.getOldValue(), command.getNewValue());
return null;
}
@Override
public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) {
failurePolicy.handleComputeFailure(site, command.getKey(), command.getRemappingBiFunction(), command.isComputeIfPresent());
return null;
}
@Override
public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) {
failurePolicy.handleComputeIfAbsentFailure(site, command.getKey(), command.getMappingFunction());
return null;
}
@Override
public Object visitWriteOnlyKeyCommand(InvocationContext ctx, WriteOnlyKeyCommand command) {
failurePolicy.handleWriteOnlyKeyFailure(site, command.getKey());
return null;
}
@Override
public Object visitReadWriteKeyValueCommand(InvocationContext ctx, ReadWriteKeyValueCommand command) {
failurePolicy.handleReadWriteKeyValueFailure(site, command.getKey());
return null;
}
@Override
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) {
failurePolicy.handleReadWriteKeyFailure(site, command.getKey());
return null;
}
@Override
public Object visitWriteOnlyManyEntriesCommand(InvocationContext ctx, WriteOnlyManyEntriesCommand command) {
failurePolicy.handleWriteOnlyManyEntriesFailure(site, command.getArguments());
return null;
}
@Override
public Object visitWriteOnlyKeyValueCommand(InvocationContext ctx, WriteOnlyKeyValueCommand command) {
failurePolicy.handleWriteOnlyKeyValueFailure(site, command.getKey());
return null;
}
@Override
public Object visitWriteOnlyManyCommand(InvocationContext ctx, WriteOnlyManyCommand command) {
failurePolicy.handleWriteOnlyManyFailure(site, command.getAffectedKeys());
return null;
}
@Override
public Object visitReadWriteManyCommand(InvocationContext ctx, ReadWriteManyCommand command) {
failurePolicy.handleReadWriteManyFailure(site, command.getAffectedKeys());
return null;
}
@Override
public Object visitReadWriteManyEntriesCommand(InvocationContext ctx, ReadWriteManyEntriesCommand command) {
failurePolicy.handleReadWriteManyEntriesFailure(site, command.getArguments());
return null;
}
@Override
public Object visitClearCommand(InvocationContext ctx, ClearCommand command) {
failurePolicy.handleClearFailure(site);
return null;
}
@Override
public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) {
failurePolicy.handlePutAllFailure(site, command.getMap());
return null;
}
@Override
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) {
failurePolicy.handlePrepareFailure(site, tx);
return null;
}
@Override
public Object visitRollbackCommand(TxInvocationContext ctx, RollbackCommand command) {
failurePolicy.handleRollbackFailure(site, tx);
return null;
}
@Override
public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) {
failurePolicy.handleCommitFailure(site, tx);
return null;
}
@Override
protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
super.handleDefault(ctx, command);
throw new IllegalStateException("Unknown command: " + command);
}
}
}
| 21,034
| 40.32613
| 132
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/BackupFailureException.java
|
package org.infinispan.xsite;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.infinispan.remoting.RpcException;
/**
* Exception to be used to signal failures to backup to remote sites.
*
* @author Mircea Markus
* @since 5.2
*/
public class BackupFailureException extends RpcException {
private Map<String,Throwable> failures;
private String localCacheName;
public BackupFailureException(String localCacheName) {
this.localCacheName = localCacheName;
}
public BackupFailureException() {
}
public void addFailure(String site, Throwable t) {
if(site != null && t != null) {
if(failures == null)
failures = new HashMap<>(3);
failures.put(site, t);
}
}
public String getRemoteSiteNames() {
return failures != null? failures.keySet().toString() : null;
}
public String getLocalCacheName() {
return localCacheName;
}
@Override
public String getMessage() {
if(failures == null || failures.isEmpty())
return super.getMessage();
return "The local cache " + localCacheName + " failed to backup data to the remote sites:\n" +
failures.entrySet().stream().map(e -> e.getKey() + ": " + e.getValue())
.collect(Collectors.joining("\n"));
}
}
| 1,363
| 24.735849
| 100
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/XSiteBackup.java
|
package org.infinispan.xsite;
/**
* @author Mircea Markus
* @since 5.2
*/
public class XSiteBackup {
private final String siteName;
private final boolean sync;
private final long timeout;
public XSiteBackup(String siteName, boolean sync, long timeout) {
this.siteName = siteName;
this.sync = sync;
this.timeout = timeout;
}
public String getSiteName() {
return siteName;
}
public boolean isSync() {
return sync;
}
public long getTimeout() {
return timeout;
}
public String toString() {
return siteName + " (" + (sync? "sync" : "async") + ", timeout=" + timeout + ")";
}
}
| 663
| 17.971429
| 87
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/package-info.java
|
/**
* This is the private xsite package.
*
* @api.private
*/
package org.infinispan.xsite;
| 95
| 12.714286
| 37
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/XSiteAdminOperations.java
|
package org.infinispan.xsite;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.configuration.cache.TakeOfflineConfiguration;
import org.infinispan.configuration.cache.XSiteStateTransferMode;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.SurvivesRestarts;
import org.infinispan.factories.impl.MBeanMetadata;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.jmx.annotations.MBean;
import org.infinispan.jmx.annotations.ManagedOperation;
import org.infinispan.jmx.annotations.Parameter;
import org.infinispan.metrics.impl.CustomMetricsSupplier;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.rpc.RpcOptions;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ValidResponseCollector;
import org.infinispan.security.AuthorizationPermission;
import org.infinispan.security.impl.Authorizer;
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.response.AutoStateTransferResponse;
import org.infinispan.xsite.response.AutoStateTransferResponseCollector;
import org.infinispan.xsite.statetransfer.StateTransferStatus;
import org.infinispan.xsite.statetransfer.XSiteStateTransferManager;
import org.infinispan.xsite.status.BringSiteOnlineResponse;
import org.infinispan.xsite.status.CacheMixedSiteStatus;
import org.infinispan.xsite.status.CacheSiteStatusBuilder;
import org.infinispan.xsite.status.SiteState;
import org.infinispan.xsite.status.SiteStatus;
import org.infinispan.xsite.status.TakeOfflineManager;
import org.infinispan.xsite.status.TakeSiteOfflineResponse;
/**
* Managed bean exposing sys admin operations for Cross-Site replication functionality.
*
* @author Mircea Markus
* @since 5.2
*/
@Scope(Scopes.NAMED_CACHE)
@SurvivesRestarts
@MBean(objectName = "XSiteAdmin", description = "Exposes tooling for handling backing up data to remote sites.")
public class XSiteAdminOperations implements CustomMetricsSupplier {
public static final String ONLINE = "online";
public static final String FAILED = "failed";
public static final String OFFLINE = "offline";
public static final String SUCCESS = "ok";
private static final Function<CacheMixedSiteStatus, String> DEFAULT_MIXED_MESSAGES = s -> "mixed, offline on nodes: " + s.getOffline();
private static final Log log = LogFactory.getLog(XSiteAdminOperations.class);
@Inject RpcManager rpcManager;
@Inject XSiteStateTransferManager stateTransferManager;
@Inject CommandsFactory commandsFactory;
@Inject TakeOfflineManager takeOfflineManager;
@Inject
Authorizer authorizer;
public static String siteStatusToString(SiteStatus status, Function<CacheMixedSiteStatus, String> mixedFunction) {
if (status.isOffline()) {
return OFFLINE;
} else if (status.isOnline()) {
return ONLINE;
} else {
assert status instanceof CacheMixedSiteStatus;
return mixedFunction.apply((CacheMixedSiteStatus) status);
}
}
public static String siteStatusToString(SiteStatus status) {
return siteStatusToString(status, DEFAULT_MIXED_MESSAGES);
}
public Map<String, SiteStatus> clusterStatus() {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
Map<String, Boolean> localNodeStatus = takeOfflineManager.status();
CacheRpcCommand command = commandsFactory.buildXSiteStatusCommand();
XSiteResponse<Map<String, Boolean>> response = invokeOnAll(command,
new PerSiteBooleanResponseCollector(clusterSize()));
if (response.hasErrors()) {
throw new CacheException("Unable to check cluster state for members: " + response.getErrors());
}
//site name => online/offline/mixed
Map<String, CacheSiteStatusBuilder> perSiteBuilder = new HashMap<>();
for (Map.Entry<String, Boolean> entry : localNodeStatus.entrySet()) {
CacheSiteStatusBuilder builder = new CacheSiteStatusBuilder();
builder.addMember(rpcManager.getAddress(), entry.getValue());
perSiteBuilder.put(entry.getKey(), builder);
}
response.forEach((address, sites) -> {
for (Map.Entry<String, Boolean> site : sites.entrySet()) {
CacheSiteStatusBuilder builder = perSiteBuilder.get(site.getKey());
if (builder == null) {
throw new IllegalStateException("Site " + site.getKey() + " not defined in all the cluster members");
}
builder.addMember(address, site.getValue());
}
});
Map<String, SiteStatus> result = new HashMap<>();
perSiteBuilder.forEach((site, builder) -> result.put(site, builder.build()));
return result;
}
@ManagedOperation(description = "Check whether the given backup site is offline or not.", displayName = "Check whether the given backup site is offline or not.")
public String siteStatus(@Parameter(name = "site", description = "The name of the backup site") String site) {
//also consider local node
if (takeOfflineManager.getSiteState(site) == SiteState.NOT_FOUND) {
return incorrectSiteName(site);
}
Map<Address, String> statuses = nodeStatus(site);
List<Address> online = new ArrayList<>(statuses.size());
List<Address> offline = new ArrayList<>(statuses.size());
List<Address> failed = new ArrayList<>(statuses.size());
statuses.forEach((a, s) -> {
if (s.equals(FAILED)) failed.add(a);
if (s.equals(OFFLINE)) offline.add(a);
if (s.equals(ONLINE)) online.add(a);
});
if (!failed.isEmpty()) return rpcError(failed, "Could not query nodes ");
if (offline.isEmpty()) return ONLINE;
if (online.isEmpty()) return OFFLINE;
return "Site appears online on nodes:" + online + " and offline on nodes: " + offline;
}
/**
* Obtain the status of the nodes from a site
*
* @param site The name of the backup site
* @return a Map<String, String> with the Address and the status of each node in the site
*/
public Map<Address, String> nodeStatus(String site) {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
SiteState state = takeOfflineManager.getSiteState(site);
if (state == SiteState.NOT_FOUND) {
throw new IllegalArgumentException(incorrectSiteName(site));
}
CacheRpcCommand command = commandsFactory.buildXSiteOfflineStatusCommand(site);
XSiteResponse<Boolean> response = invokeOnAll(command, new XSiteStatusResponseCollector(clusterSize()));
Map<Address, String> statusMap = new HashMap<>();
response.forEachError(address -> statusMap.put(address, FAILED));
response.forEach((address, offline) -> statusMap.put(address, offline ? OFFLINE : ONLINE));
statusMap.put(rpcManager.getAddress(), state == SiteState.OFFLINE ? OFFLINE : ONLINE);
return statusMap;
}
@ManagedOperation(description = "Returns the the status(offline/online) of all the configured backup sites.", displayName = "Returns the the status(offline/online) of all the configured backup sites.")
public String status() {
Map<String, SiteStatus> statuses = clusterStatus();
List<String> result = new ArrayList<>(statuses.size());
statuses.forEach((site, status) -> result.add(site + "[" + siteStatusToString(status).toUpperCase() + "]"));
return String.join("\n", result);
}
@ManagedOperation(description = "Takes this site offline in all nodes in the cluster.", displayName = "Takes this site offline in all nodes in the cluster.")
public String takeSiteOffline(@Parameter(name = "site", description = "The name of the backup site") String site) {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
TakeSiteOfflineResponse rsp = takeOfflineManager.takeSiteOffline(site);
if (rsp == TakeSiteOfflineResponse.NO_SUCH_SITE) {
return incorrectSiteName(site);
}
CacheRpcCommand command = commandsFactory.buildXSiteTakeOfflineCommand(site);
XSiteResponse<Void> response = invokeOnAll(command, new VoidResponseCollector(clusterSize()));
String prefix = "Could not take the site offline on nodes:";
return returnFailureOrSuccess(response.getErrors(), prefix);
}
@ManagedOperation(description = "Amends the values for 'afterFailures' for the 'TakeOffline' functionality on all the nodes in the cluster.", displayName = "Amends the values for 'TakeOffline.afterFailures' on all the nodes in the cluster.")
public String setTakeOfflineAfterFailures(
@Parameter(name = "site", description = "The name of the backup site") String site,
@Parameter(name = "afterFailures", description = "The number of failures after which the site will be taken offline") int afterFailures) {
return takeOffline(site, afterFailures, null);
}
@ManagedOperation(description = "Amends the values for 'minTimeToWait' for the 'TakeOffline' functionality on all the nodes in the cluster.", displayName = "Amends the values for 'TakeOffline.minTimeToWait' on all the nodes in the cluster.")
public String setTakeOfflineMinTimeToWait(
@Parameter(name = "site", description = "The name of the backup site") String site,
@Parameter(name = "minTimeToWait", description = "The minimum amount of time in milliseconds to wait before taking a site offline") long minTimeToWait) {
return takeOffline(site, null, minTimeToWait);
}
@ManagedOperation(description = "Amends the values for 'TakeOffline' functionality on all the nodes in the cluster.", displayName = "Amends the values for 'TakeOffline' functionality on all the nodes in the cluster.")
public String amendTakeOffline(
@Parameter(name = "site", description = "The name of the backup site") String site,
@Parameter(name = "afterFailures", description = "The number of failures after which the site will be taken offline") int afterFailures,
@Parameter(name = "minTimeToWait", description = "The minimum amount of time in milliseconds to wait before taking a site offline") long minTimeToWait) {
return takeOffline(site, afterFailures, minTimeToWait);
}
@ManagedOperation(description = "Returns the value of the 'minTimeToWait' for the 'TakeOffline' functionality.", displayName = "Returns the value of the 'minTimeToWait' for the 'TakeOffline' functionality.")
public String getTakeOfflineMinTimeToWait(@Parameter(name = "site", description = "The name of the backup site") String site) {
TakeOfflineConfiguration config = getTakeOfflineConfiguration(site);
return config == null ? incorrectSiteName(site) : String.valueOf(config.minTimeToWait());
}
@ManagedOperation(description = "Returns the value of the 'afterFailures' for the 'TakeOffline' functionality.", displayName = "Returns the value of the 'afterFailures' for the 'TakeOffline' functionality.")
public String getTakeOfflineAfterFailures(
@Parameter(name = "site", description = "The name of the backup site") String site) {
TakeOfflineConfiguration config = getTakeOfflineConfiguration(site);
return config == null ? incorrectSiteName(site) : String.valueOf(config.afterFailures());
}
public TakeOfflineConfiguration getTakeOfflineConfiguration(String site) {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
return takeOfflineManager.getConfiguration(site);
}
public boolean checkSite(String site) {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
return takeOfflineManager.getSiteState(site) != SiteState.NOT_FOUND;
}
@ManagedOperation(description = "Brings the given site back online on all the cluster.", displayName = "Brings the given site back online on all the cluster.")
public String bringSiteOnline(@Parameter(name = "site", description = "The name of the backup site") String site) {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
BringSiteOnlineResponse rsp = takeOfflineManager.bringSiteOnline(site);
if (rsp == BringSiteOnlineResponse.NO_SUCH_SITE) {
return incorrectSiteName(site);
}
CacheRpcCommand command = commandsFactory.buildXSiteBringOnlineCommand(site);
XSiteResponse<Void> response = invokeOnAll(command, new VoidResponseCollector(clusterSize()));
return returnFailureOrSuccess(response.getErrors(), "Could not take the site online on nodes:");
}
@ManagedOperation(displayName = "Push state to site",
description = "Pushes the state of this cache to the remote site. " +
"The remote site will be bring back online",
name = "pushState")
public final String pushState(@Parameter(description = "The destination site name", name = "SiteName") String siteName) {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
try {
String status = bringSiteOnline(siteName);
if (!SUCCESS.equals(status)) {
return String.format("Unable to pushState to '%s'. %s", siteName, status);
}
stateTransferManager.startPushState(siteName);
} catch (Throwable throwable) {
log.xsiteAdminOperationError("pushState", siteName, throwable);
return String.format("Unable to pushState to '%s'. %s", siteName, throwable.getLocalizedMessage());
}
return SUCCESS;
}
/**
* for debug only!
*/
public final List<String> getRunningStateTransfer() {
return stateTransferManager.getRunningStateTransfers();
}
@ManagedOperation(displayName = "Push State Status",
description = "Shows a map with destination site name and the state transfer status.",
name = "PushStateStatus")
public final Map<String, String> getPushStateStatus() {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
try {
return stateTransferManager.getClusterStatus()
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> StateTransferStatus.toText(entry.getValue())));
} catch (Exception e) {
return Collections.singletonMap(XSiteStateTransferManager.STATUS_ERROR, e.getLocalizedMessage());
}
}
@ManagedOperation(displayName = "Clear State Status",
description = "Clears the state transfer status.",
name = "ClearPushStateStatus")
public final String clearPushStateStatus() {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
return performOperation("clearPushStateStatus", "(local)", () -> stateTransferManager.clearClusterStatus());
}
@ManagedOperation(displayName = "Cancel Push State",
description = "Cancels the push state to remote site.",
name = "CancelPushState")
public final String cancelPushState(@Parameter(description = "The destination site name", name = "SiteName")
final String siteName) {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
return performOperation("cancelPushState", siteName, () -> stateTransferManager.cancelPushState(siteName));
}
@ManagedOperation(displayName = "Cancel Receive State",
description = "Cancels the push state to this site. All the state received from state transfer " +
"will be ignored.",
name = "CancelReceiveState")
public final String cancelReceiveState(@Parameter(description = "The sending site name", name = "SiteName")
final String siteName) {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
return performOperation("cancelReceiveState", siteName, () -> stateTransferManager.cancelReceive(siteName));
}
@ManagedOperation(displayName = "Sending Site Name",
description = "Returns the site name from which this site is receiving state.",
name = "SendingSiteName")
public final String getSendingSiteName() {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
return stateTransferManager.getSendingSiteName();
}
public final CompletionStage<String> asyncGetStateTransferMode(String site) {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
//check local first
if (stateTransferManager.stateTransferMode(site) == XSiteStateTransferMode.MANUAL) {
return CompletableFuture.completedFuture(XSiteStateTransferMode.MANUAL.toString());
}
ReplicableCommand cmd = commandsFactory.buildXSiteAutoTransferStatusCommand(site);
AutoStateTransferResponseCollector collector = new AutoStateTransferResponseCollector(true, XSiteStateTransferMode.AUTO);
return rpcManager.invokeCommandOnAll(cmd, collector, rpcManager.getSyncRpcOptions())
.thenApply(AutoStateTransferResponse::stateTransferMode)
.thenApply(Enum::toString);
}
@ManagedOperation(displayName = "State Transfer Mode",
description = "Returns the cross-site replication state transfer mode.",
name = "GetStateTransferMode")
public final String getStateTransferMode(String site) {
return CompletionStages.join(asyncGetStateTransferMode(site));
}
public CompletionStage<Boolean> asyncSetStateTransferMode(String site, String mode) {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
XSiteStateTransferMode stateTransferMode = XSiteStateTransferMode.valueOf(mode);
//update locally first
if (!stateTransferManager.setAutomaticStateTransfer(site, stateTransferMode)) {
//failed
return CompletableFutures.completedFalse();
}
ReplicableCommand cmd = commandsFactory.buildXSiteSetStateTransferModeCommand(site, stateTransferMode);
return rpcManager.invokeCommandOnAll(cmd, org.infinispan.remoting.transport.impl.VoidResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions())
.thenApply(o -> Boolean.TRUE);
}
@ManagedOperation(displayName = "Sets State Transfer Mode",
description = "Sets the cross-site state transfer mode.",
name = "SetStateTransferMode")
public final boolean setStateTransferMode(String site, String mode) {
return CompletionStages.join(asyncSetStateTransferMode(site, mode));
}
private static String performOperation(String operationName, String siteName, Operation operation) {
try {
operation.execute();
} catch (Throwable t) {
log.xsiteAdminOperationError(operationName, siteName, t);
return String.format("Unable to perform operation. Error=%s", t.getLocalizedMessage());
}
return SUCCESS;
}
private String takeOffline(String site, Integer afterFailures, Long minTimeToWait) {
authorizer.checkPermission(AuthorizationPermission.ADMIN);
if (takeOfflineManager.getSiteState(site) == SiteState.NOT_FOUND) {
return incorrectSiteName(site);
}
CacheRpcCommand command = commandsFactory.buildXSiteAmendOfflineStatusCommand(site, afterFailures, minTimeToWait);
XSiteResponse<Void> response = invokeOnAll(command, new VoidResponseCollector(clusterSize()));
//also amend locally
takeOfflineManager.amendConfiguration(site, afterFailures, minTimeToWait);
return returnFailureOrSuccess(response.getErrors(), "Could not amend for nodes:");
}
private String returnFailureOrSuccess(List<Address> failed, String prefix) {
if (!failed.isEmpty()) {
return rpcError(failed, prefix);
}
return SUCCESS;
}
private String rpcError(List<Address> failed, String prefix) {
return prefix + failed.toString();
}
private String incorrectSiteName(String site) {
return "Incorrect site name: " + site;
}
private <T> XSiteResponse<T> invokeOnAll(CacheRpcCommand command, BaseResponseCollector<T> responseCollector) {
RpcOptions rpcOptions = rpcManager.getSyncRpcOptions();
CompletionStage<XSiteResponse<T>> rsp = rpcManager.invokeCommandOnAll(command, responseCollector, rpcOptions);
return rpcManager.blocking(rsp);
}
private int clusterSize() {
return rpcManager.getTransport().getMembers().size();
}
@Override
public Collection<MBeanMetadata.AttributeMetadata> getCustomMetrics() {
return takeOfflineManager.getCustomMetrics();
}
private interface Operation {
void execute() throws Throwable;
}
private static abstract class BaseResponseCollector<T> extends ValidResponseCollector<XSiteResponse<T>> {
final Map<Address, T> okResponses;
final List<Address> errors;
private BaseResponseCollector(int expectedSize) {
okResponses = new HashMap<>(expectedSize);
errors = new ArrayList<>(expectedSize);
}
@Override
public final XSiteResponse<T> finish() {
return new XSiteResponse<>(okResponses, errors);
}
abstract void storeResponse(Address sender, ValidResponse response);
@Override
protected final XSiteResponse<T> addValidResponse(Address sender, ValidResponse response) {
storeResponse(sender, response);
return null;
}
@Override
protected final XSiteResponse<T> addTargetNotFound(Address sender) {
//ignore leavers
return null;
}
@Override
protected final XSiteResponse<T> addException(Address sender, Exception exception) {
errors.add(sender);
return null;
}
}
private static class XSiteResponse<T> {
final Map<Address, T> responses;
final List<Address> errors;
private XSiteResponse(Map<Address, T> responses, List<Address> errors) {
this.responses = responses;
this.errors = errors;
}
boolean hasErrors() {
return !errors.isEmpty();
}
List<Address> getErrors() {
return errors;
}
void forEachError(Consumer<Address> consumer) {
errors.forEach(consumer);
}
void forEach(BiConsumer<Address, T> consumer) {
responses.forEach(consumer);
}
}
private static class VoidResponseCollector extends BaseResponseCollector<Void> {
private VoidResponseCollector(int expectedSize) {
super(expectedSize);
}
@Override
void storeResponse(Address sender, ValidResponse response) {
//no-op
}
}
private static class XSiteStatusResponseCollector extends BaseResponseCollector<Boolean> {
private XSiteStatusResponseCollector(int expectedSize) {
super(expectedSize);
}
@Override
void storeResponse(Address sender, ValidResponse response) {
Object value = response.getResponseValue();
assert value instanceof Boolean;
okResponses.put(sender, (Boolean) value);
}
}
private static class PerSiteBooleanResponseCollector extends BaseResponseCollector<Map<String, Boolean>> {
private PerSiteBooleanResponseCollector(int expectedSize) {
super(expectedSize);
}
@Override
void storeResponse(Address sender, ValidResponse response) {
//noinspection unchecked
okResponses.put(sender, (Map<String, Boolean>) response.getResponseValue());
}
}
}
| 24,162
| 44.333959
| 244
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/ClusteredCacheBackupReceiver.java
|
package org.infinispan.xsite;
import static org.infinispan.commons.util.concurrent.CompletableFutures.asCompletionException;
import static org.infinispan.context.Flag.IGNORE_RETURN_VALUES;
import static org.infinispan.context.Flag.SKIP_XSITE_BACKUP;
import static org.infinispan.remoting.transport.impl.MapResponseCollector.validOnly;
import static org.infinispan.util.logging.Log.XSITE;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import jakarta.transaction.TransactionManager;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.cache.impl.InvocationHelper;
import org.infinispan.commands.AbstractVisitor;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.IracPutKeyValueCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.RemoveExpiredCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.InvocationContextFactory;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.functional.FunctionalMap;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.WriteOnlyMapImpl;
import org.infinispan.interceptors.locking.ClusteringDependentLogic;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.marshall.core.MarshallableFunctions;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.IracMetadata;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.remoting.LocalInvocation;
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;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.rpc.RpcOptions;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollector;
import org.infinispan.remoting.transport.ResponseCollectors;
import org.infinispan.transaction.impl.LocalTransaction;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.AggregateCompletionStage;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.concurrent.TimeoutException;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.commands.XSiteStateTransferFinishReceiveCommand;
import org.infinispan.xsite.commands.XSiteStateTransferStartReceiveCommand;
import org.infinispan.xsite.irac.DiscardUpdateException;
import org.infinispan.xsite.statetransfer.XSiteState;
import org.infinispan.xsite.statetransfer.XSiteStatePushCommand;
/**
* {@link org.infinispan.xsite.BackupReceiver} implementation for clustered caches.
*
* @author Pedro Ruivo
* @since 7.1
*/
@Scope(Scopes.NAMED_CACHE)
public class ClusteredCacheBackupReceiver implements BackupReceiver {
private static final Log log = LogFactory.getLog(ClusteredCacheBackupReceiver.class);
private static final BiFunction<Object, Throwable, Void> CHECK_EXCEPTION = (o, throwable) -> {
if (throwable == null || throwable instanceof DiscardUpdateException) {
//for optimistic transaction, signals the update was discarded
return null;
}
throw CompletableFutures.asCompletionException(throwable);
};
@Inject Cache<Object, Object> cache;
@Inject TimeService timeService;
@Inject CommandsFactory commandsFactory;
@Inject KeyPartitioner keyPartitioner;
@Inject InvocationHelper invocationHelper;
@Inject InvocationContextFactory invocationContextFactory;
@Inject RpcManager rpcManager;
@Inject ClusteringDependentLogic clusteringDependentLogic;
private final ByteString cacheName;
private volatile DefaultHandler defaultHandler;
public ClusteredCacheBackupReceiver(String cacheName) {
//TODO #3 [ISPN-11824] split this class for pes/opt tx and non tx mode.
this.cacheName = ByteString.fromString(cacheName);
}
@Start
public void start() {
//it would be nice if we could inject bootstrap component
//this feels kind hacky but saves 3 fields in this class
ComponentRegistry cr = cache.getAdvancedCache().getComponentRegistry();
TransactionHandler txHandler = new TransactionHandler(cache, cr.getTransactionTable());
defaultHandler = new DefaultHandler(txHandler, cr.getComponent(BlockingManager.class));
}
@Override
public CompletionStage<Void> handleStartReceivingStateTransfer(XSiteStateTransferStartReceiveCommand command) {
return invokeRemotelyInLocalSite(XSiteStateTransferStartReceiveCommand.copyForCache(command, cacheName));
}
@Override
public CompletionStage<Void> handleEndReceivingStateTransfer(XSiteStateTransferFinishReceiveCommand command) {
return invokeRemotelyInLocalSite(XSiteStateTransferFinishReceiveCommand.copyForCache(command, cacheName));
}
private static PrivateMetadata internalMetadata(IracMetadata metadata) {
return new PrivateMetadata.Builder()
.iracMetadata(metadata)
.build();
}
@Override
public CompletionStage<Void> handleStateTransferState(XSiteStatePushCommand cmd) {
//split the state and forward it to the primary owners...
CompletableFuture<Void> allowInvocation = checkInvocationAllowedFuture();
if (allowInvocation != null) {
return allowInvocation;
}
final long endTime = timeService.expectedEndTime(cmd.getTimeout(), TimeUnit.MILLISECONDS);
final Map<Address, List<XSiteState>> primaryOwnersChunks = new HashMap<>();
final Address localAddress = rpcManager.getAddress();
if (log.isTraceEnabled()) {
log.tracef("Received X-Site state transfer '%s'. Splitting by primary owner.", cmd);
}
for (XSiteState state : cmd.getChunk()) {
Address primaryOwner = clusteringDependentLogic.getCacheTopology().getDistribution(state.key()).primary();
List<XSiteState> primaryOwnerList = primaryOwnersChunks.computeIfAbsent(primaryOwner, k -> new LinkedList<>());
primaryOwnerList.add(state);
}
final List<XSiteState> localChunks = primaryOwnersChunks.remove(localAddress);
AggregateCompletionStage<Void> cf = CompletionStages.aggregateCompletionStage();
for (Map.Entry<Address, List<XSiteState>> entry : primaryOwnersChunks.entrySet()) {
if (entry.getValue() == null || entry.getValue().isEmpty()) {
continue;
}
if (log.isTraceEnabled()) {
log.tracef("Node '%s' will apply %s", entry.getKey(), entry.getValue());
}
StatePushTask task = new StatePushTask(entry.getValue(), entry.getKey(), endTime);
task.executeRemote();
cf.dependsOn(task);
}
//help gc. this is safe because the chunks was already sent
primaryOwnersChunks.clear();
if (log.isTraceEnabled()) {
log.tracef("Local node '%s' will apply %s", localAddress, localChunks);
}
if (localChunks != null) {
StatePushTask task = new StatePushTask(localChunks, localAddress, endTime);
task.executeLocal();
cf.dependsOn(task);
}
return cf.freeze().thenApply(this::assertAllowInvocationFunction);
}
@Override
public final <O> CompletionStage<O> handleRemoteCommand(VisitableCommand command, boolean preserveOrder) {
try {
//currently, it only handles sync xsite requests.
//async xsite requests are handle by the other methods.
assert !preserveOrder;
//noinspection unchecked
return (CompletionStage<O>) command.acceptVisitor(null, defaultHandler);
} catch (Throwable throwable) {
return CompletableFuture.failedFuture(throwable);
}
}
@Override
public CompletionStage<Void> putKeyValue(Object key, Object value, Metadata metadata, IracMetadata iracMetadata) {
IracPutKeyValueCommand cmd = commandsFactory.buildIracPutKeyValueCommand(key, segment(key), value, metadata,
internalMetadata(iracMetadata));
InvocationContext ctx = invocationContextFactory.createSingleKeyNonTxInvocationContext();
return invocationHelper.invokeAsync(ctx, cmd).handle(CHECK_EXCEPTION);
}
@Override
public CompletionStage<Void> removeKey(Object key, IracMetadata iracMetadata, boolean expiration) {
IracPutKeyValueCommand cmd = commandsFactory.buildIracPutKeyValueCommand(key, segment(key), null, null,
internalMetadata(iracMetadata));
cmd.setExpiration(expiration);
InvocationContext ctx = invocationContextFactory.createSingleKeyNonTxInvocationContext();
return invocationHelper.invokeAsync(ctx, cmd).handle(CHECK_EXCEPTION);
}
private <T> CompletableFuture<T> checkInvocationAllowedFuture() {
//TODO #4 [ISPN-11824] no need to change the ComponentStatus. we have start/stop methods available now
ComponentStatus status = cache.getStatus();
if (!status.allowInvocations()) {
return CompletableFuture.failedFuture(
new IllegalLifecycleStateException("Cache is stopping or terminated: " + status));
}
return null;
}
private Void assertAllowInvocationFunction(Object ignoredRetVal) {
//the put operation can fail silently. check in the end and it is better to resend the chunk than to lose keys.
ComponentStatus status = cache.getStatus();
if (!status.allowInvocations()) {
throw asCompletionException(new IllegalLifecycleStateException("Cache is stopping or terminated: " + status));
}
return null;
}
private XSiteStatePushCommand newStatePushCommand(List<XSiteState> stateList) {
return commandsFactory.buildXSiteStatePushCommand(stateList.toArray(new XSiteState[0]), 0);
}
@Override
public CompletionStage<Void> clearKeys() {
return defaultHandler.cache().clearAsync();
}
@Override
public CompletionStage<Boolean> touchEntry(Object key) {
return cache.getAdvancedCache().touch(key, false);
}
private CompletionStage<Void> invokeRemotelyInLocalSite(CacheRpcCommand command) {
CompletionStage<Map<Address, Response>> remote = rpcManager
.invokeCommandOnAll(command, validOnly(), rpcManager.getSyncRpcOptions());
//TODO #5 [ISPN-11824] this allocations can be removed and invoke XSiteStateConsumer
//handleStartReceivingStateTransfer and handleEndReceivingStateTransfer can be merged. both interact with XSiteStateConsumer.
CompletionStage<Response> local = LocalInvocation.newInstanceFromCache(cache, command).callAsync();
return CompletableFuture.allOf(remote.toCompletableFuture(), local.toCompletableFuture());
}
private int segment(Object key) {
return keyPartitioner.getSegment(key);
}
private static class DefaultHandler extends AbstractVisitor {
final TransactionHandler txHandler;
final BlockingManager blockingManager;
private DefaultHandler(TransactionHandler txHandler, BlockingManager blockingManager) {
this.txHandler = txHandler;
this.blockingManager = blockingManager;
}
@Override
public CompletionStage<Object> visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) {
return cache().putAsync(command.getKey(), command.getValue(), command.getMetadata());
}
@Override
public CompletionStage<Object> visitRemoveCommand(InvocationContext ctx, RemoveCommand command) {
return cache().removeAsync(command.getKey());
}
@Override
public Object visitRemoveExpiredCommand(InvocationContext ctx, RemoveExpiredCommand command) {
if (!command.isMaxIdle()) {
throw new UnsupportedOperationException("Lifespan based expiration is not supported for xsite");
}
return cache().removeMaxIdleExpired(command.getKey(), command.getValue());
}
@Override
public CompletionStage<Void> visitWriteOnlyManyEntriesCommand(InvocationContext ctx,
WriteOnlyManyEntriesCommand command) {
//noinspection unchecked
return fMap().evalMany(command.getArguments(), MarshallableFunctions.setInternalCacheValueConsumer());
}
@Override
public final CompletionStage<Void> visitClearCommand(InvocationContext ctx, ClearCommand command) {
return cache().clearAsync();
}
@Override
public CompletionStage<Void> visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) {
return blockingManager.runBlocking(() -> txHandler.handlePrepareCommand(command), command.getCommandId());
}
@Override
public CompletionStage<Void> visitCommitCommand(TxInvocationContext ctx, CommitCommand command) {
return blockingManager.runBlocking(() -> txHandler.handleCommitCommand(command), command.getCommandId());
}
@Override
public CompletionStage<Void> visitRollbackCommand(TxInvocationContext ctx, RollbackCommand command) {
return blockingManager.runBlocking(() -> txHandler.handleRollbackCommand(command), command.getCommandId());
}
@Override
protected final Object handleDefault(InvocationContext ctx, VisitableCommand command) {
throw new UnsupportedOperationException();
}
private AdvancedCache<Object, Object> cache() {
return txHandler.backupCache;
}
private FunctionalMap.WriteOnlyMap<Object, Object> fMap() {
return txHandler.writeOnlyMap;
}
}
// All conditional commands are unsupported
private static final class TransactionHandler extends AbstractVisitor {
private static final Log log = LogFactory.getLog(TransactionHandler.class);
private final ConcurrentMap<GlobalTransaction, GlobalTransaction> remote2localTx;
private final AdvancedCache<Object, Object> backupCache;
private final FunctionalMap.WriteOnlyMap<Object, Object> writeOnlyMap;
private final TransactionTable transactionTable;
TransactionHandler(Cache<Object, Object> backup, TransactionTable transactionTable) {
//ignore return values on the backup
this.backupCache = backup.getAdvancedCache().withStorageMediaType().withFlags(IGNORE_RETURN_VALUES, SKIP_XSITE_BACKUP);
this.writeOnlyMap = WriteOnlyMapImpl.create(FunctionalMapImpl.create(backupCache));
this.remote2localTx = new ConcurrentHashMap<>();
this.transactionTable = transactionTable;
}
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) {
if (command.isConditional()) {
throw new UnsupportedOperationException();
}
backupCache.put(command.getKey(), command.getValue(), command.getMetadata());
return null;
}
@Override
public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) {
if (command.isConditional()) {
throw new UnsupportedOperationException();
}
backupCache.remove(command.getKey());
return null;
}
@Override
public Object visitWriteOnlyManyEntriesCommand(InvocationContext ctx, WriteOnlyManyEntriesCommand command) {
CompletableFuture<?> future = writeOnlyMap
.evalMany(command.getArguments(), MarshallableFunctions.setInternalCacheValueConsumer());
return future.join();
}
void handlePrepareCommand(PrepareCommand command) {
if (isTransactional()) {
// Sanity check -- if the remote tx doesn't have modifications, it never should have been propagated!
if (!command.hasModifications()) {
throw new IllegalStateException("TxInvocationContext has no modifications!");
}
try {
replayModificationsInTransaction(command, command.isOnePhaseCommit());
} catch (Throwable throwable) {
throw CompletableFutures.asCompletionException(throwable);
}
} else {
try {
replayModifications(command);
} catch (Throwable throwable) {
throw CompletableFutures.asCompletionException(throwable);
}
}
}
void handleCommitCommand(CommitCommand command) {
if (!isTransactional()) {
log.cannotRespondToCommit(command.getGlobalTransaction(), backupCache.getName());
} else {
if (log.isTraceEnabled()) {
log.tracef("Committing remote transaction %s", command.getGlobalTransaction());
}
try {
completeTransaction(command.getGlobalTransaction(), true);
} catch (Throwable throwable) {
throw CompletableFutures.asCompletionException(throwable);
}
}
}
void handleRollbackCommand(RollbackCommand command) {
if (!isTransactional()) {
log.cannotRespondToRollback(command.getGlobalTransaction(), backupCache.getName());
} else {
if (log.isTraceEnabled()) {
log.tracef("Rolling back remote transaction %s", command.getGlobalTransaction());
}
try {
completeTransaction(command.getGlobalTransaction(), false);
} catch (Throwable throwable) {
throw CompletableFutures.asCompletionException(throwable);
}
}
}
@Override
protected Object handleDefault(InvocationContext ctx, VisitableCommand command) {
throw new UnsupportedOperationException();
}
private boolean isTransactional() {
return transactionTable != null;
}
private void completeTransaction(GlobalTransaction globalTransaction, boolean commit) throws Throwable {
GlobalTransaction localTxId = remote2localTx.remove(globalTransaction);
if (localTxId == null) {
throw XSITE.unableToFindRemoteSiteTransaction(globalTransaction);
}
LocalTransaction localTx = transactionTable.getLocalTransaction(localTxId);
if (localTx == null) {
throw XSITE.unableToFindLocalTransactionFromRemoteSiteTransaction(globalTransaction);
}
TransactionManager txManager = txManager();
txManager.resume(localTx.getTransaction());
if (!localTx.isEnlisted()) {
if (log.isTraceEnabled()) {
log.tracef("%s isn't enlisted! Removing it manually.", localTx);
}
transactionTable.removeLocalTransaction(localTx);
}
if (commit) {
txManager.commit();
} else {
txManager.rollback();
}
}
private void replayModificationsInTransaction(PrepareCommand command, boolean onePhaseCommit) throws Throwable {
TransactionManager tm = txManager();
boolean replaySuccessful = false;
try {
tm.begin();
replayModifications(command);
replaySuccessful = true;
} finally {
LocalTransaction localTx = transactionTable.getLocalTransaction(tm.getTransaction());
if (localTx != null) { //possible for the tx to be null if we got an exception during applying modifications
localTx.setFromRemoteSite(true);
if (onePhaseCommit) {
if (replaySuccessful) {
if (log.isTraceEnabled()) {
log.tracef("Committing remotely originated tx %s as it is 1PC", command.getGlobalTransaction());
}
tm.commit();
} else {
if (log.isTraceEnabled()) {
log.tracef("Rolling back remotely originated tx %s", command.getGlobalTransaction());
}
tm.rollback();
}
} else { // Wait for a remote commit/rollback.
remote2localTx.put(command.getGlobalTransaction(), localTx.getGlobalTransaction());
tm.suspend();
}
}
}
}
private TransactionManager txManager() {
return backupCache.getTransactionManager();
}
private void replayModifications(PrepareCommand command) throws Throwable {
for (WriteCommand c : command.getModifications()) {
c.acceptVisitor(null, this);
}
}
}
private class StatePushTask extends CompletableFuture<Void>
implements ResponseCollector<Response>, BiFunction<Response, Throwable, Void> {
private final List<XSiteState> chunk;
private final Address address;
private final long endTime;
private StatePushTask(List<XSiteState> chunk, Address address, long endTime) {
this.chunk = chunk;
this.address = address;
this.endTime = endTime;
}
@Override
public Void apply(Response response, Throwable throwable) {
if (throwable != null) {
if (isShouldGiveUp()) {
return null;
}
if (rpcManager.getMembers().contains(this.address) && !rpcManager.getAddress().equals(this.address)) {
if (log.isTraceEnabled()) {
log.tracef(throwable, "An exception was sent by %s. Retrying!", this.address);
}
executeRemote(); //retry remote
} else {
if (log.isTraceEnabled()) {
log.tracef(throwable, "An exception was sent by %s. Retrying locally!", this.address);
}
//if the node left the cluster, we apply the missing state. This avoids the site provider to re-send the
//full chunk.
executeLocal(); //retry locally
}
} else if (response == CacheNotFoundResponse.INSTANCE) {
if (log.isTraceEnabled()) {
log.tracef("Cache not found in node '%s'. Retrying locally!", address);
}
if (isShouldGiveUp()) {
return null;
}
executeLocal(); //retry locally
} else {
complete(null);
}
return null;
}
@Override
public Response addResponse(Address sender, Response response) {
if (response instanceof ValidResponse || response instanceof CacheNotFoundResponse) {
return response;
} else if (response instanceof ExceptionResponse) {
throw ResponseCollectors.wrapRemoteException(sender, ((ExceptionResponse) response).getException());
} else {
throw ResponseCollectors
.wrapRemoteException(sender, new RpcException("Unknown response type: " + response));
}
}
@Override
public Response finish() {
return null;
}
private void executeRemote() {
RpcOptions rpcOptions = rpcManager.getSyncRpcOptions();
rpcManager.invokeCommand(address, newStatePushCommand(chunk), this, rpcOptions).handle(this);
}
private void executeLocal() {
//TODO #1 [ISPN-11824] make state transfer non blocking
//TODO #2 [ISPN-11824] avoid all this allocations by invoking XSiteStateConsumer.apply() directly
LocalInvocation.newInstanceFromCache(cache, newStatePushCommand(chunk)).callAsync().handle(this);
}
/**
* @return {@code null} if it can retry
*/
private boolean isShouldGiveUp() {
ComponentStatus status = cache.getStatus();
if (!status.allowInvocations()) {
completeExceptionally(new IllegalLifecycleStateException("Cache is stopping or terminated: " + status));
return true;
}
if (timeService.isTimeExpired(endTime)) {
completeExceptionally(new TimeoutException("Unable to apply state in the time limit."));
return true;
}
return false;
}
}
}
| 25,676
| 41.093443
| 131
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/OfflineStatus.java
|
package org.infinispan.xsite;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.time.TimeService;
import org.infinispan.configuration.cache.TakeOfflineConfiguration;
import org.infinispan.configuration.cache.TakeOfflineConfigurationBuilder;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.notification.SiteStatusListener;
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
/**
* Keeps state needed for knowing when a site needs to be taken offline.
* <p/>
* Thread safety: This class is updated from multiple threads so the access to it is synchronized by object's intrinsic
* lock.
* <p/>
* Impl detail: As this class's state changes constantly, the equals and hashCode haven't been overridden. This
* shouldn't affect performance significantly as the number of site backups should be relatively small (1-3).
*
* @author Mircea Markus
* @author Pedro Ruivo
* @since 5.2
*/
@ThreadSafe
public class OfflineStatus {
private static final Log log = LogFactory.getLog(OfflineStatus.class);
private static final long NO_FAILURE = -1;
private final TimeService timeService;
private final SiteStatusListener listener;
private volatile TakeOfflineConfiguration takeOffline;
@GuardedBy("this") private long firstFailureTime = NO_FAILURE;
@GuardedBy("this") private int failureCount = 0;
@GuardedBy("this") private boolean isOffline = false;
public OfflineStatus(TakeOfflineConfiguration takeOfflineConfiguration, TimeService timeService, SiteStatusListener listener) {
this.takeOffline = takeOfflineConfiguration;
this.timeService = timeService;
this.listener = listener;
}
public synchronized void updateOnCommunicationFailure(long sendTimeMillis) {
if (firstFailureTime == NO_FAILURE) {
firstFailureTime = sendTimeMillis;
}
failureCount++;
internalUpdateStatus();
}
public synchronized boolean isOffline() {
return isOffline;
}
public synchronized boolean minTimeHasElapsed() {
if (firstFailureTime == NO_FAILURE) {
return false;
}
return internalMinTimeHasElapsed();
}
public synchronized long millisSinceFirstFailure() {
return internalMillisSinceFirstFailure();
}
public synchronized boolean bringOnline() {
return isOffline && internalReset();
}
public synchronized int getFailureCount() {
return failureCount;
}
public synchronized boolean isEnabled() {
return takeOffline.enabled();
}
public synchronized void reset() {
internalReset();
}
public TakeOfflineConfiguration getTakeOffline() {
return takeOffline;
}
public synchronized boolean forceOffline() {
if (isOffline) {
return false;
}
isOffline = true;
listener.siteOffline();
return true;
}
@Override
public synchronized String toString() {
return "OfflineStatus{" +
"takeOffline=" + takeOffline +
", recordingOfflineStatus=" + (firstFailureTime != NO_FAILURE) +
", firstFailureTime=" + firstFailureTime +
", isOffline=" + isOffline +
", failureCount=" + failureCount +
'}';
}
public void amend(Integer afterFailures, Long minTimeToWait) {
TakeOfflineConfigurationBuilder builder = new TakeOfflineConfigurationBuilder(null, null);
builder.read(getTakeOffline(), Combine.DEFAULT);
if (afterFailures != null) {
builder.afterFailures(afterFailures);
}
if (minTimeToWait != null) {
builder.minTimeToWait(minTimeToWait);
}
amend(builder.create());
}
/**
* Configures the site to use the supplied configuration for determining when to take a site offline. Also triggers a
* state reset.
*/
private void amend(TakeOfflineConfiguration takeOffline) {
this.takeOffline = takeOffline;
reset();
}
@GuardedBy("this")
private void internalUpdateStatus() {
if (isOffline) {
//already offline
return;
}
boolean hasMinWait = takeOffline.minTimeToWait() > 0;
if (hasMinWait && !internalMinTimeHasElapsed()) {
//minTimeToWait() not elapsed yet.
return;
}
long minFailures = takeOffline.afterFailures();
if (minFailures > 0) {
if (minFailures <= failureCount) {
if (log.isTraceEnabled()) {
log.tracef("Site is failed: min failures (%s) reached (count=%s).", minFailures, failureCount);
}
listener.siteOffline();
isOffline = true;
}
//else, afterFailures() not reached yet.
} else if (hasMinWait) {
if (log.isTraceEnabled()) {
log.trace("Site is failed: minTimeToWait elapsed and we don't have a min failure number to wait for.");
}
listener.siteOffline();
isOffline = true;
}
//else, no afterFailures() neither minTimeToWait() configured
}
@GuardedBy("this")
private boolean internalMinTimeHasElapsed() {
long minTimeToWait = takeOffline.minTimeToWait();
if (minTimeToWait <= 0)
throw new IllegalStateException("Cannot invoke this method if minTimeToWait is not enabled");
long millis = internalMillisSinceFirstFailure();
if (millis >= minTimeToWait) {
if (log.isTraceEnabled()) {
log.tracef("The minTimeToWait has passed: minTime=%s, timeSinceFirstFailure=%s",
minTimeToWait, millis);
}
return true;
}
return false;
}
/**
* @return true if status changed
*/
@GuardedBy("this")
private boolean internalReset() {
boolean wasOffline = isOffline;
firstFailureTime = NO_FAILURE;
failureCount = 0;
isOffline = false;
if (wasOffline) {
listener.siteOnline();
}
return wasOffline;
}
@GuardedBy("this")
private long internalMillisSinceFirstFailure() {
return timeService.timeDuration(MILLISECONDS.toNanos(firstFailureTime), MILLISECONDS);
}
}
| 6,274
| 30.532663
| 130
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/AbstractCustomFailurePolicy.java
|
package org.infinispan.xsite;
import java.util.Map;
import jakarta.transaction.Transaction;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CustomFailurePolicy;
/**
* Support class for {@link CustomFailurePolicy}.
*
* @author Mircea Markus
* @since 5.2
*/
public abstract class AbstractCustomFailurePolicy<K,V> implements CustomFailurePolicy<K,V> {
protected volatile Cache<K,V> cache;
@Override
public void init(Cache<K, V> cache) {
this.cache = cache;
}
@Override
public void handlePutFailure(String site, K key, V value, boolean putIfAbsent) {
}
@Override
public void handleRemoveFailure(String site, K key, V oldValue) {
}
@Override
public void handleReplaceFailure(String site, K key, V oldValue, V newValue) {
}
@Override
public void handleClearFailure(String site) {
}
@Override
public void handlePutAllFailure(String site, Map<K, V> map) {
}
@Override
public void handlePrepareFailure(String site, Transaction transaction) {
}
@Override
public void handleRollbackFailure(String site, Transaction transaction) {
}
@Override
public void handleCommitFailure(String site, Transaction transaction) {
}
}
| 1,239
| 20.754386
| 92
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/SingleXSiteRpcCommand.java
|
package org.infinispan.xsite;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.util.ByteString;
/**
* RPC command to replicate cache operations (such as put, remove, replace, etc.) to the backup site.
*
* @author Pedro Ruivo
* @since 7.0
*/
public class SingleXSiteRpcCommand extends XSiteReplicateCommand<Object> {
public static final byte COMMAND_ID = 40;
private ReplicableCommand command;
public SingleXSiteRpcCommand(ByteString cacheName, ReplicableCommand command) {
super(COMMAND_ID, cacheName);
this.command = command;
}
public SingleXSiteRpcCommand(ByteString cacheName) {
this(cacheName, null);
}
public SingleXSiteRpcCommand() {
this(null);
}
@Override
public CompletionStage<Object> performInLocalSite(ComponentRegistry registry, boolean preserveOrder) {
// Need to check VisitableCommand before CacheRpcCommand as PrepareCommand implements both but need to visit
if (command instanceof VisitableCommand) {
return super.performInLocalSite(registry, preserveOrder);
} else {
try {
//noinspection unchecked
return (CompletionStage<Object>) ((CacheRpcCommand) command).invokeAsync(registry);
} catch (Throwable throwable) {
return CompletableFuture.failedFuture(throwable);
}
}
}
@Override
public CompletionStage<Object> performInLocalSite(BackupReceiver receiver, boolean preserveOrder) {
return receiver.handleRemoteCommand((VisitableCommand) command, preserveOrder);
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable {
throw new UnsupportedOperationException();
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(command);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
command = (ReplicableCommand) input.readObject();
}
@Override
public boolean isReturnValueExpected() {
return command.isReturnValueExpected();
}
@Override
public String toString() {
return "SingleXSiteRpcCommand{" +
"command=" + command +
'}';
}
}
| 2,617
| 29.44186
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/BackupSender.java
|
package org.infinispan.xsite;
import jakarta.transaction.Transaction;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.interceptors.InvocationStage;
import org.infinispan.remoting.transport.BackupResponse;
import org.infinispan.transaction.impl.AbstractCacheTransaction;
/**
* Component responsible with sending backup data to remote sites. The send operation is executed async, it's up to the
* caller to wait on the returned {@link BackupResponse} in the case it wants an sync call.
*
* @see BackupResponse
* @author Mircea Markus
* @since 5.2
*/
public interface BackupSender {
/**
* Prepares a transaction on the remote site.
*/
InvocationStage backupPrepare(PrepareCommand command, AbstractCacheTransaction cacheTransaction, Transaction transaction);
InvocationStage backupCommit(CommitCommand command, Transaction transaction);
InvocationStage backupRollback(RollbackCommand command, Transaction transaction);
InvocationStage backupWrite(WriteCommand command, WriteCommand originalCommand);
InvocationStage backupClear(ClearCommand command);
}
| 1,317
| 33.684211
| 125
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/GlobalXSiteAdminOperations.java
|
package org.infinispan.xsite;
import static java.util.stream.Collectors.toMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.infinispan.Cache;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.jmx.annotations.MBean;
import org.infinispan.jmx.annotations.ManagedOperation;
import org.infinispan.jmx.annotations.Parameter;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.security.AuthorizationPermission;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.xsite.statetransfer.XSiteStateTransferManager;
import org.infinispan.xsite.status.ContainerSiteStatusBuilder;
import org.infinispan.xsite.status.SiteStatus;
/**
* A per-container (cache manager) cross-site admin operations.
* <p>
* All the operations invoked in this class will be applied to all caches which remotely backups its data.
*
* @author Pedro Ruivo
* @since 8.1
*/
@Scope(Scopes.GLOBAL)
@MBean(objectName = "GlobalXSiteAdminOperations", description = "Exposes tooling for handling backing up data to remote sites.")
public class GlobalXSiteAdminOperations {
public static final String CACHE_DELIMITER = ",";
@Inject
EmbeddedCacheManager cacheManager;
private static void addCacheAdmin(Cache<?, ?> cache, List<CacheXSiteAdminOperation> list) {
if (cache != null) {
ComponentRegistry cacheRegistry = SecurityActions.getCacheComponentRegistry(cache.getAdvancedCache());
XSiteAdminOperations operation = cacheRegistry.getComponent(XSiteAdminOperations.class);
if (operation != null) {
list.add(new CacheXSiteAdminOperation(cache.getName(), operation));
}
}
}
public Map<String, String> takeAllCachesOffline(String site) {
return performMultiCacheOperation(operations -> operations.takeSiteOffline(site));
}
public Map<String, String> bringAllCachesOnline(String site) {
return performMultiCacheOperation(operations -> operations.bringSiteOnline(site));
}
public Map<String, String> pushStateAllCaches(String site) {
return performMultiCacheOperation(operations -> operations.pushState(site));
}
public Map<String, String> cancelPushStateAllCaches(String site) {
return performMultiCacheOperation(operations -> operations.cancelPushState(site));
}
@ManagedOperation(
description = "Takes this site offline in all caches in the cluster.",
displayName = "Takes this site offline in all caches in the cluster."
)
public String takeSiteOffline(@Parameter(name = "site", description = "The name of the backup site") String site) {
return toJMXResponse(performMultiCacheOperation(operations -> operations.takeSiteOffline(site)));
}
@ManagedOperation(
description = "Brings the given site back online on all the caches.",
displayName = "Brings the given site back online on all the caches."
)
public String bringSiteOnline(@Parameter(name = "site", description = "The name of the backup site") String site) {
return toJMXResponse(performMultiCacheOperation(operations -> operations.bringSiteOnline(site)));
}
@ManagedOperation(
displayName = "Push state to site",
description = "Pushes the state of all caches to the corresponding remote site if the cache backups to it. " +
"The remote site will be bring back online",
name = "pushState"
)
public final String pushState(@Parameter(description = "The destination site name", name = "SiteName") String site) {
return toJMXResponse(performMultiCacheOperation(operations -> operations.pushState(site)));
}
@ManagedOperation(
displayName = "Cancel Push State",
description = "Cancels the push state on all the caches to remote site.",
name = "CancelPushState"
)
public final String cancelPushState(
@Parameter(description = "The destination site name", name = "SiteName") final String site) {
return toJMXResponse(performMultiCacheOperation(operations -> operations.cancelPushState(site)));
}
public final Map<String, SiteStatus> globalStatus() {
SecurityActions.checkPermission(cacheManager, AuthorizationPermission.ADMIN);
final Iterator<CacheXSiteAdminOperation> iterator = collectXSiteAdminOperation().iterator();
if (!iterator.hasNext()) {
return Collections.emptyMap();
}
Map<String, ContainerSiteStatusBuilder> siteStatusBuilderMap = new HashMap<>();
while (iterator.hasNext()) {
CacheXSiteAdminOperation xsiteAdminOperation = iterator.next();
xsiteAdminOperation.xSiteAdminOperations.clusterStatus().forEach((site, status) -> {
ContainerSiteStatusBuilder builder = siteStatusBuilderMap.get(site);
if (builder == null) {
builder = new ContainerSiteStatusBuilder();
siteStatusBuilderMap.put(site, builder);
}
builder.addCacheName(xsiteAdminOperation.cacheName, status);
});
}
Map<String, SiteStatus> result = new HashMap<>();
siteStatusBuilderMap.forEach((site, builder) -> result.put(site, builder.build()));
return result;
}
/**
* Invoked when a remote site is connected.
* <p>
* This method is used to trigger the cross-site replication state transfer if it is enabled. It checks all the
* caches.
*
* @param sitesUp The {@link Collection} of remote sites online.
*/
public void onSitesUp(Collection<String> sitesUp) {
for (ComponentRegistry registry : SecurityActions.getGlobalComponentRegistry(cacheManager).getNamedComponentRegistries()) {
ComponentRef<XSiteStateTransferManager> st = registry.getXSiteStateTransferManager();
if (st != null) { //XSiteStateTransferManager not cached yet, meaning this node is starting up.
st.running().startAutomaticStateTransfer(sitesUp);
}
}
}
private String toJMXResponse(Map<String, String> results) {
return results.entrySet().stream()
.map(e -> e.getKey() + ": " + e.getValue())
.collect(Collectors.joining(CACHE_DELIMITER));
}
/**
* Execute an operation for all caches in the site
*
* @return A Map keyed by the cache name and with the outcome in the value. Possible values are 'ok' or the error
* message.
*/
private Map<String, String> performMultiCacheOperation(Operation operation) {
SecurityActions.checkPermission(cacheManager, AuthorizationPermission.ADMIN);
Collection<CacheXSiteAdminOperation> admOps = collectXSiteAdminOperation();
if (admOps.isEmpty()) {
return Collections.emptyMap();
}
return admOps.stream().collect(toMap(op -> op.cacheName, op -> {
try {
return operation.execute(op.xSiteAdminOperations);
} catch (Exception e) {
return "Exception on " + op.cacheName + " : " + e.getMessage();
}
}));
}
private Collection<CacheXSiteAdminOperation> collectXSiteAdminOperation() {
Collection<String> cacheNames = cacheManager.getCacheNames();
List<CacheXSiteAdminOperation> operations = new ArrayList<>(cacheNames.size() + 1);
for (String cacheName : cacheNames) {
addCacheAdmin(cacheManager.getCache(cacheName, false), operations);
}
return operations;
}
private interface Operation {
String execute(XSiteAdminOperations admins);
}
private static class CacheXSiteAdminOperation {
private final String cacheName;
private final XSiteAdminOperations xSiteAdminOperations;
private CacheXSiteAdminOperation(String cacheName, XSiteAdminOperations xSiteAdminOperations) {
this.cacheName = cacheName;
this.xSiteAdminOperations = xSiteAdminOperations;
}
}
}
| 8,263
| 40.114428
| 129
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/XSiteReplicateCommand.java
|
package org.infinispan.xsite;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.util.ByteString;
/**
* Abstract class to invoke RPC on the remote site.
*
* @author Pedro Ruivo
* @since 7.0
*/
public abstract class XSiteReplicateCommand<O> extends BaseRpcCommand {
private final byte commandId;
protected String originSite;
protected XSiteReplicateCommand(byte commandId, ByteString cacheName) {
super(cacheName);
this.commandId = commandId;
}
public CompletionStage<O> performInLocalSite(ComponentRegistry registry, boolean preserveOrder) {
//by default, the command is executed against BackupReceiver.
return performInLocalSite(registry.getBackupReceiver().running(), preserveOrder);
}
public abstract CompletionStage<O> performInLocalSite(BackupReceiver receiver, boolean preserveOrder);
public void setOriginSite(String originSite) {
this.originSite = originSite;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public byte getCommandId() {
return commandId;
}
}
| 1,221
| 25.565217
| 105
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/XSiteNamedCache.java
|
package org.infinispan.xsite;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.infinispan.util.ByteString;
/**
* Caches the site name {@link String} and {@link ByteString} instances.
*
* @since 14.0
*/
public final class XSiteNamedCache {
private static final Map<String, ByteString> CACHE = new ConcurrentHashMap<>(4);
private XSiteNamedCache() {
}
public static ByteString cachedByteString(String siteName) {
return CACHE.computeIfAbsent(siteName, ByteString::fromString);
}
public static String cachedString(String siteName) {
return cachedByteString(siteName).toString();
}
public static ByteString cachedByteString(ByteString siteName) {
ByteString old = CACHE.putIfAbsent(siteName.toString(), siteName);
return old == null ? siteName : old;
}
}
| 845
| 24.636364
| 83
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/CustomFailurePolicy.java
|
package org.infinispan.xsite;
/**
* Used for implementing custom policies in case of communication failures with a remote site. The handle methods are
* allowed to throw instances of {@link BackupFailureException} to signal that they want the intra-site operation to
* fail as well. If handle methods don't throw any exception then the operation will succeed in the local cluster. For
* convenience, there is a support implementation of this class: {@link AbstractCustomFailurePolicy}
* <p/>
* Lifecycle: the same instance is invoked during the lifecycle of a cache so it is allowed to hold state between
* invocations.
* <p/>
* Threadsafety: instances of this class might be invoked from different threads and they should be synchronized.
*
* @author Mircea Markus
* @see BackupFailureException
* @since 5.2
* @deprecated since 11.0. Use {@link org.infinispan.configuration.cache.CustomFailurePolicy} instead.
*/
@Deprecated
public interface CustomFailurePolicy<K, V> extends org.infinispan.configuration.cache.CustomFailurePolicy<K, V> {
}
| 1,059
| 45.086957
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/NoOpBackupSender.java
|
package org.infinispan.xsite;
import jakarta.transaction.Transaction;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.interceptors.InvocationStage;
import org.infinispan.interceptors.SyncInvocationStage;
import org.infinispan.transaction.impl.AbstractCacheTransaction;
/**
* A no-op implementation of {@link BackupSender}.
* <p>
* This class is used when cross-site replication is disabled.
*
* @author Pedro Ruivo
* @since 10.0
*/
@Scope(value = Scopes.NAMED_CACHE)
public class NoOpBackupSender implements BackupSender {
private static final NoOpBackupSender INSTANCE = new NoOpBackupSender();
private NoOpBackupSender() {
}
public static NoOpBackupSender getInstance() {
return INSTANCE;
}
@Override
public InvocationStage backupPrepare(PrepareCommand command, AbstractCacheTransaction cacheTransaction,
Transaction transaction) {
return SyncInvocationStage.completedNullStage();
}
@Override
public InvocationStage backupWrite(WriteCommand command, WriteCommand originalCommand) {
return SyncInvocationStage.completedNullStage();
}
@Override
public InvocationStage backupClear(ClearCommand command) {
return SyncInvocationStage.completedNullStage();
}
@Override
public InvocationStage backupCommit(CommitCommand command, Transaction transaction) {
return SyncInvocationStage.completedNullStage();
}
@Override
public InvocationStage backupRollback(RollbackCommand command, Transaction transaction) {
return SyncInvocationStage.completedNullStage();
}
@Override
public String toString() {
return "NoOpBackupSender{}";
}
}
| 1,981
| 28.58209
| 106
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/BackupReceiver.java
|
package org.infinispan.xsite;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.IracMetadata;
import org.infinispan.xsite.commands.XSiteStateTransferFinishReceiveCommand;
import org.infinispan.xsite.commands.XSiteStateTransferStartReceiveCommand;
import org.infinispan.xsite.statetransfer.XSiteStatePushCommand;
/**
* Component present on a backup site that manages the backup information and logic.
*
* @see ClusteredCacheBackupReceiver
* @author Mircea Markus
* @since 5.2
*/
@Scope(Scopes.NAMED_CACHE)
public interface BackupReceiver {
<O> CompletionStage<O> handleRemoteCommand(VisitableCommand command, boolean preserveOrder);
/**
* Updates the key with the value from a remote site.
* <p>
* If a conflict occurs, the update can be discarded.
*
* @param key The key to update.
* @param value The new value.
* @param metadata The new {@link Metadata}.
* @param iracMetadata The {@link IracMetadata} for conflict resolution.
* @return A {@link CompletionStage} that is completed when the update is apply in the cluster or is discarded.
*/
CompletionStage<Void> putKeyValue(Object key, Object value, Metadata metadata, IracMetadata iracMetadata);
/**
* Deletes the key.
* <p>
* This is a request from the remote site and the removal can be discarded if a conflict happens.
*
* @param key The key to delete.
* @param iracMetadata The {@link IracMetadata} for conflict resolution.
* @param expiration {@code true} if it is to remove an expired key.
* @return A {@link CompletionStage} that is completed when the key is deleted or it is discarded.
*/
CompletionStage<Void> removeKey(Object key, IracMetadata iracMetadata, boolean expiration);
/**
* Clears the cache.
* <p>
* This is not safe and it doesn't perform any conflict resolution.
*
* @return A {@link CompletionStage} that is completed when the cache is cleared.
*/
CompletionStage<Void> clearKeys();
/**
* Touches an entry and returns if it was able to or not.
* @param key the key of the entry to touch
* @return if the entry was touched
*/
CompletionStage<Boolean> touchEntry(Object key);
/**
* It handles starting the state transfer from a remote site. The command must be broadcast to the entire cluster in
* which the cache exists.
*/
CompletionStage<Void> handleStartReceivingStateTransfer(XSiteStateTransferStartReceiveCommand command);
/**
* It handles finishing the state transfer from a remote site. The command must be broadcast to the entire cluster in
* which the cache exists.
*/
CompletionStage<Void> handleEndReceivingStateTransfer(XSiteStateTransferFinishReceiveCommand command);
/**
* It handles the state transfer state from a remote site. It is possible to have a single node applying the state or
* forward the state to respective primary owners.
*/
CompletionStage<Void> handleStateTransferState(XSiteStatePushCommand cmd);
}
| 3,267
| 37.447059
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/notification/SiteStatusListener.java
|
package org.infinispan.xsite.notification;
/**
* A simple interface that is invoked by {@link org.infinispan.xsite.OfflineStatus} when a particular site changes its
* status to online/offline.
*
* @author Pedro Ruivo
* @since 9.0
*/
public interface SiteStatusListener {
default void siteOnline() {
}
default void siteOffline() {
}
}
| 356
| 17.789474
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/DiscardUpdateException.java
|
package org.infinispan.xsite.irac;
import org.infinispan.commons.CacheException;
/**
* For optimistic transactions, it signals the update from the remote site is not valid (old version or conflict
* resolution rejected it).
*
* @author Pedro Ruivo
* @since 11.0
*/
public class DiscardUpdateException extends CacheException {
private static final DiscardUpdateException CACHED_INSTANCE = new DiscardUpdateException("Update Discarded", null,
true, false);
public DiscardUpdateException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public static DiscardUpdateException getInstance() {
return CACHED_INSTANCE;
}
}
| 776
| 28.884615
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/IracXSiteBackup.java
|
package org.infinispan.xsite.irac;
import org.infinispan.util.ExponentialBackOff;
import org.infinispan.xsite.XSiteBackup;
import net.jcip.annotations.GuardedBy;
/**
* Extends {@link XSiteBackup} class with logging configuration.
*
* @since 14.0
*/
public class IracXSiteBackup extends XSiteBackup implements Runnable {
private final boolean logExceptions;
private final short index;
@GuardedBy("this")
private boolean backOffEnabled;
@GuardedBy("this")
private ExponentialBackOff backOff;
@GuardedBy("this")
private Runnable afterBackOff = () -> {};
public IracXSiteBackup(String siteName, boolean sync, long timeout, boolean logExceptions, short index) {
super(siteName, sync, timeout);
assert index >= 0;
this.logExceptions = logExceptions;
this.backOff = ExponentialBackOff.NO_OP;
this.backOffEnabled = false;
this.index = index;
}
public boolean logExceptions() {
return logExceptions;
}
public synchronized void enableBackOff() {
if (backOffEnabled) return;
backOffEnabled = true;
backOff.asyncBackOff().thenRun(this);
}
synchronized void useBackOff(ExponentialBackOff backOff, Runnable after) {
this.backOff = backOff;
this.afterBackOff = after;
}
public synchronized boolean isBackOffEnabled() {
return backOffEnabled;
}
synchronized void resetBackOff() {
backOffEnabled = false;
backOff.reset();
afterBackOff.run();
}
@Override
public synchronized void run() {
backOffEnabled = false;
afterBackOff.run();
}
@Override
public String toString() {
return super.toString() + (isBackOffEnabled() ? " [backoff-enabled]" : "");
}
public int siteIndex() {
return index;
}
}
| 1,796
| 23.283784
| 108
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/NoOpIracManager.java
|
package org.infinispan.xsite.irac;
import java.util.Collection;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.util.IntSet;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.metadata.impl.IracMetadata;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheTopology;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.xsite.statetransfer.XSiteState;
/**
* A no-op implementation of {@link IracManager} for cache without asynchronous remote site backups.
*
* @author Pedro Ruivo
* @since 11.0
*/
@Scope(Scopes.NAMED_CACHE)
public enum NoOpIracManager implements IracManager {
INSTANCE;
@Override
public void trackUpdatedKey(int segment, Object key, Object lockOwner) {
// no-op
}
@Override
public void trackExpiredKey(int segment, Object key, Object lockOwner) {
// no-op
}
@Override
public CompletionStage<Void> trackForStateTransfer(Collection<XSiteState> stateList) {
return CompletableFutures.completedNull();
}
@Override
public void trackClear(boolean sendClear) {
// no-op
}
@Override
public void removeState(IracManagerKeyInfo state) {
//no-op
}
@Override
public void onTopologyUpdate(CacheTopology oldCacheTopology, CacheTopology newCacheTopology) {
// no-op
}
@Override
public void requestState(Address requestor, IntSet segments) {
// no-op
}
@Override
public void receiveState(int segment, Object key, Object lockOwner, IracMetadata tombstone) {
// no-op
}
@Override
public CompletionStage<Boolean> checkAndTrackExpiration(Object key) {
return CompletableFutures.completedTrue();
}
@Override
public void incrementNumberOfDiscards() {
// no-op
}
@Override
public void incrementNumberOfConflictLocalWins() {
// no-op
}
@Override
public void incrementNumberOfConflictRemoteWins() {
// no-op
}
@Override
public void incrementNumberOfConflictMerged() {
// no-op
}
@Override
public boolean containsKey(Object key) {
return false;
}
}
| 2,234
| 22.526316
| 100
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/IracManagerStateTransferState.java
|
package org.infinispan.xsite.irac;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
/**
* A {@link IracManagerKeyState} implementation for state transfer requests,
*
* @since 14
*/
class IracManagerStateTransferState extends IracManagerKeyChangedState {
private final CompletableFuture<Void> completableFuture = new CompletableFuture<>();
public IracManagerStateTransferState(int segment, Object key, int numberOfBackups) {
super(segment, key, "state-transfer", false, numberOfBackups);
}
@Override
public boolean isStateTransfer() {
return true;
}
@Override
public boolean isDone() {
if (super.isDone()) {
completableFuture.complete(null);
return true;
}
return false;
}
@Override
public void discard() {
super.discard();
completableFuture.complete(null);
}
CompletionStage<Void> getCompletionStage() {
return completableFuture;
}
}
| 997
| 22.209302
| 87
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/IracManagerKeyInfo.java
|
package org.infinispan.xsite.irac;
import org.infinispan.commands.CommandInvocationId;
/**
* Basic information about a key stored in {@link IracManager}.
* <p>
* It includes the segment the owner of the key. The owner, in the {@link IracManager} context, is the {@link
* CommandInvocationId} or transaction which updated (or removed) the key.
*
* @since 14
*/
public interface IracManagerKeyInfo {
/**
* @return The key.
*/
Object getKey();
/**
* @return The owner who updated the key.
*/
Object getOwner();
/**
* @return The key's segment.
*/
int getSegment();
}
| 620
| 19.032258
| 110
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/IracClearResponseCollector.java
|
package org.infinispan.xsite.irac;
import java.lang.invoke.MethodHandles;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.util.concurrent.CountDownRunnable;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.status.DefaultTakeOfflineManager;
/**
* Used by asynchronous cross-site replication, it aggregates response from multiple sites and returns {@link
* IracBatchSendResult}.
* <p>
* This collector assumes the request is a {@link ClearCommand}, and never completes exceptionally.
*
* @author Pedro Ruivo
* @since 14.0
*/
public class IracClearResponseCollector implements Runnable {
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
private static final AtomicReferenceFieldUpdater<IracClearResponseCollector, IracBatchSendResult> RESULT_UPDATED = AtomicReferenceFieldUpdater.newUpdater(IracClearResponseCollector.class, IracBatchSendResult.class, "result");
private volatile IracBatchSendResult result = IracBatchSendResult.OK;
private final String cacheName;
private final CountDownRunnable countDownRunnable;
private final CompletableFuture<IracBatchSendResult> complete = new CompletableFuture<>();
public IracClearResponseCollector(String cacheName) {
this.cacheName = cacheName;
countDownRunnable = new CountDownRunnable(this);
}
public void dependsOn(IracXSiteBackup backup, CompletionStage<Void> request) {
countDownRunnable.increment();
request.whenComplete((bitSet, throwable) -> onResponse(backup, throwable));
}
public CompletionStage<IracBatchSendResult> freeze() {
countDownRunnable.freeze();
return complete;
}
public void forceBackOffAndRetry() {
RESULT_UPDATED.set(this, IracBatchSendResult.BACK_OFF_AND_RETRY);
}
private void onResponse(IracXSiteBackup backup, Throwable throwable) {
try {
boolean trace = log.isTraceEnabled();
if (throwable != null) {
if (DefaultTakeOfflineManager.isCommunicationError(throwable)) {
//in case of communication error, we need to back-off.
RESULT_UPDATED.set(this, IracBatchSendResult.BACK_OFF_AND_RETRY);
backup.enableBackOff();
} else {
//don't overwrite communication errors
RESULT_UPDATED.compareAndSet(this, IracBatchSendResult.OK, IracBatchSendResult.RETRY);
backup.resetBackOff();
}
if (backup.logExceptions()) {
log.warnXsiteBackupFailed(cacheName, backup.getSiteName(), throwable);
} else if (trace) {
log.tracef(throwable, "Encountered issues while backing clear command for cache %s to site %s", cacheName, backup.getSiteName());
}
} else if (trace) {
backup.resetBackOff();
if (log.isTraceEnabled())
log.tracef("Received clear response from %s (%d remaining)", backup.getSiteName(), countDownRunnable.missing());
}
} finally {
countDownRunnable.decrement();
}
}
@Override
public void run() {
// executed after all results are received (or timed out)!
complete.complete(result);
}
}
| 3,458
| 38.306818
| 228
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/IracManager.java
|
package org.infinispan.xsite.irac;
import java.util.Collection;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.irac.IracClearKeysCommand;
import org.infinispan.commons.util.IntSet;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.metadata.impl.IracMetadata;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheTopology;
import org.infinispan.xsite.statetransfer.XSiteState;
/**
* It manages the keys changed in the local cluster and sends to all asynchronous backup configured.
* <p>
* The {@code lockOwner} is the last command (or transaction) who updated the key. It is used to detect conflicting
* local updates while sending to the remote backups (sites).
*
* @author Pedro Ruivo
* @since 11.0
*/
@Scope(Scopes.NAMED_CACHE)
public interface IracManager {
/**
* Sets the {@code key} as changed by the {@code lockOwner}.
*
* @param segment The key's segment.
* @param key The key changed.
* @param lockOwner The lock owner who updated the key.
*/
void trackUpdatedKey(int segment, Object key, Object lockOwner);
/**
* Similar to {@link #trackUpdatedKey(int, Object, Object)} but it tracks expired keys instead.
* <p>
* Expired key need a different conflict resolution algorithm since remove expired should never win any conflict.
*
* @param segment The key's segment.
* @param key The key expired.
* @param lockOwner The lock owner who updated the key.
*/
void trackExpiredKey(int segment, Object key, Object lockOwner);
/**
* Tracks a set of keys to be sent to the remote site.
* <p>
* There is no much difference between this method and {@link #trackUpdatedKey(int, Object, Object)}. It just returns
* a {@link CompletionStage} to notify when the keys were sent. It is required by the cross-site state transfer
* protocol to know when it has finish.
*
* @param stateList The list of {@link XSiteState}.
* @return A {@link CompletionStage} which is completed when all the keys in {@code stateList} have been sent to the
* remote site.
*/
CompletionStage<Void> trackForStateTransfer(Collection<XSiteState> stateList);
/**
* Sets all keys as removed.
*
* @param sendClear if {@code true}, an {@link IracClearKeysCommand} is sent to the backup sites.
*/
void trackClear(boolean sendClear);
/**
* Removes the state associated to a single key.
*
* @param state The state to remove.
*/
void removeState(IracManagerKeyInfo state);
/**
* Notifies a topology changed.
*
* @param oldCacheTopology The old {@link CacheTopology}.
* @param newCacheTopology The new {@link CacheTopology}.
*/
void onTopologyUpdate(CacheTopology oldCacheTopology, CacheTopology newCacheTopology);
/**
* Requests the state stored in this instance for the given {@code segments}.
*
* @param requestor The requestor.
* @param segments The segments requested.
*/
void requestState(Address requestor, IntSet segments);
/**
* Receives the state related to the {@code key}.
*
* @param segment The key's segment.
* @param key The key modified.
* @param lockOwner The last {@code lockOwner}.
* @param tombstone The tombstone (can be {@code null})
*/
void receiveState(int segment, Object key, Object lockOwner, IracMetadata tombstone);
/**
* Checks if the given key is expired on all other sites. If the key is expired on all other sites this will return
* true
*
* @param key The key to check if it is expired or not
* @return Whether this key is expired on all other sites
*/
CompletionStage<Boolean> checkAndTrackExpiration(Object key);
/**
* Increase the count of discards.
*/
void incrementNumberOfDiscards();
/**
* Increase the count of conflicts if merge policy discard update (local value wins)
*/
void incrementNumberOfConflictLocalWins();
/**
* Increase the count of conflicts if merge policy applies update (remote value wins)
*/
void incrementNumberOfConflictRemoteWins();
/**
* Increase the count of conflicts if merge policy created a new value (merge remote value with local value)
*/
void incrementNumberOfConflictMerged();
/**
* Checks if the key is present.
* <p>
* A key is present as long as its latest update was not confirmed by all remote sites.
*
* @param key The key to check.
* @return {@code true} if the key is present.
*/
boolean containsKey(Object key);
}
| 4,691
| 32.755396
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/IracManagerKeyChangedState.java
|
package org.infinispan.xsite.irac;
import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater;
import static org.infinispan.commons.util.Util.toStr;
import java.lang.invoke.MethodHandles;
import java.util.BitSet;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import net.jcip.annotations.GuardedBy;
/**
* Default implementation of {@link IracManagerKeyState}.
*
* @author Pedro Ruivo
* @see IracManagerKeyState
* @since 14
*/
class IracManagerKeyChangedState implements IracManagerKeyState {
private static final AtomicReferenceFieldUpdater<IracManagerKeyChangedState, Status> STATUS_UPDATER = newUpdater(IracManagerKeyChangedState.class, Status.class, "status");
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
private final int segment;
private final Object key;
private final Object owner;
private final boolean expiration;
@GuardedBy("backupMissing")
private final BitSet backupMissing;
private volatile Status status = Status.READY;
public IracManagerKeyChangedState(int segment, Object key, Object owner, boolean expiration, int numberOfBackups) {
this.segment = segment;
this.key = Objects.requireNonNull(key);
this.owner = Objects.requireNonNull(owner);
this.expiration = expiration;
BitSet backupMissing = new BitSet(numberOfBackups);
backupMissing.set(0, numberOfBackups);
this.backupMissing = backupMissing;
}
@Override
public Object getKey() {
return key;
}
@Override
public Object getOwner() {
return owner;
}
@Override
public int getSegment() {
return segment;
}
@Override
public boolean isExpiration() {
return expiration;
}
@Override
public boolean isStateTransfer() {
return false;
}
@Override
public boolean canSend() {
if (log.isTraceEnabled()) {
log.tracef("[IRAC] State.setSending for key %s (status=%s)", toStr(key), status);
}
return STATUS_UPDATER.compareAndSet(this, Status.READY, Status.SENDING);
}
@Override
public void retry() {
if (log.isTraceEnabled()) {
log.tracef("[IRAC] State.setRetry for key %s (status=%s)", toStr(key), status);
}
STATUS_UPDATER.compareAndSet(this, Status.SENDING, Status.READY);
}
@Override
public boolean isDone() {
return STATUS_UPDATER.get(this) == Status.DONE;
}
@Override
public void discard() {
if (log.isTraceEnabled()) {
log.tracef("[IRAC] State.setDiscard for key %s (status=%s)", toStr(key), status);
}
STATUS_UPDATER.lazySet(this, Status.DONE);
}
@Override
public void successFor(IracXSiteBackup site) {
synchronized (backupMissing) {
backupMissing.clear(site.siteIndex());
if (backupMissing.isEmpty()) {
if (log.isTraceEnabled()) {
log.tracef("[IRAC] State.setCompleted for key %s (status=%s)", toStr(key), status);
}
STATUS_UPDATER.set(this, Status.DONE);
}
}
}
@Override
public boolean wasSuccessful(IracXSiteBackup site) {
synchronized (backupMissing) {
return !backupMissing.get(site.siteIndex());
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"segment=" + segment +
", key=" + toStr(key) +
", owner=" + owner +
", expiration=" + expiration +
", isStateTransfer=" + isStateTransfer() +
", status=" + status +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IracManagerKeyInfo)) return false;
IracManagerKeyInfo that = (IracManagerKeyInfo) o;
if (getSegment() != that.getSegment()) return false;
if (!getKey().equals(that.getKey())) return false;
return getOwner().equals(that.getOwner());
}
@Override
public int hashCode() {
int result = getSegment();
result = 31 * result + getKey().hashCode();
result = 31 * result + getOwner().hashCode();
return result;
}
private enum Status {
READY,
SENDING,
DONE
}
}
| 4,391
| 26.45
| 174
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/IracResponseCollector.java
|
package org.infinispan.xsite.irac;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import org.infinispan.commons.util.IntSet;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.status.DefaultTakeOfflineManager;
/**
* A response collector for an asynchronous cross site requests.
* <p>
* Multiple keys are batched together in a single requests. The remote site sends a {@link IntSet} back where if bit
* {@code n} is set, it means the {@code n}th key in the batch failed to be applied (example, lock failed to be
* acquired), and it needs to be retried.
* <p>
* If an {@link Exception} is received (example, timed-out waiting for the remote site ack), it assumes all keys in the
* batch aren't applied, and they are retried.
* <p>
* When the response (or exception) is received, {@link IracResponseCompleted#onResponseCompleted(IracBatchSendResult, Collection)} is invoked with the global result in {@link IracBatchSendResult} and a collection
* with all the successfully applied keys. Once the listener finishes execution, the {@link CompletableFuture} completes
* (completed value not relevant, and it is never completed exceptionally).
*
* @author Pedro Ruivo
* @since 12
*/
public class IracResponseCollector extends CompletableFuture<Void> implements BiConsumer<IntSet, Throwable> {
private static final Log log = LogFactory.getLog(IracResponseCollector.class);
private final IracXSiteBackup backup;
private final String cacheName;
private final Collection<IracManagerKeyState> batch;
private final IracResponseCompleted listener;
public IracResponseCollector(String cacheName, IracXSiteBackup backup, Collection<IracManagerKeyState> batch, IracResponseCompleted listener) {
this.cacheName = cacheName;
this.backup = backup;
this.batch = batch;
this.listener = listener;
}
@Override
public void accept(IntSet rspIntSet, Throwable throwable) {
boolean trace = log.isTraceEnabled();
if (throwable != null) {
IracBatchSendResult result;
if (DefaultTakeOfflineManager.isCommunicationError(throwable)) {
//in case of communication error, we need to back-off.
backup.enableBackOff();
result = IracBatchSendResult.BACK_OFF_AND_RETRY;
} else {
//don't overwrite communication errors
backup.resetBackOff();
result = IracBatchSendResult.RETRY;
}
if (backup.logExceptions()) {
log.warnXsiteBackupFailed(cacheName, backup.getSiteName(), throwable);
} else if (trace) {
log.tracef(throwable, "[IRAC] Encountered issues while backing up data for cache %s to site %s", cacheName, backup.getSiteName());
}
batch.forEach(IracManagerKeyState::retry);
notifyAndComplete(result, Collections.emptyList());
return;
}
if (trace) {
log.tracef("[IRAC] Received response from site %s for cache %s: %s", backup.getSiteName(), cacheName, rspIntSet);
}
backup.resetBackOff();
// Everything is good.
if (rspIntSet == null || rspIntSet.isEmpty()) {
for (IracManagerKeyState state : batch) {
state.successFor(backup);
}
notifyAndComplete(IracBatchSendResult.OK, batch);
return;
}
// Handle failed keys.
int index = 0;
List<IracManagerKeyState> successfulSent = new ArrayList<>(batch.size());
for (IracManagerKeyState state : batch) {
if (rspIntSet.contains(index++)) {
state.retry();
continue;
}
state.successFor(backup);
successfulSent.add(state);
}
notifyAndComplete(IracBatchSendResult.RETRY, successfulSent);
}
private void notifyAndComplete(IracBatchSendResult result, Collection<IracManagerKeyState> successfulSent) {
listener.onResponseCompleted(result, successfulSent);
complete(null);
}
@FunctionalInterface
public interface IracResponseCompleted {
void onResponseCompleted(IracBatchSendResult result, Collection<IracManagerKeyState> successfulSent);
}
}
| 4,356
| 38.252252
| 213
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/DefaultIracManager.java
|
package org.infinispan.xsite.irac;
import static org.infinispan.commons.util.IntSets.mutableCopyFrom;
import static org.infinispan.commons.util.IntSets.mutableEmptySet;
import static org.infinispan.remoting.transport.impl.VoidResponseCollector.ignoreLeavers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.PrimitiveIterator;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
import java.util.function.Predicate;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.irac.IracCleanupKeysCommand;
import org.infinispan.commands.irac.IracClearKeysCommand;
import org.infinispan.commands.irac.IracPutManyCommand;
import org.infinispan.commands.irac.IracStateResponseCommand;
import org.infinispan.commands.irac.IracTouchKeyCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.util.IntSet;
import org.infinispan.commons.util.Util;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.configuration.cache.BackupConfiguration;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.XSiteStateTransferConfiguration;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.container.versioning.irac.IracTombstoneManager;
import org.infinispan.distribution.DistributionInfo;
import org.infinispan.distribution.LocalizedCacheTopology;
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.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.interceptors.locking.ClusteringDependentLogic;
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.metadata.impl.IracMetadata;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.rpc.RpcOptions;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollector;
import org.infinispan.remoting.transport.XSiteResponse;
import org.infinispan.topology.CacheTopology;
import org.infinispan.util.ExponentialBackOff;
import org.infinispan.util.ExponentialBackOffImpl;
import org.infinispan.util.concurrent.AggregateCompletionStage;
import org.infinispan.util.concurrent.CompletionStages;
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.statetransfer.XSiteState;
import org.infinispan.xsite.status.SiteState;
import org.infinispan.xsite.status.TakeOfflineManager;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.CompletableSource;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Maybe;
/**
* Default implementation of {@link IracManager}.
* <p>
* It tracks the keys updated by this site and sends them, periodically, to the configured remote sites.
* <p>
* The primary owner coordinates everything. It sends the updates request to the remote site and coordinates the local
* site backup owners. After sending the updates to the remote site, it sends a cleanup request to the local site backup
* owners
* <p>
* The backup owners only keeps a backup list of the tracked keys.
* <p>
* On topology change, the updated keys list is replicate to the new owner(s). Also, if a segment is being transferred
* (i.e. the primary owner isn't a write and read owner), no updates to the remote site is sent since, most likely, the
* node doesn't have the most up-to-date value.
*
* @author Pedro Ruivo
* @since 11.0
*/
@MBean(objectName = "AsyncXSiteStatistics", description = "Statistics for Asynchronous cross-site replication")
@Scope(Scopes.NAMED_CACHE)
public class DefaultIracManager implements IracManager, JmxStatisticsExposer {
private static final Log log = LogFactory.getLog(DefaultIracManager.class);
private static final Predicate<Map.Entry<Object, IracManagerKeyState>> CLEAR_PREDICATE = e -> {
e.getValue().discard();
return true;
};
@Inject RpcManager rpcManager;
@Inject TakeOfflineManager takeOfflineManager;
@Inject ClusteringDependentLogic clusteringDependentLogic;
@Inject CommandsFactory commandsFactory;
@Inject IracTombstoneManager iracTombstoneManager;
private final Map<Object, IracManagerKeyState> updatedKeys;
private final Collection<IracXSiteBackup> asyncBackups;
private final IracExecutor iracExecutor;
private final int batchSize;
private volatile boolean hasClear;
private boolean statisticsEnabled;
private final LongAdder discardCounts = new LongAdder();
private final LongAdder conflictLocalWinsCount = new LongAdder();
private final LongAdder conflictRemoteWinsCount = new LongAdder();
private final LongAdder conflictMergedCount = new LongAdder();
public DefaultIracManager(Configuration config, Collection<IracXSiteBackup> backups) {
updatedKeys = new ConcurrentHashMap<>(64);
iracExecutor = new IracExecutor(this::run);
asyncBackups = backups;
statisticsEnabled = config.statistics().enabled();
batchSize = config.sites().asyncBackupsStream()
.map(BackupConfiguration::stateTransfer)
.mapToInt(XSiteStateTransferConfiguration::chunkSize)
.reduce(1, Integer::max);
}
@Inject
public void inject(@ComponentName(KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR) ScheduledExecutorService executorService,
@ComponentName(KnownComponentNames.BLOCKING_EXECUTOR) Executor blockingExecutor) {
// using the inject method here in order to decrease the class size
iracExecutor.setExecutor(blockingExecutor);
setBackOff(backup -> new ExponentialBackOffImpl(executorService));
}
@Start
public void start() {
hasClear = false;
}
@Override
public void trackUpdatedKey(int segment, Object key, Object lockOwner) {
trackState(new IracManagerKeyChangedState(segment, key, lockOwner, false, asyncBackups.size()));
}
@Override
public void trackExpiredKey(int segment, Object key, Object lockOwner) {
trackState(new IracManagerKeyChangedState(segment, key, lockOwner, true, asyncBackups.size()));
}
@Override
public CompletionStage<Void> trackForStateTransfer(Collection<XSiteState> stateList) {
if (log.isTraceEnabled()) {
log.tracef("[IRAC] Tracking state for state transfer: %s", Util.toStr(stateList));
}
// TODO we have way to send only to a single site, we can improve this code!
AggregateCompletionStage<Void> cf = CompletionStages.aggregateCompletionStage();
LocalizedCacheTopology topology = clusteringDependentLogic.getCacheTopology();
for (XSiteState state : stateList) {
int segment = topology.getSegment(state.key());
IracManagerStateTransferState iracState = new IracManagerStateTransferState(segment, state.key(), asyncBackups.size());
// if an update is in progress, we don't need to send the same value again.
if (updatedKeys.putIfAbsent(iracState.getKey(), iracState) == null) {
cf.dependsOn(iracState.getCompletionStage());
}
}
iracExecutor.run();
return cf.freeze();
}
@Override
public void trackClear(boolean sendClear) {
// only the originator sends the clear to the backup sites but all nodes need to clear the "updatedKeys" map
if (log.isTraceEnabled()) {
log.tracef("Tracking clear request. Replicate to backup sites? %s", sendClear);
}
hasClear = sendClear;
updatedKeys.entrySet().removeIf(CLEAR_PREDICATE);
if (sendClear) {
iracExecutor.run();
}
}
@Override
public void removeState(IracManagerKeyInfo state) {
removeStateFromLocal(state);
}
@Override
public void onTopologyUpdate(CacheTopology oldCacheTopology, CacheTopology newCacheTopology) {
if (log.isTraceEnabled()) {
log.trace("[IRAC] Topology Updated. Checking pending keys.");
}
Address local = rpcManager.getAddress();
if (!newCacheTopology.getMembers().contains(local)) {
// not in teh cache topology
return;
}
IntSet addedSegments = mutableCopyFrom(newCacheTopology.getWriteConsistentHash().getSegmentsForOwner(local));
if (oldCacheTopology.getMembers().contains(local)) {
addedSegments.removeAll(oldCacheTopology.getWriteConsistentHash().getSegmentsForOwner(local));
}
if (!addedSegments.isEmpty()) {
// request state from old primary owner
// and group new segments by primary owner
Map<Address, IntSet> primarySegments = new HashMap<>(newCacheTopology.getMembers().size());
int numOfSegments = clusteringDependentLogic.getCacheTopology().getNumSegments();
Function<Address, IntSet> intSetConstructor = address -> mutableEmptySet(numOfSegments);
for (PrimitiveIterator.OfInt it = addedSegments.iterator(); it.hasNext(); ) {
int segment = it.nextInt();
Address primary = newCacheTopology.getWriteConsistentHash().locatePrimaryOwnerForSegment(segment);
primarySegments.computeIfAbsent(primary, intSetConstructor).set(segment);
}
primarySegments.forEach(this::sendStateRequest);
}
// even if this node doesn't have any new segments, it may become the primary owner of some segments
// i.e. backup owner => primary owner "promotion".
// only trigger a round if we have pending updates.
if (!updatedKeys.isEmpty()) {
iracExecutor.run();
}
}
@Override
public void requestState(Address requestor, IntSet segments) {
transferStateTo(requestor, segments, updatedKeys.values());
iracTombstoneManager.sendStateTo(requestor, segments);
}
@Override
public void receiveState(int segment, Object key, Object lockOwner, IracMetadata tombstone) {
iracTombstoneManager.storeTombstoneIfAbsent(segment, key, tombstone);
updatedKeys.putIfAbsent(key, new IracManagerKeyChangedState(segment, key, lockOwner, false, asyncBackups.size()));
iracExecutor.run();
}
@Override
public CompletionStage<Boolean> checkAndTrackExpiration(Object key) {
if (log.isTraceEnabled()) {
log.tracef("Checking remote backup sites to see if key %s has been touched recently", key);
}
IracTouchKeyCommand command = commandsFactory.buildIracTouchCommand(key);
AtomicBoolean expired = new AtomicBoolean(true);
// TODO: technically this waits for all backups to respond - we can optimize so
// we return early
// if at least one backup says it isn't expired
AggregateCompletionStage<AtomicBoolean> collector = CompletionStages.aggregateCompletionStage(expired);
for (XSiteBackup backup : asyncBackups) {
if (takeOfflineManager.getSiteState(backup.getSiteName()) == SiteState.OFFLINE) {
if (log.isTraceEnabled()) {
log.tracef("Skipping %s as it is offline", backup.getSiteName());
}
continue; // backup is offline
}
if (log.isTraceEnabled()) {
log.tracef("Sending irac touch key command to %s", backup);
}
XSiteResponse<Boolean> response = sendToRemoteSite(backup, command);
collector.dependsOn(response.thenAccept(touched -> {
if (touched) {
if (log.isTraceEnabled()) {
log.tracef("Key %s was recently touched on a remote site %s", key, backup);
}
expired.set(false);
} else if (log.isTraceEnabled()) {
log.tracef("Entry %s was expired on remote site %s", key, backup);
}
}));
}
return collector.freeze().thenApply(AtomicBoolean::get);
}
// public for testing purposes
void transferStateTo(Address dst, IntSet segments, Collection<? extends IracManagerKeyState> stateCollection) {
if (log.isTraceEnabled()) {
log.tracef("Starting state transfer to %s. Segments=%s, %s keys to check", dst, segments, stateCollection.size());
}
//noinspection ResultOfMethodCallIgnored
Flowable.fromIterable(stateCollection)
.filter(s -> !s.isStateTransfer() && !s.isExpiration() && segments.contains(s.getSegment()))
.buffer(batchSize)
.concatMapCompletableDelayError(batch -> createAndSendBatch(dst, batch))
.subscribe(() -> {
if (log.isTraceEnabled()) {
log.tracef("State transfer to %s finished!", dst);
}
}, throwable -> {
if (log.isTraceEnabled()) {
log.tracef(throwable, "State transfer to %s failed!", dst);
}
});
}
private Completable createAndSendBatch(Address dst, Collection<? extends IracManagerKeyState> batch) {
if (log.isTraceEnabled()) {
log.tracef("Sending state response to %s. Batch=%s", dst, Util.toStr(batch));
}
RpcOptions rpcOptions = rpcManager.getSyncRpcOptions();
ResponseCollector<Void> rspCollector = ignoreLeavers();
IracStateResponseCommand cmd = commandsFactory.buildIracStateResponseCommand(batch.size());
for (IracManagerKeyState state : batch) {
IracMetadata tombstone = iracTombstoneManager.getTombstone(state.getKey());
cmd.add(state, tombstone);
}
return Completable.fromCompletionStage(rpcManager.invokeCommand(dst, cmd, rspCollector, rpcOptions)
.exceptionally(throwable -> {
if (log.isTraceEnabled()) {
log.tracef(throwable, "Batch sent to %s failed! Batch=%s", dst, Util.toStr(batch));
}
return null;
}));
}
private void trackState(IracManagerKeyState state) {
if (log.isTraceEnabled()) {
log.tracef("[IRAC] Tracking state %s", state);
}
IracManagerKeyState old = updatedKeys.put(state.getKey(), state);
if (old != null) {
// avoid sending the cleanup command to the cluster members
old.discard();
}
iracExecutor.run();
}
private CompletionStage<Void> run() {
// this run on a blocking thread!
if (log.isTraceEnabled()) {
log.tracef("[IRAC] Sending keys to remote site(s). Is clear? %s, keys: %s", hasClear, Util.toStr(updatedKeys.keySet()));
}
if (hasClear) {
// clear doesn't work very well with concurrent updates
// let's block all updates until the clear is applied everywhere
return sendClearUpdate();
}
return Flowable.fromIterable(updatedKeys.values())
.filter(this::canStateBeSent)
.concatMapMaybe(this::fetchEntry)
.buffer(batchSize)
.concatMapCompletable(this::sendUpdateBatch)
.onErrorComplete(t -> {
onUnexpectedThrowable(t);
return true;
})
.toCompletionStage(null);
}
public void setBackOff(Function<IracXSiteBackup, ExponentialBackOff> builder) {
asyncBackups.forEach(backup -> backup.useBackOff(builder.apply(backup), iracExecutor));
}
public boolean isEmpty() {
return updatedKeys.isEmpty();
}
private boolean canStateBeSent(IracManagerKeyState state) {
LocalizedCacheTopology cacheTopology = clusteringDependentLogic.getCacheTopology();
DistributionInfo dInfo = cacheTopology.getSegmentDistribution(state.getSegment());
//not the primary, we do not send the update to the remote site.
if (!dInfo.isWriteOwner() && !dInfo.isReadOwner()) {
// topology changed! we no longer have the key; just drop it
state.discard();
removeStateFromLocal(state);
return false;
}
return dInfo.isPrimary() && state.canSend();
}
private Maybe<IracStateData> fetchEntry(IracManagerKeyState state) {
return Maybe.fromCompletionStage(clusteringDependentLogic.getEntryLoader()
.loadAndStoreInDataContainer(state.getKey(), state.getSegment())
.thenApply(e -> new IracStateData(state, e, iracTombstoneManager.getTombstone(state.getKey())))
.exceptionally(throwable -> {
log.debugf(throwable, "[IRAC] Failed to load entry to send to remote sites. It will be retried. State=%s", state);
state.retry();
return null;
}));
}
private CompletableSource sendUpdateBatch(Collection<? extends IracStateData> batch) {
int size = batch.size();
boolean trace = log.isTraceEnabled();
if (trace) {
log.tracef("[IRAC] Batch ready to send remote site with %d keys", size);
}
if (size == 0) {
if (trace) {
log.trace("[IRAC] Batch not sent, reason: batch is empty");
}
return Completable.complete();
}
AggregateCompletionStage<Void> aggregation = CompletionStages.aggregateCompletionStage();
for (IracXSiteBackup backup: asyncBackups) {
if (backup.isBackOffEnabled()) {
for (IracStateData data : batch) {
data.state.retry();
}
continue;
}
IracPutManyCommand cmd = commandsFactory.buildIracPutManyCommand(size);
Collection<IracManagerKeyState> invalidState = new ArrayList<>(size);
Collection<IracManagerKeyState> validState = new ArrayList<>(size);
for (IracStateData data : batch) {
if (data.entry == null && data.tombstone == null) {
// there a concurrency issue where the entry and the tombstone do not exist (remove following by a put)
// the put will create a new state and the key will be sent to the remote sites
invalidState.add(data.state);
continue;
}
if (data.state.wasSuccessful(backup))
continue;
validState.add(data.state);
if (data.state.isExpiration()) {
cmd.addExpire(data.state.getKey(), data.tombstone);
} else if (data.entry == null) {
cmd.addRemove(data.state.getKey(), data.tombstone);
} else {
cmd.addUpdate(data.state.getKey(), data.entry.getValue(), data.entry.getMetadata(), data.entry.getInternalMetadata().iracMetadata());
}
}
if (!cmd.isEmpty()) {
IracResponseCollector rspCollector = new IracResponseCollector(commandsFactory.getCacheName(), backup, validState, this::onBatchResponse);
try {
CompletionStage<IntSet> cs;
if (takeOfflineManager.getSiteState(backup.getSiteName()) != SiteState.OFFLINE) {
cs = sendToRemoteSite(backup, cmd);
} else {
cs = CompletableFutures.completedNull();
}
// The result of this current Completable is not necessary, only the collector's result is.
cs.whenCompleteAsync(rspCollector, iracExecutor.executor());
aggregation.dependsOn(rspCollector);
} catch (Throwable throwable) {
// safety net; should never happen
// onUnexpectedThrowable() log the exception!
onUnexpectedThrowable(throwable);
for (IracStateData data : batch) {
data.state.retry();
}
}
}
if (!invalidState.isEmpty()) {
if (trace) {
log.tracef("[IRAC] Removing %d invalid state(s)", invalidState.size());
}
invalidState.forEach(IracManagerKeyState::discard);
removeStateFromCluster(invalidState);
}
}
return Completable.fromCompletionStage(aggregation.freeze());
}
private CompletionStage<Void> sendClearUpdate() {
// make sure the clear is replicated everywhere before sending the updates!
IracClearKeysCommand cmd = commandsFactory.buildIracClearKeysCommand();
IracClearResponseCollector collector = new IracClearResponseCollector(commandsFactory.getCacheName());
for (IracXSiteBackup backup : asyncBackups) {
if (takeOfflineManager.getSiteState(backup.getSiteName()) == SiteState.OFFLINE) {
continue; // backup is offline
}
if (backup.isBackOffEnabled()) {
collector.forceBackOffAndRetry();
continue;
}
collector.dependsOn(backup, sendToRemoteSite(backup, cmd));
}
return collector.freeze().handle(this::onClearCompleted);
}
private Void onClearCompleted(IracBatchSendResult result, Throwable throwable) {
if (throwable != null) {
onUnexpectedThrowable(throwable);
return null;
}
switch (result) {
case OK:
hasClear = false;
// fallthrough
case RETRY:
case BACK_OFF_AND_RETRY:
iracExecutor.run();
break;
default:
onUnexpectedThrowable(new IllegalStateException("Unknown result: " + result));
break;
}
return null;
}
private void onUnexpectedThrowable(Throwable throwable) {
// unlikely, retry
log.unexpectedErrorFromIrac(throwable);
iracExecutor.run();
}
private void sendStateRequest(Address primary, IntSet segments) {
CacheRpcCommand cmd = commandsFactory.buildIracRequestStateCommand(segments);
rpcManager.sendTo(primary, cmd, DeliverOrder.NONE);
}
private <O> XSiteResponse<O> sendToRemoteSite(XSiteBackup backup, XSiteReplicateCommand<O> cmd) {
XSiteResponse<O> rsp = rpcManager.invokeXSite(backup, cmd);
takeOfflineManager.registerRequest(rsp);
return rsp;
}
private void removeStateFromCluster(Collection<? extends IracManagerKeyInfo> stateToCleanup) {
if (stateToCleanup.isEmpty()) {
return;
}
if (log.isTraceEnabled()) {
log.tracef("[IRAC] Removing states from cluster: %s", Util.toStr(stateToCleanup));
}
IntSet segments = mutableEmptySet();
LocalizedCacheTopology cacheTopology = clusteringDependentLogic.getCacheTopology();
Set<Address> owners = new HashSet<>(cacheTopology.getMembers().size());
for (IracManagerKeyInfo state : stateToCleanup) {
if (segments.add(state.getSegment())) {
owners.addAll(cacheTopology.getSegmentDistribution(state.getSegment()).writeOwners());
}
}
if (!segments.isEmpty()) {
IracCleanupKeysCommand cmd = commandsFactory.buildIracCleanupKeyCommand(stateToCleanup);
rpcManager.sendToMany(owners, cmd, DeliverOrder.NONE);
stateToCleanup.forEach(this::removeStateFromLocal);
}
}
private void removeStateFromLocal(IracManagerKeyInfo state) {
//noinspection SuspiciousMethodCalls
boolean removed = updatedKeys.remove(state.getKey(), state);
if (log.isTraceEnabled()) {
log.tracef("[IRAC] State removed? %s, state=%s", removed, state);
}
}
private void onBatchResponse(IracBatchSendResult result, Collection<? extends IracManagerKeyState> successfulSent) {
if (log.isTraceEnabled()) {
log.tracef("[IRAC] Batch completed with %d keys applied. Global result=%s", successfulSent.size(), result);
}
Collection<IracManagerKeyState> doneKeys = new ArrayList<>(successfulSent.size());
switch (result) {
case OK:
for (IracManagerKeyState state : successfulSent) {
if (state.isDone()) {
doneKeys.add(state);
}
}
break;
case RETRY:
iracExecutor.run();
break;
case BACK_OFF_AND_RETRY:
// No-op, backup is already scheduled for retry.
break;
default:
onUnexpectedThrowable(new IllegalStateException("Unknown result: " + result));
break;
}
removeStateFromCluster(doneKeys);
}
@ManagedAttribute(description = "Number of keys that need to be sent to remote site(s)",
displayName = "Queue size",
measurementType = MeasurementType.DYNAMIC)
public int getQueueSize() {
return statisticsEnabled ? updatedKeys.size() : -1;
}
@ManagedAttribute(description = "Number of tombstones stored",
displayName = "Number of tombstones",
measurementType = MeasurementType.DYNAMIC)
public int getNumberOfTombstones() {
return statisticsEnabled ? iracTombstoneManager.size() : -1;
}
@ManagedAttribute(description = "The total number of conflicts between local and remote sites.",
displayName = "Number of conflicts",
measurementType = MeasurementType.TRENDSUP)
public long getNumberOfConflicts() {
return statisticsEnabled ? sumConflicts() : -1;
}
@ManagedAttribute(description = "The number of updates from remote sites discarded (duplicate or old update).",
displayName = "Number of discards",
measurementType = MeasurementType.TRENDSUP)
public long getNumberOfDiscards() {
return statisticsEnabled ? discardCounts.longValue() : -1;
}
@ManagedAttribute(description = "The number of conflicts where the merge policy discards the remote update.",
displayName = "Number of conflicts where local value is used",
measurementType = MeasurementType.TRENDSUP)
public long getNumberOfConflictsLocalWins() {
return statisticsEnabled ? conflictLocalWinsCount.longValue() : -1;
}
@ManagedAttribute(description = "The number of conflicts where the merge policy applies the remote update.",
displayName = "Number of conflicts where remote value is used",
measurementType = MeasurementType.TRENDSUP)
public long getNumberOfConflictsRemoteWins() {
return statisticsEnabled ? conflictRemoteWinsCount.longValue() : -1;
}
@ManagedAttribute(description = "Number of conflicts where the merge policy created a new entry.",
displayName = "Number of conflicts merged",
measurementType = MeasurementType.TRENDSUP)
public long getNumberOfConflictsMerged() {
return statisticsEnabled ? conflictMergedCount.longValue() : -1;
}
@ManagedAttribute(description = "Is tombstone cleanup task running?",
displayName = "Tombstone cleanup task running",
dataType = DataType.TRAIT)
public boolean isTombstoneCleanupTaskRunning() {
return iracTombstoneManager.isTaskRunning();
}
@ManagedAttribute(description = "Current delay in milliseconds between tombstone cleanup tasks",
displayName = "Delay between tombstone cleanup tasks",
measurementType = MeasurementType.DYNAMIC)
public long getTombstoneCleanupTaskCurrentDelay() {
return iracTombstoneManager.getCurrentDelayMillis();
}
@ManagedAttribute(description = "Enables or disables the gathering of statistics by this component", writable = true)
@Override
public boolean getStatisticsEnabled() {
return statisticsEnabled;
}
/**
* @param enabled whether gathering statistics for JMX are enabled.
*/
@Override
public void setStatisticsEnabled(boolean enabled) {
statisticsEnabled = enabled;
}
/**
* Resets statistics gathered. Is a no-op, and should be overridden if it is to be meaningful.
*/
@ManagedOperation(displayName = "Reset Statistics", description = "Resets statistics gathered by this component")
@Override
public void resetStatistics() {
discardCounts.reset();
conflictLocalWinsCount.reset();
conflictRemoteWinsCount.reset();
conflictMergedCount.reset();
}
private long sumConflicts() {
return conflictLocalWinsCount.longValue() + conflictRemoteWinsCount.longValue() + conflictMergedCount.longValue();
}
@Override
public void incrementNumberOfDiscards() {
discardCounts.increment();
}
@Override
public void incrementNumberOfConflictLocalWins() {
conflictLocalWinsCount.increment();
}
@Override
public void incrementNumberOfConflictRemoteWins() {
conflictRemoteWinsCount.increment();
}
@Override
public void incrementNumberOfConflictMerged() {
conflictMergedCount.increment();
}
@Override
public boolean containsKey(Object key) {
return updatedKeys.containsKey(key);
}
private static final class IracStateData {
final IracManagerKeyState state;
final InternalCacheEntry<Object, Object> entry;
final IracMetadata tombstone;
private IracStateData(IracManagerKeyState state, InternalCacheEntry<Object, Object> entry, IracMetadata tombstone) {
this.state = Objects.requireNonNull(state);
this.entry = entry;
this.tombstone = tombstone;
}
}
}
| 29,843
| 40.623431
| 150
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/IracExecutor.java
|
package org.infinispan.xsite.irac;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.WithinThreadExecutor;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Executes the "IRAC" sending task in a single thread.
* <p>
* This executor makes sure no more than one task is running at the same time. Also, it avoids "queueing" multiple tasks
* by queuing at most one. This is possible because the task does the same thing: iterator over pending updates and send
* them to the remote site.
*
* @author Pedro Ruivo
* @since 12
*/
public class IracExecutor implements Runnable {
private static final Log log = LogFactory.getLog(IracExecutor.class);
private final WrappedRunnable runnable;
private volatile CompletableFuture<Void> lastRunnable;
private volatile Executor executor;
final AtomicBoolean hasPendingRunnable;
public IracExecutor(Supplier<CompletionStage<Void>> runnable) {
this.runnable = new WrappedRunnable(Objects.requireNonNull(runnable));
this.lastRunnable = CompletableFutures.completedNull();
this.executor = new WithinThreadExecutor();
this.hasPendingRunnable = new AtomicBoolean();
}
public void setExecutor(Executor executor) {
this.executor = Objects.requireNonNull(executor);
}
/**
* Executes, in a new thread, or queues the task.
*/
@Override
public void run() {
if (hasPendingRunnable.compareAndSet(false, true)) {
//noinspection NonAtomicOperationOnVolatileField
lastRunnable = lastRunnable.thenComposeAsync(runnable, executor);
}
}
private class WrappedRunnable implements Function<Void, CompletionStage<Void>> {
private final Supplier<CompletionStage<Void>> runnable;
private WrappedRunnable(Supplier<CompletionStage<Void>> runnable) {
this.runnable = runnable;
}
/**
* Use by {@link CompletableFuture#thenComposeAsync(Function, Executor)}, executes the task and returns the {@link
* CompletionStage} return by it.
*
* @param unused Unused value.
* @return The {@link CompletionStage} from the task.
*/
@Override
public CompletionStage<Void> apply(Void unused) {
hasPendingRunnable.set(false);
try {
return runnable.get();
} catch (Throwable e) {
log.unexpectedErrorFromIrac(e);
return CompletableFutures.completedNull();
}
}
}
public Executor executor() {
return executor;
}
}
| 2,884
| 31.784091
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/IracManagerKeyState.java
|
package org.infinispan.xsite.irac;
/**
* Keeps a key state for {@link IracManager}.
* <p>
* There are 3 major information stored:
* <p>
* 1) If it is an expiration update. Expiration update needs special handling since, in case of conflict, it should be
* dropped.
* <p>
* 2) If it is a state transfer request. State transfer happens in batches in the sender and it needs to keep track of
* that ouside {@link IracManager} scope.
* <p>
* 3) Sending status. If the update has been sent to the remote site or not.
*
* @since 14
*/
interface IracManagerKeyState extends IracManagerKeyInfo {
/**
* @return {@code true} if it is an expiration update.
*/
boolean isExpiration();
/**
* @return {@code true} if it is a state transfer update.
*/
boolean isStateTransfer();
/**
* This method checks if the update can be sent to the remote site.
* <p>
* It returns {@link false} when the update is in progress, or it is discarded.
*
* @return {@code true} if the key's update needs to be sent to the remote site.
*/
boolean canSend();
/**
* Update this class status to be ready to send.
*/
void retry();
/**
* It returns {@code true} if the state is successfully applied in all online sites.
*
* @return {@code true} if the state is successfully applied.
*/
boolean isDone();
/**
* Discards this state.
*/
void discard();
/**
* Mark the given site as successfully received the current state.
*
* @param site: Site that received the state.
*/
void successFor(IracXSiteBackup site);
/**
* Check if given site received this state.
*
* @param site: Site to verify.
* @return true if successfully sent, false otherwise.
*/
boolean wasSuccessful(IracXSiteBackup site);
}
| 1,833
| 24.830986
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/IracManagerKeyInfoImpl.java
|
package org.infinispan.xsite.irac;
import static org.infinispan.commons.io.UnsignedNumeric.readUnsignedInt;
import static org.infinispan.commons.io.UnsignedNumeric.writeUnsignedInt;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Objects;
/**
* Default implementation of {@link IracManagerKeyInfo}.
*
* @author Pedro Ruivo
* @since 14
*/
public class IracManagerKeyInfoImpl implements IracManagerKeyInfo {
private final int segment;
private final Object key;
private final Object owner;
public IracManagerKeyInfoImpl(int segment, Object key, Object owner) {
this.segment = segment;
this.key = Objects.requireNonNull(key);
this.owner = Objects.requireNonNull(owner);
}
@Override
public Object getKey() {
return key;
}
@Override
public Object getOwner() {
return owner;
}
@Override
public int getSegment() {
return segment;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IracManagerKeyInfo)) return false;
IracManagerKeyInfo that = (IracManagerKeyInfo) o;
if (segment != that.getSegment()) return false;
if (!key.equals(that.getKey())) return false;
return owner.equals(that.getOwner());
}
@Override
public int hashCode() {
int result = segment;
result = 31 * result + key.hashCode();
result = 31 * result + owner.hashCode();
return result;
}
@Override
public String toString() {
return "IracManagerKeyInfoImpl{" + "segment=" + segment + ", key=" + key + ", owner=" + owner + '}';
}
public static void writeTo(ObjectOutput output, IracManagerKeyInfo keyInfo) throws IOException {
if (keyInfo == null) {
output.writeObject(null);
return;
}
output.writeObject(keyInfo.getKey());
writeUnsignedInt(output, keyInfo.getSegment());
output.writeObject(keyInfo.getOwner());
}
public static IracManagerKeyInfo readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
Object key = input.readObject();
if (key == null) {
return null;
}
return new IracManagerKeyInfoImpl(readUnsignedInt(input), key, input.readObject());
}
}
| 2,310
| 25.563218
| 108
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/irac/IracBatchSendResult.java
|
package org.infinispan.xsite.irac;
/**
* Global result of a multi key cross-site request.
*/
enum IracBatchSendResult {
/**
* Cross-site request applied successfully.
*/
OK,
/**
* Cross-site request failed (example: lock timeout). Retry sending.
*/
RETRY,
/**
* Cross-site request failed (network failure). Back-off for a while and retry.
*/
BACK_OFF_AND_RETRY
}
| 408
| 19.45
| 82
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/spi/DefaultXSiteEntryMergePolicy.java
|
package org.infinispan.xsite.spi;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
/**
* The default {@link XSiteEntryMergePolicy} implementation.
* <p>
* It uses the site's name to deterministically choose the winning entry. The site with the name lexicographically
* lowers wins.
*
* @author Pedro Ruivo
* @since 12.0
*/
public class DefaultXSiteEntryMergePolicy<K, V> implements XSiteEntryMergePolicy<K, V> {
private static final DefaultXSiteEntryMergePolicy<?, ?> INSTANCE = new DefaultXSiteEntryMergePolicy<>();
private DefaultXSiteEntryMergePolicy() {
}
public static <U, W> DefaultXSiteEntryMergePolicy<U, W> getInstance() {
//noinspection unchecked
return (DefaultXSiteEntryMergePolicy<U, W>) INSTANCE;
}
@Override
public CompletionStage<SiteEntry<V>> merge(K key, SiteEntry<V> localEntry, SiteEntry<V> remoteEntry) {
assert !localEntry.getSiteName().equals(remoteEntry.getSiteName());
return CompletableFuture.completedFuture(localEntry.getSiteName().compareTo(remoteEntry.getSiteName()) <= 0 ?
localEntry :
remoteEntry);
}
}
| 1,164
| 32.285714
| 115
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/spi/package-info.java
|
/**
* Cross-Site Replication conflict resolution.
*
* @api.public
*/
package org.infinispan.xsite.spi;
| 107
| 14.428571
| 46
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/spi/AlwaysRemoveXSiteEntryMergePolicy.java
|
package org.infinispan.xsite.spi;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
/**
* A {@link XSiteEntryMergePolicy} that removes the key if a conflict is detected.
*
* @author Pedro Ruivo
* @see XSiteEntryMergePolicy
* @since 12.0
*/
public class AlwaysRemoveXSiteEntryMergePolicy<K, V> implements XSiteEntryMergePolicy<K, V> {
private static final AlwaysRemoveXSiteEntryMergePolicy<?, ?> INSTANCE = new AlwaysRemoveXSiteEntryMergePolicy<>();
private AlwaysRemoveXSiteEntryMergePolicy() {
}
public static <T, U> AlwaysRemoveXSiteEntryMergePolicy<T, U> getInstance() {
//noinspection unchecked
return (AlwaysRemoveXSiteEntryMergePolicy<T, U>) INSTANCE;
}
private static String computeSiteName(SiteEntry<?> entry1, SiteEntry<?> entry2) {
return entry1.getSiteName().compareTo(entry2.getSiteName()) < 0 ?
entry1.getSiteName() :
entry2.getSiteName();
}
@Override
public CompletionStage<SiteEntry<V>> merge(K key, SiteEntry<V> localEntry, SiteEntry<V> remoteEntry) {
SiteEntry<V> resolved = new SiteEntry<>(computeSiteName(localEntry, remoteEntry), null, null);
return CompletableFuture.completedFuture(resolved);
}
}
| 1,260
| 33.081081
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/spi/SiteEntry.java
|
package org.infinispan.xsite.spi;
import java.util.Objects;
import org.infinispan.metadata.Metadata;
/**
* It stores the entry value and {@link Metadata} for a specific site.
*
* @author Pedro Ruivo
* @since 12.0
*/
public class SiteEntry<V> {
private final String siteName;
private final V value;
private final Metadata metadata;
public SiteEntry(String siteName, V value, Metadata metadata) {
this.siteName = Objects.requireNonNull(siteName, "Site Name must be non-null");
this.value = value;
this.metadata = metadata;
}
public String getSiteName() {
return siteName;
}
public V getValue() {
return value;
}
public Metadata getMetadata() {
return metadata;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SiteEntry<?> siteEntry = (SiteEntry<?>) o;
return siteName.equals(siteEntry.siteName) &&
Objects.equals(value, siteEntry.value) &&
Objects.equals(metadata, siteEntry.metadata);
}
@Override
public int hashCode() {
return Objects.hash(siteName, value, metadata);
}
@Override
public String toString() {
return "SiteEntry{" +
"siteName='" + siteName + '\'' +
", value=" + value +
", metadata=" + metadata +
'}';
}
}
| 1,462
| 21.507692
| 85
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/spi/XSiteMergePolicy.java
|
package org.infinispan.xsite.spi;
import java.util.Objects;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.SitesConfigurationBuilder;
/**
* An alias with the provided implementation of {@link XSiteEntryMergePolicy}.
* <p>
* To be used in {@link SitesConfigurationBuilder#mergePolicy(XSiteEntryMergePolicy)}
*
* @author Pedro Ruivo
* @see XSiteEntryMergePolicy
* @see PreferNonNullXSiteEntryMergePolicy
* @see PreferNullXSiteEntryMergePolicy
* @see AlwaysRemoveXSiteEntryMergePolicy
* @see DefaultXSiteEntryMergePolicy
* @since 12.0
*/
public enum XSiteMergePolicy implements XSiteEntryMergePolicy<Object, Object> {
/**
* Chooses the {@code non-null} value if available (write/remove conflict, write wins), otherwise uses the {@link
* #DEFAULT}.
*
* @see PreferNonNullXSiteEntryMergePolicy
*/
PREFER_NON_NULL {
@Override
public <K, V> XSiteEntryMergePolicy<K, V> getInstance() {
return PreferNonNullXSiteEntryMergePolicy.getInstance();
}
},
/**
* Chooses the {@code null} value if available (write/remove conflict, remove wins), otherwise uses the {@link
* #DEFAULT}.
*
* @see PreferNullXSiteEntryMergePolicy
*/
PREFER_NULL {
@Override
public <K, V> XSiteEntryMergePolicy<K, V> getInstance() {
return PreferNullXSiteEntryMergePolicy.getInstance();
}
},
/**
* Always remove the key if there is a conflict.
*
* @see AlwaysRemoveXSiteEntryMergePolicy
*/
ALWAYS_REMOVE {
@Override
public <K, V> XSiteEntryMergePolicy<K, V> getInstance() {
return AlwaysRemoveXSiteEntryMergePolicy.getInstance();
}
},
/**
* The default implementation chooses the entry with the lower lexicographically site name ({@link
* SiteEntry#getSiteName()}).
*
* @see DefaultXSiteEntryMergePolicy
*/
DEFAULT {
@Override
public <K, V> XSiteEntryMergePolicy<K, V> getInstance() {
return DefaultXSiteEntryMergePolicy.getInstance();
}
};
public static XSiteMergePolicy fromString(String str) {
for (XSiteMergePolicy mergePolicy : XSiteMergePolicy.values()) {
if (mergePolicy.name().equalsIgnoreCase(str)) {
return mergePolicy;
}
}
return null;
}
public static <K, V> XSiteMergePolicy fromInstance(XSiteEntryMergePolicy<K, V> r2) {
for (XSiteMergePolicy mergePolicy : XSiteMergePolicy.values()) {
XSiteEntryMergePolicy<K, V> r1 = mergePolicy.getInstance();
if (Objects.equals(r1, r2)) {
return mergePolicy;
}
}
return null;
}
public static <T, U> XSiteEntryMergePolicy<T, U> instanceFromString(String value, ClassLoader classLoader) {
XSiteMergePolicy mergePolicy = XSiteMergePolicy.fromString(value);
return mergePolicy == null ? Util.getInstance(value, classLoader) : mergePolicy.getInstance();
}
@Override
public CompletionStage<SiteEntry<Object>> merge(Object key, SiteEntry<Object> localEntry, SiteEntry<Object> remoteEntry) {
throw new UnsupportedOperationException();
}
public abstract <K, V> XSiteEntryMergePolicy<K, V> getInstance();
}
| 3,282
| 30.873786
| 125
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/spi/PreferNullXSiteEntryMergePolicy.java
|
package org.infinispan.xsite.spi;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
/**
* A {@link XSiteEntryMergePolicy} implementation that chooses a null entry.
* <p>
* If both entries are null (or non-null), then it uses the {@link DefaultXSiteEntryMergePolicy} to resolve the conflict.
*
* @author Pedro Ruivo
* @see DefaultXSiteEntryMergePolicy
* @since 12.0
*/
public class PreferNullXSiteEntryMergePolicy<K, V> implements XSiteEntryMergePolicy<K, V> {
private static final PreferNullXSiteEntryMergePolicy<?, ?> INSTANCE = new PreferNullXSiteEntryMergePolicy<>();
private PreferNullXSiteEntryMergePolicy() {
}
public static <T, U> PreferNullXSiteEntryMergePolicy<T, U> getInstance() {
//noinspection unchecked
return (PreferNullXSiteEntryMergePolicy<T, U>) INSTANCE;
}
@Override
public CompletionStage<SiteEntry<V>> merge(K key, SiteEntry<V> localEntry, SiteEntry<V> remoteEntry) {
boolean localIsNull = localEntry.getValue() == null;
boolean remoteIsNull = remoteEntry.getValue() == null;
if (localIsNull == remoteIsNull) { //both are null or bot are non-null
return DefaultXSiteEntryMergePolicy.<K, V>getInstance().merge(key, localEntry, remoteEntry);
} else if (localIsNull) {
return CompletableFuture.completedFuture(localEntry);
} else {
return CompletableFuture.completedFuture(remoteEntry);
}
}
}
| 1,466
| 35.675
| 121
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/spi/PreferNonNullXSiteEntryMergePolicy.java
|
package org.infinispan.xsite.spi;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
/**
* A {@link XSiteEntryMergePolicy} implementation that chooses a non-null entry.
* <p>
* If both entries are null (or non-null), then it uses the {@link DefaultXSiteEntryMergePolicy} to resolve the conflict.
*
* @author Pedro Ruivo
* @see DefaultXSiteEntryMergePolicy
* @since 12.0
*/
public class PreferNonNullXSiteEntryMergePolicy<K, V> implements XSiteEntryMergePolicy<K, V> {
private static final PreferNonNullXSiteEntryMergePolicy<?, ?> INSTANCE = new PreferNonNullXSiteEntryMergePolicy<>();
private PreferNonNullXSiteEntryMergePolicy() {
}
public static <T, U> PreferNonNullXSiteEntryMergePolicy<T, U> getInstance() {
//noinspection unchecked
return (PreferNonNullXSiteEntryMergePolicy<T, U>) INSTANCE;
}
@Override
public CompletionStage<SiteEntry<V>> merge(K key, SiteEntry<V> localEntry, SiteEntry<V> remoteEntry) {
boolean localIsNull = localEntry.getValue() == null;
boolean remoteIsNull = remoteEntry.getValue() == null;
if (localIsNull == remoteIsNull) { //both are null or bot are non-null
return DefaultXSiteEntryMergePolicy.<K, V>getInstance().merge(key, localEntry, remoteEntry);
} else if (localIsNull) {
return CompletableFuture.completedFuture(remoteEntry);
} else {
return CompletableFuture.completedFuture(localEntry);
}
}
}
| 1,488
| 36.225
| 121
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/spi/XSiteEntryMergePolicy.java
|
package org.infinispan.xsite.spi;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import org.infinispan.metadata.Metadata;
import org.infinispan.util.concurrent.BlockingManager;
/**
* An interface to resolve conflicts for asynchronous cross-site replication.
*
* @author Pedro Ruivo
* @since 12.0
*/
public interface XSiteEntryMergePolicy<K, V> {
/**
* Resolves conflicts for asynchronous cross-site replication.
* <p>
* When a conflict is detected (concurrent updates on the same key in different sites), this method is invoked with
* the local data and the remote site's data ({@link SiteEntry}). It includes the value and the {@link Metadata}
* associated.
* <p>
* The value and the {@link Metadata} may be {@code null}. If that is the case, it means the {@code key} doesn't
* exist (for {@code localEntry}) or it is a remove operation (for {@code remoteEntry}).
* <p>
* The returned {@link SiteEntry} must be equal independent of the order of the arguments (i.e. {@code resolve(k, s1,
* s2).equals(resolve(k, s2, s1))}) otherwise your date may be corrupted. It is allowed to return one of the
* arguments ({@code localEntry} or {@code remoteEntry}) and to create a new {@link SiteEntry} with a new value.
* <p>
* Note: if the return {@link SiteEntry#getValue()} is {@code null}, Infinispan will interpret it to remove the
* {@code key}.
* <p>
* Note2: This method shouldn't block (I/O or locks). If it needs to block, use a different thread and complete the
* {@link CompletionStage} with the result. We recommend using {@link BlockingManager#supplyBlocking(Supplier,
* Object)}.
*
* @param key The key that was updated concurrently.
* @param localEntry The local value and {@link Metadata} stored.
* @param remoteEntry The remote value and {@link Metadata} received.
* @return A {@link CompletionStage} with the {@link SiteEntry}.
*/
CompletionStage<SiteEntry<V>> merge(K key, SiteEntry<V> localEntry, SiteEntry<V> remoteEntry);
}
| 2,093
| 45.533333
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/XSiteStateConsumerImpl.java
|
package org.infinispan.xsite.statetransfer;
import static org.infinispan.context.Flag.IGNORE_RETURN_VALUES;
import static org.infinispan.context.Flag.IRAC_STATE;
import static org.infinispan.context.Flag.PUT_FOR_X_SITE_STATE_TRANSFER;
import static org.infinispan.context.Flag.SKIP_REMOTE_LOOKUP;
import static org.infinispan.context.Flag.SKIP_XSITE_BACKUP;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.tx.TransactionImpl;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.Configurations;
import org.infinispan.context.Flag;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.InvocationContextFactory;
import org.infinispan.context.impl.LocalTxInvocationContext;
import org.infinispan.context.impl.SingleKeyNonTxInvocationContext;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.statetransfer.CommitManager;
import org.infinispan.transaction.impl.LocalTransaction;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* It contains the logic needed to consume the state sent from other site.
*
* @author Pedro Ruivo
* @since 7.0
*/
@Scope(Scopes.NAMED_CACHE)
public class XSiteStateConsumerImpl implements XSiteStateConsumer {
private static final long STATE_TRANSFER_PUT_FLAGS = EnumUtil.bitSetOf(PUT_FOR_X_SITE_STATE_TRANSFER,
IGNORE_RETURN_VALUES, SKIP_REMOTE_LOOKUP,
SKIP_XSITE_BACKUP, IRAC_STATE);
private static final Log log = LogFactory.getLog(XSiteStateConsumerImpl.class);
private static final AtomicLong TX_ID_GENERATOR = new AtomicLong(0);
@Inject TransactionTable transactionTable;
@Inject InvocationContextFactory invocationContextFactory;
@Inject CommandsFactory commandsFactory;
@Inject AsyncInterceptorChain interceptorChain;
@Inject CommitManager commitManager;
@Inject KeyPartitioner keyPartitioner;
private final boolean isTxVersioned;
private final boolean isTransactional;
private final AtomicReference<String> sendingSite = new AtomicReference<>(null);
public XSiteStateConsumerImpl(Configuration configuration) {
this.isTxVersioned = Configurations.isTxVersioned(configuration);
this.isTransactional = configuration.transaction().transactionMode().isTransactional();
}
@Override
public void startStateTransfer(String sendingSite) {
log.debugf("Starting state transfer. Receiving from %s", sendingSite);
if (this.sendingSite.compareAndSet(null, sendingSite)) {
commitManager.startTrack(Flag.PUT_FOR_X_SITE_STATE_TRANSFER);
} else {
throw new CacheException("Already receiving state from " + this.sendingSite.get());
}
}
@Override
public void endStateTransfer(String sendingSite) {
if (log.isDebugEnabled()) {
log.debugf("Ending state transfer from %s", sendingSite);
}
String currentSendingSite = this.sendingSite.get();
if (sendingSite == null || sendingSite.equals(currentSendingSite)) {
this.sendingSite.set(null);
commitManager.stopTrack(PUT_FOR_X_SITE_STATE_TRANSFER);
} else {
if (log.isDebugEnabled()) {
log.debugf("Received an end request from a non-sender site. Expects %s but got %s", currentSendingSite,
sendingSite);
}
}
}
@Override
public void applyState(XSiteState[] chunk) throws Exception {
if (log.isDebugEnabled()) {
log.debugf("Received state: %s keys", chunk.length);
}
if (isTransactional) {
applyStateInTransaction(chunk);
} else {
applyStateInNonTransaction(chunk);
}
}
@Override
public String getSendingSiteName() {
return sendingSite.get();
}
private void applyStateInTransaction(XSiteState[] chunk) {
XSiteApplyStateTransaction tx = new XSiteApplyStateTransaction();
InvocationContext ctx = invocationContextFactory.createInvocationContext(tx, false);
assert ctx instanceof LocalTxInvocationContext;
LocalTransaction localTransaction = ((LocalTxInvocationContext) ctx).getCacheTransaction();
try {
localTransaction.setStateTransferFlag(PUT_FOR_X_SITE_STATE_TRANSFER);
for (XSiteState siteState : chunk) {
interceptorChain.invoke(ctx, createPut(siteState));
if (log.isTraceEnabled()) {
log.tracef("Successfully applied key'%s'", siteState);
}
}
invoke1PCPrepare(localTransaction);
if (log.isDebugEnabled()) {
log.debugf("Successfully applied state. %s keys inserted", chunk.length);
}
} catch (Exception e) {
log.unableToApplyXSiteState(e);
safeRollback(localTransaction);
throw e;
} finally {
transactionTable.removeLocalTransaction(localTransaction);
}
}
private void applyStateInNonTransaction(XSiteState[] chunk) {
SingleKeyNonTxInvocationContext ctx = (SingleKeyNonTxInvocationContext) invocationContextFactory
.createSingleKeyNonTxInvocationContext();
for (XSiteState siteState : chunk) {
PutKeyValueCommand command = createPut(siteState);
ctx.setLockOwner(command.getKeyLockOwner());
interceptorChain.invoke(ctx, command);
ctx.resetState(); //re-use same context. Old context is not longer needed
if (log.isTraceEnabled()) {
log.tracef("Successfully applied key'%s'", siteState);
}
}
if (log.isDebugEnabled()) {
log.debugf("Successfully applied state. %s keys inserted", chunk.length);
}
}
private PutKeyValueCommand createPut(XSiteState state) {
Object key = state.key();
PutKeyValueCommand cmd = commandsFactory.buildPutKeyValueCommand(key, state.value(),
keyPartitioner.getSegment(key), state.metadata(), STATE_TRANSFER_PUT_FLAGS);
cmd.setInternalMetadata(state.internalMetadata());
return cmd;
}
private void invoke1PCPrepare(LocalTransaction localTransaction) {
PrepareCommand prepareCommand;
if (isTxVersioned) {
prepareCommand = commandsFactory.buildVersionedPrepareCommand(localTransaction.getGlobalTransaction(),
localTransaction.getModifications(), true);
} else {
prepareCommand = commandsFactory.buildPrepareCommand(localTransaction.getGlobalTransaction(),
localTransaction.getModifications(), true);
}
LocalTxInvocationContext ctx = invocationContextFactory.createTxInvocationContext(localTransaction);
interceptorChain.invoke(ctx, prepareCommand);
}
private void safeRollback(LocalTransaction localTransaction) {
try {
RollbackCommand prepareCommand = commandsFactory.buildRollbackCommand(localTransaction.getGlobalTransaction());
LocalTxInvocationContext ctx = invocationContextFactory.createTxInvocationContext(localTransaction);
interceptorChain.invokeAsync(ctx, prepareCommand);
} catch (Exception e) {
//ignored!
if (log.isDebugEnabled()) {
log.debug("Error rollbacking transaction.", e);
}
}
}
private static class XSiteApplyStateTransaction extends TransactionImpl {
// Make it different from embedded txs (1)
// Make it different from embedded state transfer txs (2)
static final int FORMAT_ID = 3;
XSiteApplyStateTransaction() {
byte[] bytes = new byte[8];
Util.longToBytes(TX_ID_GENERATOR.incrementAndGet(), bytes, 0);
XidImpl xid = XidImpl.create(FORMAT_ID, bytes, bytes);
setXid(xid);
}
}
}
| 8,550
| 40.110577
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/AsyncProviderState.java
|
package org.infinispan.xsite.statetransfer;
import java.util.List;
import org.infinispan.configuration.cache.BackupConfiguration;
import org.infinispan.configuration.cache.XSiteStateTransferConfiguration;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.XSiteBackup;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.CompletableSource;
/**
* A {@link XSiteStateProviderState} for asynchronous cross-site replication state transfer (IRAC).
*
* @author Pedro Ruivo
* @since 12.0
*/
public class AsyncProviderState extends BaseXSiteStateProviderState<AsyncProviderState.AsyncOutboundTask> {
private static final Log log = LogFactory.getLog(AsyncProviderState.class);
private AsyncProviderState(XSiteBackup backup, XSiteStateTransferConfiguration configuration) {
super(backup, configuration);
}
public static AsyncProviderState create(BackupConfiguration config) {
XSiteBackup backup = new XSiteBackup(config.site(), true, config.stateTransfer().timeout());
return new AsyncProviderState(backup, config.stateTransfer());
}
@Override
public boolean isSync() {
return false;
}
@Override
AsyncOutboundTask createTask(Address originator, XSiteStateProvider provider) {
return new AsyncOutboundTask(originator, provider, this);
}
static class AsyncOutboundTask extends BaseXSiteStateProviderState.OutboundTask {
AsyncOutboundTask(Address coordinator, XSiteStateProvider provider, AsyncProviderState state) {
super(coordinator, provider, state);
}
@Override
public CompletableSource apply(List<XSiteState> xSiteStates) {
//Flowable#concatMapCompletable method
if (log.isDebugEnabled()) {
log.debugf("Sending chunk to site '%s'. Chunk has %s keys.", state.getBackup().getSiteName(), xSiteStates.size());
}
return Completable.fromCompletionStage(provider.getIracManager().trackForStateTransfer(xSiteStates));
}
}
}
| 2,123
| 33.819672
| 126
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/XSiteStateProvider.java
|
package org.infinispan.xsite.statetransfer;
import java.util.Collection;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.xsite.irac.IracManager;
/**
* It contains the logic to send state to another site.
*
* @author Pedro Ruivo
* @since 7.0
*/
public interface XSiteStateProvider {
/**
* It notifies this node to start sending state to the remote site. Also, it should keep information about which node
* requested the state transfer in order to send back the notification when finishes.
*
* @param siteName the remote site name.
* @param requestor the requestor.
* @param minTopologyId the topology id to wait before start sending the state.
*/
void startStateTransfer(String siteName, Address requestor, int minTopologyId);
/**
* It cancels the state transfer for the remote site. If no state transfer is available, it should do nothing.
*
* @param siteName the remote site name.
*/
void cancelStateTransfer(String siteName);
/**
* @return a site name collection with the sites in which this cache is sending state.
*/
Collection<String> getCurrentStateSending();
/**
* @return a site name collection with sites in which the coordinator is not in the {@code currentMembers}.
*/
Collection<String> getSitesMissingCoordinator(Collection<Address> currentMembers);
/**
* Notifies {@link XSiteStatePushTask} has completed the send.
*
* @param siteName The remote site name.
* @param origin The originator {@link Address}.
* @param statusOk {@code true} if completed successfully, {@code false} if it failed.
*/
void notifyStateTransferEnd(String siteName, Address origin, boolean statusOk);
/**
* Exposes {@link CommandsFactory} to {@link XSiteStatePushTask}.
*/
CommandsFactory getCommandsFactory();
/**
* Exposes {@link RpcManager} to {@link XSiteStatePushTask}.
*/
RpcManager getRpcManager();
/**
* Exposes {@link IracManager} to {@link XSiteStatePushTask}.
*/
IracManager getIracManager();
/**
* Exposes timeout {@link ScheduledExecutorService} to {@link XSiteStatePushTask}.
*/
ScheduledExecutorService getScheduledExecutorService();
/**
* Exposes non-blocking {@link Executor} to {@link XSiteStatePushTask}.
*/
Executor getExecutor();
}
| 2,564
| 30.666667
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/StatusResponseCollector.java
|
package org.infinispan.xsite.statetransfer;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ValidResponseCollector;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* Collects and merges all the {@link StateTransferStatus} from all nodes in the cluster.
*
* @author Pedro Ruivo
* @since 12
*/
class StatusResponseCollector extends ValidResponseCollector<Map<String, StateTransferStatus>> implements BiConsumer<String, StateTransferStatus> {
private final Map<String, StateTransferStatus> result = new HashMap<>();
private Exception exception;
@Override
public Map<String, StateTransferStatus> finish() {
if (exception != null) {
throw CompletableFutures.asCompletionException(exception);
}
return result;
}
@Override
protected Map<String, StateTransferStatus> addValidResponse(Address sender, ValidResponse response) {
//noinspection unchecked
Map<String, StateTransferStatus> rsp = (Map<String, StateTransferStatus>) response.getResponseValue();
rsp.forEach(this);
return null;
}
@Override
protected Map<String, StateTransferStatus> addTargetNotFound(Address sender) {
return null;
}
@Override
protected Map<String, StateTransferStatus> addException(Address sender, Exception exception) {
recordException(exception);
return null;
}
private void recordException(Exception e) {
if (this.exception == null) {
this.exception = e;
} else {
this.exception.addSuppressed(e);
}
}
@Override
public void accept(String site, StateTransferStatus status) {
result.merge(site, status, StateTransferStatus::merge);
}
}
| 1,894
| 29.079365
| 147
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/NoOpXSiteStateProvider.java
|
package org.infinispan.xsite.statetransfer;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.xsite.irac.IracManager;
/**
* A no-op implementation of {@link XSiteStateProvider}.
* <p>
* This class is used when cross-site replication is disabled.
*
* @author Pedro Ruivo
* @since 10.0
*/
@Scope(value = Scopes.NAMED_CACHE)
public class NoOpXSiteStateProvider implements XSiteStateProvider {
private static final NoOpXSiteStateProvider INSTANCE = new NoOpXSiteStateProvider();
private NoOpXSiteStateProvider() {
}
public static NoOpXSiteStateProvider getInstance() {
return INSTANCE;
}
@Override
public void startStateTransfer(String siteName, Address requestor, int minTopologyId) {
// no-op
}
@Override
public void cancelStateTransfer(String siteName) {
// no-op
}
@Override
public Collection<String> getCurrentStateSending() {
return Collections.emptyList();
}
@Override
public Collection<String> getSitesMissingCoordinator(Collection<Address> currentMembers) {
return Collections.emptyList();
}
@Override
public void notifyStateTransferEnd(String siteName, Address origin, boolean statusOk) {
//no-op
}
@Override
public CommandsFactory getCommandsFactory() {
return null;
}
@Override
public RpcManager getRpcManager() {
return null;
}
@Override
public IracManager getIracManager() {
return null;
}
@Override
public ScheduledExecutorService getScheduledExecutorService() {
return null;
}
@Override
public Executor getExecutor() {
return null;
}
@Override
public String toString() {
return "NoOpXSiteStateProvider{}";
}
}
| 2,093
| 22.266667
| 93
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/XSiteStateConsumer.java
|
package org.infinispan.xsite.statetransfer;
/**
* It contains the logic needed to consume the state sent from other site.
*
* @author Pedro Ruivo
* @since 7.0
*/
public interface XSiteStateConsumer {
/**
* It notifies the start of state transfer from other site.
*
* @param sendingSite the site name that will send the state.
* @throws org.infinispan.commons.CacheException if this node is received state from a different site name.
*/
void startStateTransfer(String sendingSite);
/**
* It notifies the end of state transfer from other site.
*
* @param sendingSite the site name that is sending the state.
*/
void endStateTransfer(String sendingSite);
/**
* It applies state from other site.
*
* @param chunk a chunk of keys
* @throws Exception if something go wrong while applying the state
*/
void applyState(XSiteState[] chunk) throws Exception;
/**
* @return the site name that is sending the state.
*/
String getSendingSiteName();
}
| 1,036
| 25.589744
| 110
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/XSiteState.java
|
package org.infinispan.xsite.statetransfer;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.commons.marshall.Ids;
import org.infinispan.commons.util.Util;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.persistence.spi.MarshallableEntry;
/**
* Represents the state of a single key to be sent to a backup site. It contains the only needed information, i.e., the
* key, current value and associated metadata.
*
* @author Pedro Ruivo
* @since 7.0
*/
public class XSiteState {
private final Object key;
private final Object value;
private final Metadata metadata;
private final PrivateMetadata internalMetadata;
private XSiteState(Object key, Object value, Metadata metadata, PrivateMetadata internalMetadata) {
this.key = key;
this.value = value;
this.metadata = metadata;
this.internalMetadata = internalMetadata;
}
public final Object key() {
return key;
}
public final Object value() {
return value;
}
public final Metadata metadata() {
return metadata;
}
public PrivateMetadata internalMetadata() {
return internalMetadata;
}
public static XSiteState fromDataContainer(InternalCacheEntry<?, ?> entry) {
return new XSiteState(entry.getKey(), entry.getValue(), entry.getMetadata(), entry.getInternalMetadata());
}
public static XSiteState fromCacheLoader(MarshallableEntry<?, ?> marshalledEntry) {
return new XSiteState(marshalledEntry.getKey(), marshalledEntry.getValue(), marshalledEntry.getMetadata(),
marshalledEntry.getInternalMetadata());
}
@Override
public String toString() {
return "XSiteState{" +
"key=" + Util.toStr(key) +
", value=" + Util.toStr(value) +
", metadata=" + metadata +
", internalMetadata=" + internalMetadata +
'}';
}
public static class XSiteStateExternalizer extends AbstractExternalizer<XSiteState> {
@Override
public Integer getId() {
return Ids.X_SITE_STATE;
}
@Override
public Set<Class<? extends XSiteState>> getTypeClasses() {
return Collections.singleton(XSiteState.class);
}
@Override
public void writeObject(ObjectOutput output, XSiteState object) throws IOException {
output.writeObject(object.key);
output.writeObject(object.value);
output.writeObject(object.metadata);
output.writeObject(object.internalMetadata);
}
@Override
public XSiteState readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new XSiteState(input.readObject(), input.readObject(), (Metadata) input.readObject(),
(PrivateMetadata) input.readObject());
}
}
}
| 3,076
| 29.77
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/SyncProviderState.java
|
package org.infinispan.xsite.statetransfer;
import static org.infinispan.util.logging.Log.XSITE;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import org.infinispan.configuration.cache.BackupConfiguration;
import org.infinispan.configuration.cache.XSiteStateTransferConfiguration;
import org.infinispan.remoting.transport.Address;
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 io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.CompletableSource;
import net.jcip.annotations.GuardedBy;
/**
* A {@link XSiteStateProviderState} for synchronous cross-site replication state transfer.
*
* @author Pedro Ruivo
* @since 12.0
*/
public class SyncProviderState extends BaseXSiteStateProviderState<SyncProviderState.SyncOutboundTask> {
private static final Log log = LogFactory.getLog(SyncProviderState.class);
private SyncProviderState(XSiteBackup backup, XSiteStateTransferConfiguration configuration) {
super(backup, configuration);
}
public static SyncProviderState create(BackupConfiguration config) {
XSiteBackup backup = new XSiteBackup(config.site(), true, config.stateTransfer().timeout());
return new SyncProviderState(backup, config.stateTransfer());
}
@Override
public boolean isSync() {
return true;
}
@Override
SyncOutboundTask createTask(Address originator, XSiteStateProvider provider) {
return new SyncOutboundTask(originator, provider, this);
}
static class SyncOutboundTask extends BaseXSiteStateProviderState.OutboundTask {
SyncOutboundTask(Address coordinator, XSiteStateProvider provider, SyncProviderState state) {
super(coordinator, provider, state);
}
@Override
public CompletableSource apply(List<XSiteState> xSiteStates) {
//Flowable#concatMapCompletable method
XSiteBackup backup = state.getBackup();
//TODO!? can we use xSiteStates directly instead of copying?
XSiteState[] privateBuffer = xSiteStates.toArray(new XSiteState[0]);
if (log.isDebugEnabled()) {
log.debugf("Sending chunk to site '%s'. Chunk has %s keys.", backup.getSiteName(), privateBuffer.length);
}
XSiteStatePushCommand command = provider.getCommandsFactory().buildXSiteStatePushCommand(privateBuffer, backup.getTimeout());
return Completable.fromCompletionStage(new CommandRetry(backup, command, provider, state.getWaitTimeMillis(), state.getMaxRetries()).send());
}
}
private static class CommandRetry extends CompletableFuture<Void> implements java.util.function.BiConsumer<Void, Throwable> {
private final XSiteBackup backup;
private final XSiteStatePushCommand cmd;
private final XSiteStateProvider provider;
private final long waitTimeMillis;
@GuardedBy("this")
private int maxRetries;
private CommandRetry(XSiteBackup backup, XSiteStatePushCommand cmd, XSiteStateProvider provider, long waitTimeMillis, int maxRetries) {
this.backup = backup;
this.cmd = cmd;
this.provider = provider;
this.waitTimeMillis = waitTimeMillis;
this.maxRetries = maxRetries;
}
//method to invoke from other class
CompletionStage<Void> send() {
doSend();
return this;
}
//used in scheduled executor, invokes doSend after the wait time.
void nonBlockingSend() {
provider.getExecutor().execute(this::doSend);
}
//actual send
private void doSend() {
provider.getRpcManager().invokeXSite(backup, cmd).whenComplete(this);
}
@Override
public void accept(Void o, Throwable throwable) {
//CompletionStage#whenComplete method, with the reply from remote site.
if (throwable != null) {
if (canRetry()) {
if (log.isTraceEnabled()) {
log.tracef("Command %s is going to be retried.", cmd);
}
if (waitTimeMillis <= 0) {
send();
} else {
provider.getScheduledExecutorService().schedule(this::nonBlockingSend, waitTimeMillis, TimeUnit.MILLISECONDS);
}
} else {
if (log.isTraceEnabled()) {
log.tracef("Command %s failed.", cmd);
}
Throwable cause = CompletableFutures.extractException(throwable);
XSITE.unableToSendXSiteState(backup.getSiteName(), cause);
completeExceptionally(cause);
}
} else {
if (log.isTraceEnabled()) {
log.tracef("Command %s successful.", cmd);
}
complete(null);
}
}
private synchronized boolean canRetry() {
return maxRetries-- > 0;
}
}
}
| 5,094
| 35.392857
| 150
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/XSiteStatePushCommand.java
|
package org.infinispan.xsite.statetransfer;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.xsite.BackupReceiver;
import org.infinispan.xsite.XSiteReplicateCommand;
/**
* Wraps the state to be sent to another site
*
* @author Pedro Ruivo
* @since 7.0
*/
public class XSiteStatePushCommand extends XSiteReplicateCommand<Void> {
public static final byte COMMAND_ID = 33;
private XSiteState[] chunk;
private long timeoutMillis;
public XSiteStatePushCommand(ByteString cacheName, XSiteState[] chunk, long timeoutMillis) {
super(COMMAND_ID, cacheName);
this.chunk = chunk;
this.timeoutMillis = timeoutMillis;
}
public XSiteStatePushCommand(ByteString cacheName) {
super(COMMAND_ID, cacheName);
}
@Override
public CompletionStage<Void> performInLocalSite(BackupReceiver receiver, boolean preserveOrder) {
assert !preserveOrder;
return receiver.handleStateTransferState(this);
}
public XSiteStatePushCommand() {
this(null);
}
public XSiteState[] getChunk() {
return chunk;
}
public long getTimeout() {
return timeoutMillis;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable {
XSiteStateConsumer stateConsumer = componentRegistry.getXSiteStateTransferManager().running().getStateConsumer();
stateConsumer.applyState(chunk);
return CompletableFutures.completedNull();
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeLong(timeoutMillis);
MarshallUtil.marshallArray(chunk, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
timeoutMillis = input.readLong();
chunk = MarshallUtil.unmarshallArray(input, XSiteState[]::new);
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public boolean canBlock() {
return true;
}
@Override
public String toString() {
return "XSiteStatePushCommand{" +
"cacheName=" + cacheName +
", timeout=" + timeoutMillis +
" (" + chunk.length + " keys)" +
'}';
}
}
| 2,625
| 25.795918
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/XSiteStatePushTask.java
|
package org.infinispan.xsite.statetransfer;
import java.util.concurrent.CompletionStage;
import io.reactivex.rxjava3.core.Flowable;
/**
* Sends local cluster state to remote site.
*
* @author Pedro Ruivo
* @since 12.0
*/
public interface XSiteStatePushTask {
/**
* Perform the state transfer with the state from {@link Flowable}.
* <p>
* The {@link Flowable} can only be iterated after {@code delayer} is completed.
*
* @param flowable The {@link Flowable} with the local cluster state.
* @param delayer A {@link CompletionStage} which is completed when it is allowed to start sending the state.
*/
void execute(Flowable<XSiteState> flowable, CompletionStage<Void> delayer);
}
| 721
| 27.88
| 113
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/XSiteStateTransferManagerImpl.java
|
package org.infinispan.xsite.statetransfer;
import static org.infinispan.remoting.transport.impl.VoidResponseCollector.ignoreLeavers;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
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.concurrent.ConcurrentMap;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.configuration.cache.BackupConfiguration;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.XSiteStateTransferMode;
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.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.rpc.RpcOptions;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.impl.VoidResponseCollector;
import org.infinispan.topology.CacheTopology;
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.util.logging.LogFactory;
import org.infinispan.xsite.XSiteReplicateCommand;
import org.infinispan.xsite.commands.XSiteAutoTransferStatusCommand;
import org.infinispan.xsite.commands.XSiteStateTransferCancelSendCommand;
import org.infinispan.xsite.commands.XSiteStateTransferClearStatusCommand;
import org.infinispan.xsite.commands.XSiteStateTransferFinishReceiveCommand;
import org.infinispan.xsite.commands.XSiteStateTransferRestartSendingCommand;
import org.infinispan.xsite.commands.XSiteStateTransferStartSendCommand;
import org.infinispan.xsite.response.AutoStateTransferResponse;
import org.infinispan.xsite.response.AutoStateTransferResponseCollector;
import org.infinispan.xsite.status.SiteState;
import org.infinispan.xsite.status.TakeOfflineManager;
/**
* {@link org.infinispan.xsite.statetransfer.XSiteStateTransferManager} implementation.
*
* @author Pedro Ruivo
* @since 7.0
*/
@Scope(Scopes.NAMED_CACHE)
public class XSiteStateTransferManagerImpl implements XSiteStateTransferManager {
private static final Log log = LogFactory.getLog(XSiteStateTransferManagerImpl.class);
private static final BiFunction<Throwable, String, Void> DEBUG_CANCEL_FAIL = (t, site) -> {
log.debugf(t, "Unable to cancel x-site state transfer for site %s", site);
return null;
};
@Inject RpcManager rpcManager;
@Inject CommandsFactory commandsFactory;
@Inject XSiteStateConsumer consumer;
@Inject XSiteStateProvider provider;
@Inject TakeOfflineManager takeOfflineManager;
@ComponentName(KnownComponentNames.CACHE_NAME)
@Inject String cacheName;
private final ConcurrentMap<String, RemoteSiteStatus> sites;
private volatile int currentTopologyId = -1;
//local cluster state transfer
private volatile boolean isStateTransferInProgress;
public XSiteStateTransferManagerImpl(Configuration configuration) {
sites = new ConcurrentHashMap<>();
for (BackupConfiguration bc : configuration.sites().allBackups()) {
sites.put(bc.site(), RemoteSiteStatus.fromConfiguration(bc));
}
}
@Start
public void start() {
sites.remove(rpcManager.getTransport().localSiteName());
}
@Override
public void notifyStatePushFinished(String siteName, Address node, boolean statusOk) {
RemoteSiteStatus status = sites.get(siteName);
assert status != null; // if this node is coordinating the state transfer, RemoteSiteStatus must exist
if (status.confirmStateTransfer(node, statusOk)) {
//state transfer finished. Cleanup local site & remote site
cancelStateTransferSending(siteName).exceptionally(t -> {
log.xsiteCancelSendFailed(t, siteName);
return null;
});
if (status.isSync()) {
//with async cross-site, the remote site doesn't have the concept of state transfer.
sendStateTransferFinishToRemoteSite(status).exceptionally(t -> {
log.xsiteCancelReceiveFailed(t, getLocalSite(), siteName);
return null;
});
}
}
}
@Override
public final void startPushState(String siteName) {
rpcManager.blocking(asyncStartPushState(validateSite(siteName)));
}
@Override
public List<String> getRunningStateTransfers() {
return sites.values().stream()
.filter(RemoteSiteStatus::isStateTransferInProgress)
.map(RemoteSiteStatus::getSiteName)
.collect(Collectors.toList());
}
@Override
public Map<String, StateTransferStatus> getStatus() {
return sites.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getStatus()));
}
@Override
public void clearStatus() {
sites.values().forEach(RemoteSiteStatus::clearStatus);
}
@Override
public void cancelPushState(String siteName) throws Throwable {
RemoteSiteStatus status = validateSite(siteName);
status.cancelStateTransfer();
AggregateCompletionStage<Void> rsp = CompletionStages.aggregateCompletionStage();
CompletionStage<Void> cancelSending = cancelStateTransferSending(siteName);
cancelSending.exceptionally(t -> {
log.xsiteCancelSendFailed(t, siteName);
return null;
});
rsp.dependsOn(cancelSending);
if (status.isSync()) {
//with async cross-site, the remote site doesn't have the concept of state transfer.
CompletionStage<Void> cancelReceiving = sendStateTransferFinishToRemoteSite(status);
cancelReceiving.exceptionally(t -> {
log.xsiteCancelReceiveFailed(t, getLocalSite(), siteName);
return null;
});
rsp.dependsOn(cancelReceiving);
}
rsp.freeze().toCompletableFuture().join();
}
@Override
public Map<String, StateTransferStatus> getClusterStatus() {
CacheRpcCommand command = commandsFactory.buildXSiteStateTransferStatusRequestCommand();
StatusResponseCollector collector = new StatusResponseCollector();
getStatus().forEach(collector); //add local status
return rpcManager.blocking(rpcManager.invokeCommandOnAll(command, collector, rpcManager.getSyncRpcOptions()));
}
@Override
public void clearClusterStatus() {
XSiteStateTransferClearStatusCommand cmd = commandsFactory.buildXSiteStateTransferClearStatusCommand();
CompletionStage<Void> rsp = rpcManager.invokeCommandOnAll(cmd, ignoreLeavers(), rpcManager.getSyncRpcOptions());
cmd.invokeLocal(this);
rpcManager.blocking(rsp);
}
@Override
public String getSendingSiteName() {
return consumer.getSendingSiteName();
}
@Override
public void cancelReceive(String siteName) {
XSiteStateTransferFinishReceiveCommand cmd = commandsFactory.buildXSiteStateTransferFinishReceiveCommand(siteName);
CompletionStage<Void> rsp = sendToLocalSite(cmd);
cmd.invokeLocal(consumer);
rpcManager.blocking(rsp);
}
@Override
public void becomeCoordinator(String siteName) {
startCoordinating(Collections.singleton(siteName), rpcManager.getMembers());
if (isStateTransferInProgress) {
//cancel all the x-site state transfer until the local site is rebalanced
doCancelSendingForRestart(siteName);
} else {
//it is balanced
if (log.isDebugEnabled()) {
log.debugf("Restarting x-site state transfer for site %s", siteName);
}
try {
rpcManager.blocking(restartStateTransferSending(siteName));
} catch (Exception e) {
log.failedToRestartXSiteStateTransfer(siteName, e);
}
}
}
@Override
public XSiteStateProvider getStateProvider() {
return provider;
}
@Override
public XSiteStateConsumer getStateConsumer() {
return consumer;
}
@Override
public void startAutomaticStateTransfer(Collection<String> sites) {
for (String site : sites) {
doAutomaticStateTransfer(site);
}
}
@Override
public XSiteStateTransferMode stateTransferMode(String site) {
RemoteSiteStatus status = sites.get(site);
return status == null ? XSiteStateTransferMode.MANUAL : status.stateTransferMode();
}
@Override
public boolean setAutomaticStateTransfer(String site, XSiteStateTransferMode mode) {
RemoteSiteStatus status = sites.get(site);
return status != null && status.setStateTransferMode(mode);
}
private void doAutomaticStateTransfer(String site) {
RemoteSiteStatus status = sites.get(site);
if (skipAutomaticStateTransferEnabled(site, status)) {
return;
}
isStateTransferRequired(status).whenComplete((proceed, throwable) -> {
if (throwable != null) {
Log.XSITE.unableToStartXSiteAutStateTransfer(cacheName, site, throwable);
} else if (proceed) {
bringSiteOnline(site).thenRun(() -> asyncStartPushState(status));
} else {
Log.XSITE.debugf("[%s] Cross-Site state transfer not required for site '%s'", cacheName, site);
}
});
}
private boolean skipAutomaticStateTransferEnabled(String site, RemoteSiteStatus status) {
if (status == null) {
Log.XSITE.debugf("[%s] Cross-Site automatic state transfer not started for site '%s'. It is not a backup location for this cache", cacheName, site);
return true;
}
if (status.isSync()) {
Log.XSITE.debugf("[%s] Cross-Site automatic state transfer not started for site '%s'. The backup strategy is set to SYNC", cacheName, site);
return true;
}
if (status.stateTransferMode() == XSiteStateTransferMode.MANUAL) {
Log.XSITE.debugf("[%s] Cross-Site automatic state transfer not started for site '%s'. Automatic state transfer is disabled", cacheName, site);
return true;
}
return false;
}
private CompletionStage<Boolean> isStateTransferRequired(RemoteSiteStatus status) {
final String site = status.getSiteName();
AutoStateTransferResponseCollector collector = new AutoStateTransferResponseCollector(takeOfflineManager.getSiteState(site) == SiteState.OFFLINE, status.stateTransferMode());
XSiteAutoTransferStatusCommand cmd = commandsFactory.buildXSiteAutoTransferStatusCommand(site);
return rpcManager.invokeCommandOnAll(cmd, collector, rpcManager.getSyncRpcOptions())
.thenApply(AutoStateTransferResponse::canDoAutomaticStateTransfer);
}
private CompletionStage<Void> bringSiteOnline(String site) {
CacheRpcCommand cmd = commandsFactory.buildXSiteBringOnlineCommand(site);
CompletionStage<Void> rsp = rpcManager.invokeCommandOnAll(cmd, VoidResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions());
takeOfflineManager.bringSiteOnline(site);
return rsp;
}
@Override
public void onTopologyUpdated(CacheTopology cacheTopology, boolean stateTransferInProgress) {
int topologyId = cacheTopology.getTopologyId();
if (log.isDebugEnabled()) {
log.debugf("Topology change. TopologyId: %s. State transfer in progress? %s", Integer.toString(topologyId), stateTransferInProgress);
}
this.currentTopologyId = topologyId;
this.isStateTransferInProgress = stateTransferInProgress;
final List<Address> newMembers = cacheTopology.getMembers();
final boolean amINewCoordinator = newMembers.get(0).equals(rpcManager.getAddress());
Collection<String> missingCoordinatorSites = provider.getSitesMissingCoordinator(new HashSet<>(newMembers));
if (amINewCoordinator) {
startCoordinating(missingCoordinatorSites, newMembers);
}
if (stateTransferInProgress) {
//cancel all the x-site state transfer until the local site is rebalanced
sites.values().stream()
.filter(RemoteSiteStatus::isStateTransferInProgress)
.map(RemoteSiteStatus::getSiteName)
.forEach(this::doCancelSendingForRestart);
} else {
//it is balanced
for (RemoteSiteStatus status : sites.values()) {
if (!status.restartStateTransfer(newMembers)) {
continue;
}
String siteName = status.getSiteName();
if (log.isDebugEnabled()) {
log.debugf("Topology change detected! Restarting x-site state transfer for site %s", siteName);
}
try {
restartStateTransferSending(siteName);
} catch (Exception e) {
log.failedToRestartXSiteStateTransfer(siteName, e);
}
}
}
}
private CompletionStage<Void> asyncStartPushState(RemoteSiteStatus status) {
String siteName = status.getSiteName();
if (!status.startStateTransfer(rpcManager.getMembers())) {
CompletableFuture.failedFuture(log.xsiteStateTransferAlreadyInProgress(siteName));
}
CompletionStage<Void> rsp = null;
if (status.isSync()) {
//with async cross-site, the remote site doesn't have the concept of state transfer.
//the remote site receives normal updates and apply conflict resolution if required.
XSiteReplicateCommand<Void> remoteSiteCommand = commandsFactory.buildXSiteStateTransferStartReceiveCommand();
rsp = rpcManager.invokeXSite(status.getBackup(), remoteSiteCommand);
}
if (isStateTransferInProgress) {
if (log.isDebugEnabled()) {
log.debugf("Not starting state transfer to site '%s' while rebalance in progress. Waiting until it is finished!",
siteName);
}
return rsp == null ? CompletableFutures.completedNull() : rsp;
}
if (rsp == null) {
return asyncStartLocalSend(status);
} else {
return rsp.thenCompose(o -> asyncStartLocalSend(status));
}
}
private CompletionStage<Void> asyncStartLocalSend(RemoteSiteStatus status) {
XSiteStateTransferStartSendCommand cmd = commandsFactory.buildXSiteStateTransferStartSendCommand(status.getSiteName(), currentTopologyId);
CompletionStage<Void> rsp = sendToLocalSite(cmd);
cmd.setOrigin(rpcManager.getAddress());
cmd.invokeLocal(provider);
rsp.exceptionally(throwable -> {
handleFailure(status, throwable);
return null;
});
return rsp;
}
private String getLocalSite() {
return rpcManager.getTransport().localSiteName();
}
private void doCancelSendingForRestart(String siteName) {
try {
if (log.isDebugEnabled()) {
log.debugf("Canceling x-site state transfer for site %s", siteName);
}
CompletionStage<Void> rsp = cancelStateTransferSending(siteName);
if (log.isDebugEnabled()) {
rsp.exceptionally(t -> DEBUG_CANCEL_FAIL.apply(t, siteName));
}
} catch (Exception e) {
//not serious... we are going to restart it anyway
if (log.isDebugEnabled()) {
DEBUG_CANCEL_FAIL.apply(e, siteName);
}
}
}
private RemoteSiteStatus validateSite(String siteName) throws NullPointerException, IllegalArgumentException {
RemoteSiteStatus status = sites.get(Objects.requireNonNull(siteName, "Site name cannot be null."));
if (status == null) {
throw log.siteNotFound(siteName);
}
return status;
}
private CompletionStage<Void> cancelStateTransferSending(String siteName) {
XSiteStateTransferCancelSendCommand cmd = commandsFactory.buildXSiteStateTransferCancelSendCommand(siteName);
CompletionStage<Void> rsp = sendToLocalSite(cmd);
cmd.invokeLocal(provider);
return rsp;
}
private CompletionStage<Void> restartStateTransferSending(String siteName) {
int topologyId = currentTopologyId;
XSiteStateTransferRestartSendingCommand cmd = commandsFactory.buildXSiteStateTransferRestartSendingCommand(siteName, topologyId);
CompletionStage<Void> rsp = sendToLocalSite(cmd);
cmd.setOrigin(rpcManager.getAddress());
cmd.invokeLocal(provider);
return rsp;
}
private void startCoordinating(Collection<String> sitesName, Collection<Address> members) {
if (log.isDebugEnabled()) {
log.debugf("Becoming the x-site state transfer coordinator for %s", sitesName);
}
for (String siteName : sitesName) {
RemoteSiteStatus status = sites.get(siteName);
assert status != null;
status.startStateTransfer(members);
}
}
private void handleFailure(RemoteSiteStatus siteStatus, Throwable throwable) {
final String siteName = siteStatus.getSiteName();
if (log.isDebugEnabled()) {
log.debugf(throwable, "Handle start state transfer failure to %s", siteName);
}
siteStatus.failStateTransfer();
CompletionStage<Void> rsp = cancelStateTransferSending(siteName);
if (log.isDebugEnabled()) {
rsp.exceptionally(t -> DEBUG_CANCEL_FAIL.apply(t, siteName));
}
if (!siteStatus.isSync()) {
return;
}
//with async cross-site, the remote site doesn't have the concept of state transfer.
rsp = sendStateTransferFinishToRemoteSite(siteStatus);
if (log.isDebugEnabled()) {
rsp.exceptionally(t -> {
log.debugf(t, "Exception while cancel receiving in remote site %s", siteName);
return null;
});
}
}
private CompletionStage<Void> sendToLocalSite(CacheRpcCommand command) {
return rpcManager.invokeCommandOnAll(command, ignoreLeavers(), fifoSyncRpcOptions());
}
private CompletionStage<Void> sendStateTransferFinishToRemoteSite(RemoteSiteStatus status) {
return rpcManager.invokeXSite(status.getBackup(), commandsFactory.buildXSiteStateTransferFinishReceiveCommand(null));
}
private RpcOptions fifoSyncRpcOptions() {
RpcOptions sync = rpcManager.getSyncRpcOptions();
return new RpcOptions(DeliverOrder.PER_SENDER, sync.timeout(), sync.timeUnit());
}
}
| 18,761
| 39.61039
| 180
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/NoOpXSiteStateTransferManager.java
|
package org.infinispan.xsite.statetransfer;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.infinispan.configuration.cache.XSiteStateTransferMode;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheTopology;
/**
* A no-op implementation of {@link XSiteStateTransferManager}.
*
* This instance is used when cross-site replication is disabled.
*
* @author Pedro Ruivo
* @since 8.0
*/
@Scope(value = Scopes.NAMED_CACHE)
public class NoOpXSiteStateTransferManager implements XSiteStateTransferManager {
@Inject XSiteStateConsumer consumer;
public NoOpXSiteStateTransferManager() {
}
@Override
public void notifyStatePushFinished(String siteName, Address node, boolean statusOk) {
// no-op
}
@Override
public void startPushState(String siteName) {
// no-op
}
@Override
public void cancelPushState(String siteName) {
// no-op
}
@Override
public List<String> getRunningStateTransfers() {
return Collections.emptyList();
}
@Override
public Map<String, StateTransferStatus> getStatus() {
return Collections.emptyMap();
}
@Override
public void clearStatus() {
// no-op
}
@Override
public Map<String, StateTransferStatus> getClusterStatus() {
return Collections.emptyMap();
}
@Override
public void clearClusterStatus() {
// no-op
}
@Override
public String getSendingSiteName() {
return null;
}
@Override
public void cancelReceive(String siteName) {
// no-op
}
@Override
public void becomeCoordinator(String siteName) {
// no-op
}
@Override
public void onTopologyUpdated(CacheTopology cacheTopology, boolean stateTransferInProgress) {
//no-op
}
@Override
public XSiteStateProvider getStateProvider() {
return NoOpXSiteStateProvider.getInstance();
}
@Override
public XSiteStateConsumer getStateConsumer() {
//although xsite is disabled, this class is still able to receive state from a remote site.
return consumer;
}
@Override
public void startAutomaticStateTransfer(Collection<String> sites) {
//no-op
}
@Override
public XSiteStateTransferMode stateTransferMode(String site) {
return XSiteStateTransferMode.MANUAL;
}
@Override
public boolean setAutomaticStateTransfer(String site, XSiteStateTransferMode mode) {
return false;
}
@Override
public String toString() {
return "NoOpXSiteStateTransferManager{}";
}
}
| 2,762
| 21.647541
| 97
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/StateTransferStatus.java
|
package org.infinispan.xsite.statetransfer;
/**
* Cross-site state transfer status.
*
* @author Pedro Ruivo
* @since 12
*/
public enum StateTransferStatus {
IDLE,
SENDING,
SEND_OK,
SEND_FAILED,
SEND_CANCELED;
public static StateTransferStatus merge(StateTransferStatus one, StateTransferStatus two) {
switch (one) {
case IDLE:
return two;
case SENDING:
return two == IDLE ? one : two;
case SEND_OK:
switch (two) {
case IDLE:
case SENDING:
return one;
default:
return two;
}
case SEND_FAILED:
switch (two) {
case IDLE:
case SENDING:
case SEND_OK:
case SEND_CANCELED:
return one;
default:
return two;
}
case SEND_CANCELED:
switch (two) {
case IDLE:
case SENDING:
case SEND_OK:
return one;
default:
return two;
}
default:
throw new IllegalStateException();
}
}
public static String toText(StateTransferStatus status) {
switch (status) {
case IDLE:
return "IDLE";
case SENDING:
return XSiteStateTransferManager.STATUS_SENDING;
case SEND_OK:
return XSiteStateTransferManager.STATUS_OK;
case SEND_FAILED:
return XSiteStateTransferManager.STATUS_ERROR;
case SEND_CANCELED:
return XSiteStateTransferManager.STATUS_CANCELED;
default:
throw new IllegalStateException();
}
}
}
| 1,801
| 24.380282
| 94
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/XSiteStateTransferManager.java
|
package org.infinispan.xsite.statetransfer;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.infinispan.configuration.cache.XSiteStateTransferMode;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheTopology;
/**
* It manages the state transfer between sites.
*
* @author Pedro Ruivo
* @since 7.0
*/
public interface XSiteStateTransferManager {
String STATUS_OK = "OK";
String STATUS_ERROR = "ERROR";
String STATUS_SENDING = "SENDING";
String STATUS_CANCELED = "CANCELED";
/**
* It receives the notifications from local site when some node finishes pushing the state to the remote site.
*
* @param siteName the remote site name
* @param node the {@link Address} from the node that finishes.
* @param statusOk {@code true} if no error or exception occurred during the state transfer.
*/
void notifyStatePushFinished(String siteName, Address node, boolean statusOk);
/**
* It notifies all nodes from local site to start transfer the state to the remote site.
*
* @param siteName the remote site name
* @throws Throwable If some unexpected behavior occurs.
*/
void startPushState(String siteName) throws Throwable;
/**
* It cancels a running state transfer.
*
* @param siteName the site name to where the state is being sent.
* @throws Throwable if some exception occurs during the remote invocation with the local cluster or remote site.
*/
void cancelPushState(String siteName) throws Throwable;
/**
* @return a list of site names in which this cache is pushing state.
*/
List<String> getRunningStateTransfers();
/**
* @return the completed state transfer status for which this node is the coordinator.
*/
Map<String, StateTransferStatus> getStatus();
/**
* Clears the completed state transfer status.
*/
void clearStatus();
/**
* @return the completed state transfer status from all the coordinators in the cluster.
*/
Map<String, StateTransferStatus> getClusterStatus();
/**
* Clears the completed state transfer status in all the cluster.
*/
void clearClusterStatus();
/**
* @return {@code null} if this node is not receiving state or the site name which is sending the state.
*/
String getSendingSiteName();
/**
* Sets the cluster to normal state.
* <p/>
* The main use for this method is when the link between the sites is broken and the receiver site keeps it state
* transfer state forever.
*
* @param siteName the site name which is sending the state.
* @throws Exception if some exception occurs during the remote invocation.
*/
void cancelReceive(String siteName) throws Exception;
/**
* Makes this node the coordinator for the state transfer to the site name.
* <p/>
* This method is invoked when the coordinator dies and this node receives a late start state transfer request.
*
* @param siteName the site name.
*/
void becomeCoordinator(String siteName);
/**
* Notifies {@link XSiteStateTransferManager} that a new {@link CacheTopology} is installed and if the local cluster
* state transfer is in progress (or about to start)
*
* @param cacheTopology The new {@link CacheTopology}.
* @param stateTransferInProgress {@code true} if the state transfer is in progress or starting.
*/
void onTopologyUpdated(CacheTopology cacheTopology, boolean stateTransferInProgress);
/**
* @return The {@link XSiteStateProvider} instance.
*/
XSiteStateProvider getStateProvider();
/**
* @return The {@link XSiteStateConsumer} instance.
*/
XSiteStateConsumer getStateConsumer();
/**
* Starts cross-site state transfer for the remote sites, if required.
*
* @param sites The remote sites.
*/
void startAutomaticStateTransfer(Collection<String> sites);
/**
* @param site The remote site.
* @return The {@link XSiteStateTransferMode} configured for the remote site.
*/
XSiteStateTransferMode stateTransferMode(String site);
/**
* Sets the {@link XSiteStateTransferMode} to the remote site.
* <p>
* If the configuration for the remote site does not support the {@link XSiteStateTransferMode}, then this method returns
* {@code false}.
*
* @param site The remote site.
* @param mode The new {@link XSiteStateTransferMode}.
* @return {@code false} if the site does not support the corresponding {@link XSiteStateTransferMode}.
*/
boolean setAutomaticStateTransfer(String site, XSiteStateTransferMode mode);
}
| 4,695
| 31.839161
| 124
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/BaseXSiteStateProviderState.java
|
package org.infinispan.xsite.statetransfer;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicReference;
import org.infinispan.configuration.cache.XSiteStateTransferConfiguration;
import org.infinispan.remoting.transport.Address;
import org.infinispan.xsite.XSiteBackup;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.CompletableObserver;
import io.reactivex.rxjava3.core.CompletableSource;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.functions.Predicate;
/**
* Common code for {@link AsyncProviderState} and {@link SyncProviderState} implementation.
* <p>
* The only difference between the two implementation is the way the state is send to the remote site. The synchronous
* implementation sends the state directly while the asynchronous makes use of IRAC (and its conflict resolution).
*
* @author Pedro Ruivo
* @since 12.0
*/
public abstract class BaseXSiteStateProviderState<T extends BaseXSiteStateProviderState.OutboundTask> implements XSiteStateProviderState {
private final XSiteBackup backup;
private final XSiteStateTransferConfiguration configuration;
private final AtomicReference<T> task;
public BaseXSiteStateProviderState(XSiteBackup backup, XSiteStateTransferConfiguration configuration) {
this.backup = backup;
this.configuration = configuration;
task = new AtomicReference<>();
}
@Override
public XSiteStatePushTask createPushTask(Address originator, XSiteStateProvider provider) {
T newTask = createTask(originator, provider);
return task.compareAndSet(null, newTask) ? newTask : null;
}
@Override
public void cancelTransfer() {
T currentTask = task.getAndSet(null);
if (currentTask != null) {
currentTask.cancel();
}
}
@Override
public boolean isSending() {
return task.get() != null;
}
@Override
public boolean isOriginatorMissing(Collection<Address> members) {
T currentTask = task.get();
return currentTask != null && !members.contains(currentTask.getCoordinator());
}
// methods for OutboundTask
void taskFinished() {
task.set(null);
}
XSiteBackup getBackup() {
return backup;
}
int getChunkSize() {
return configuration.chunkSize();
}
long getWaitTimeMillis() {
return configuration.waitTime();
}
int getMaxRetries() {
return configuration.maxRetries();
}
abstract T createTask(Address originator, XSiteStateProvider provider);
static abstract class OutboundTask implements XSiteStatePushTask, Predicate<List<XSiteState>>, Function<List<XSiteState>, CompletableSource>, CompletableObserver {
private final Address coordinator;
final XSiteStateProvider provider;
final BaseXSiteStateProviderState<?> state;
private volatile boolean canceled = false;
OutboundTask(Address coordinator, XSiteStateProvider provider, BaseXSiteStateProviderState<?> state) {
this.coordinator = coordinator;
this.provider = provider;
this.state = state;
}
Address getCoordinator() {
return coordinator;
}
@Override
public void execute(Flowable<XSiteState> flowable, CompletionStage<Void> delayer) {
//delayer is the cache topology future. we need to ensure the topology id is installed before iterating
delayer.thenRunAsync(() -> flowable
.buffer(state.getChunkSize())
.takeUntil(this)
.concatMapCompletable(this, 1)
.subscribe(this),
provider.getExecutor());
}
public void cancel() {
canceled = true;
}
@Override
public boolean test(List<XSiteState> ignored) {
//Flowable#takeUntil method
return canceled;
}
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onComplete() {
//if canceled, the coordinator already cleanup the resources. There is nothing to be done here.
if (canceled) {
return;
}
provider.notifyStateTransferEnd(state.getBackup().getSiteName(), coordinator, true);
state.taskFinished();
}
@Override
public void onError(@NonNull Throwable e) {
//if canceled, the coordinator already cleanup the resources. There is nothing to be done here.
if (canceled) {
return;
}
provider.notifyStateTransferEnd(state.getBackup().getSiteName(), coordinator, false);
state.taskFinished();
}
}
}
| 4,859
| 30.354839
| 166
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/XSiteStateProviderState.java
|
package org.infinispan.xsite.statetransfer;
import java.util.Collection;
import org.infinispan.configuration.cache.BackupConfiguration;
import org.infinispan.remoting.transport.Address;
/**
* Interface to store the information about a single remote site for {@link XSiteStateProviderImpl}.
*
* @author Pedro Ruivo
* @since 12.0
*/
public interface XSiteStateProviderState {
/**
* Creates a new {@link XSiteStatePushTask} to do state transfer to remove site.
*
* @param originator The originator {@link Address} (node who initiated the state transfer).
* @param provider The {@link XSiteStateProvider} instance to notify when the {@link XSiteStatePushTask} finishes.
* @return The {@link XSiteStatePushTask} instance. or {@code null} if a state transfer is already in progress.
*/
XSiteStatePushTask createPushTask(Address originator, XSiteStateProvider provider);
/**
* Cancels any running state transfer.
* <p>
* If no state transfer is in progress, this method is a no-op.
*/
void cancelTransfer();
/**
* @return {@code true} if a state transfer is in progress for this site.
*/
boolean isSending();
/**
* Returns
*
* @param members The current cluster members list.
* @return {@code true} if a state transfer is in progress and the originator is not in that {@link Collection}.
*/
boolean isOriginatorMissing(Collection<Address> members);
/**
* @return {@code true} if the backup is configured to synchronous cross-site replication.
*/
boolean isSync();
/**
* Factory for {@link XSiteStateProviderState} instances.
*
* @param config The {@link BackupConfiguration}.
* @return The {@link XSiteStateProviderState} instance.
*/
static XSiteStateProviderState fromBackupConfiguration(BackupConfiguration config) {
return config.isSyncBackup() ? SyncProviderState.create(config) : AsyncProviderState.create(config);
}
}
| 1,976
| 31.409836
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/XSiteStateTransferCollector.java
|
package org.infinispan.xsite.statetransfer;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* It collects the acknowledgements sent from local site member to signal the ending of the state sent.
*
* @author Pedro Ruivo
* @since 7.0
*/
public final class XSiteStateTransferCollector {
private static final Log log = LogFactory.getLog(XSiteStateTransferCollector.class);
private final Set<Address> collector;
private boolean statusOk;
public XSiteStateTransferCollector(Collection<Address> confirmationPending) {
if (confirmationPending == null) {
throw new NullPointerException("Pending confirmations must be non-null.");
} else if (confirmationPending.isEmpty()) {
throw new IllegalArgumentException("Pending confirmations must be non-empty.");
}
this.collector = new HashSet<>(confirmationPending);
if (log.isDebugEnabled()) {
log.debugf("Created collector with %s pending!", collector);
}
this.statusOk = true;
}
public boolean confirmStateTransfer(Address node, boolean statusOk) {
synchronized (collector) {
if (log.isTraceEnabled()) {
log.tracef("Remove %s from %s. Status=%s", node, collector, statusOk);
}
if (this.statusOk && !statusOk) {
this.statusOk = false;
}
return collector.remove(node) && collector.isEmpty();
}
}
public boolean isStatusOk() {
synchronized (collector) {
return statusOk;
}
}
public boolean updateMembers(Collection<Address> members) {
synchronized (collector) {
if (log.isTraceEnabled()) {
log.tracef("Retain %s from %s", members, collector);
}
return collector.retainAll(members) && collector.isEmpty();
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
XSiteStateTransferCollector that = (XSiteStateTransferCollector) o;
return collector.equals(that.collector);
}
@Override
public int hashCode() {
return collector.hashCode();
}
@Override
public String toString() {
return "XSiteStateTransferCollector{" +
"collector=" + collector +
'}';
}
}
| 2,492
| 28.329412
| 103
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/RemoteSiteStatus.java
|
package org.infinispan.xsite.statetransfer;
import java.util.Collection;
import java.util.Objects;
import org.infinispan.configuration.cache.BackupConfiguration;
import org.infinispan.configuration.cache.XSiteStateTransferMode;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.logging.Log;
import org.infinispan.xsite.XSiteBackup;
import net.jcip.annotations.GuardedBy;
/**
* Cross-Site state transfer status & collector
*
* @author Pedro Ruivo
* @since 12
*/
public class RemoteSiteStatus {
private final XSiteBackup backup;
private final boolean isSync;
@GuardedBy("this")
private StateTransferStatus status;
@GuardedBy("this")
private XSiteStateTransferCollector collector;
@GuardedBy("this")
private XSiteStateTransferMode stateTransferMode;
private RemoteSiteStatus(XSiteBackup backup, boolean isSync, XSiteStateTransferMode stateTransferMode) {
this.backup = Objects.requireNonNull(backup);
this.isSync = isSync;
this.stateTransferMode = stateTransferMode;
this.status = StateTransferStatus.IDLE;
}
public XSiteBackup getBackup() {
return backup;
}
public boolean isSync() {
return isSync;
}
public String getSiteName() {
return backup.getSiteName();
}
public synchronized StateTransferStatus getStatus() {
return status;
}
public synchronized void clearStatus() {
if (collector == null) {
status = StateTransferStatus.IDLE;
}
}
public synchronized boolean startStateTransfer(Collection<Address> members) {
if (collector != null) {
return false;
}
collector = new XSiteStateTransferCollector(members);
status = StateTransferStatus.SENDING;
return true;
}
public synchronized boolean restartStateTransfer(Collection<Address> newMembers) {
if (collector == null) {
return false;
}
collector = new XSiteStateTransferCollector(newMembers);
return true;
}
public synchronized boolean confirmStateTransfer(Address node, boolean statusOk) {
if (collector == null) {
return false;
}
if (collector.confirmStateTransfer(node, statusOk)) {
status = statusOk ? StateTransferStatus.SEND_OK : StateTransferStatus.SEND_FAILED;
collector = null;
return true;
}
return false;
}
public synchronized void cancelStateTransfer() {
if (collector == null) {
return;
}
collector = null;
status = StateTransferStatus.SEND_CANCELED;
}
public synchronized boolean isStateTransferInProgress() {
return collector != null;
}
public synchronized void failStateTransfer() {
if (collector == null) {
return;
}
collector = null;
status = StateTransferStatus.SEND_FAILED;
}
public static RemoteSiteStatus fromConfiguration(BackupConfiguration configuration) {
XSiteBackup backup = new XSiteBackup(configuration.site(), true, configuration.replicationTimeout());
return new RemoteSiteStatus(backup, configuration.isSyncBackup(), configuration.stateTransfer().mode());
}
public synchronized XSiteStateTransferMode stateTransferMode() {
return stateTransferMode;
}
public synchronized boolean setStateTransferMode(XSiteStateTransferMode mode) {
if (isSync) {
throw Log.XSITE.autoXSiteStateTransferModeNotAvailableInSync();
}
if (stateTransferMode == mode) {
return false;
}
stateTransferMode = mode;
return true;
}
}
| 3,603
| 26.937984
| 110
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/statetransfer/XSiteStateProviderImpl.java
|
package org.infinispan.xsite.statetransfer;
import static org.infinispan.factories.KnownComponentNames.NON_BLOCKING_EXECUTOR;
import static org.infinispan.factories.KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commons.util.IntSet;
import org.infinispan.commons.util.IntSets;
import org.infinispan.configuration.cache.BackupConfiguration;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.container.impl.InternalDataContainer;
import org.infinispan.factories.annotations.ComponentName;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.interceptors.locking.ClusteringDependentLogic;
import org.infinispan.persistence.manager.PersistenceManager;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.statetransfer.StateTransferLock;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.commands.XSiteStateTransferFinishSendCommand;
import org.infinispan.xsite.irac.IracManager;
import org.reactivestreams.Publisher;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.functions.Predicate;
/**
* It contains the logic to send state to another site.
*
* @author Pedro Ruivo
* @since 7.0
*/
@Scope(Scopes.NAMED_CACHE)
public class XSiteStateProviderImpl implements XSiteStateProvider {
private static final Log log = LogFactory.getLog(XSiteStateProviderImpl.class);
private static final Predicate<InternalCacheEntry<Object, Object>> NOT_L1_ENTRY = e -> !e.isL1Entry();
@Inject InternalDataContainer<Object, Object> dataContainer;
@Inject PersistenceManager persistenceManager;
@Inject ClusteringDependentLogic clusteringDependentLogic;
@Inject CommandsFactory commandsFactory;
@Inject RpcManager rpcManager;
@Inject ComponentRef<XSiteStateTransferManager> stateTransferManager;
@Inject IracManager iracManager;
@Inject StateTransferLock stateTransferLock;
@Inject
@ComponentName(NON_BLOCKING_EXECUTOR)
ExecutorService nonBlockingExecutor;
@Inject
@ComponentName(TIMEOUT_SCHEDULE_EXECUTOR)
ScheduledExecutorService timeoutExecutor;
private final ConcurrentMap<String, XSiteStateProviderState> sites;
public XSiteStateProviderImpl(Configuration configuration) {
sites = new ConcurrentHashMap<>();
for (BackupConfiguration backupConfiguration : configuration.sites().allBackups()) {
sites.put(backupConfiguration.site(), XSiteStateProviderState.fromBackupConfiguration(backupConfiguration));
}
}
@Start
public void start() {
sites.remove(rpcManager.getTransport().localSiteName());
}
@Override
public void startStateTransfer(String siteName, Address origin, int minTopologyId) {
XSiteStateProviderState state = sites.get(siteName);
assert state != null; //invoked from XSiteStateTransferManager, so the site name must exist
XSiteStatePushTask task = state.createPushTask(origin, this);
if (task == null) {
if (log.isDebugEnabled()) {
log.debugf("Do not start state transfer to site '%s'. It has already started!", siteName);
}
checkCoordinatorAlive(siteName, origin);
return;
}
if (log.isDebugEnabled()) {
log.debugf("Starting state transfer to site '%s'", siteName);
}
IntSet segments = localPrimarySegments();
Flowable<XSiteState> flowable = Flowable.concat(publishDataContainerEntries(segments), publishStoreEntries(segments, state.isSync()));
task.execute(flowable, stateTransferLock.topologyFuture(minTopologyId));
checkCoordinatorAlive(siteName, origin);
}
@Override
public void cancelStateTransfer(String siteName) {
XSiteStateProviderState state = sites.get(siteName);
assert state != null; //invoked from XSiteStateTransferManager, so the site name must exist
state.cancelTransfer();
}
@Override
public Collection<String> getCurrentStateSending() {
return sites.entrySet().stream()
.filter(e -> e.getValue().isSending())
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
@Override
public Collection<String> getSitesMissingCoordinator(Collection<Address> currentMembers) {
return sites.entrySet().stream()
.filter(e -> e.getValue().isOriginatorMissing(currentMembers))
.map(Map.Entry::getKey).collect(Collectors.toList());
}
@Override
public void notifyStateTransferEnd(final String siteName, final Address origin, final boolean statusOk) {
if (log.isDebugEnabled()) {
log.debugf("Finished state transfer to site '%s'. Ok? %s", siteName, statusOk);
}
if (rpcManager.getAddress().equals(origin)) {
stateTransferManager.running().notifyStatePushFinished(siteName, origin, statusOk);
} else {
XSiteStateTransferFinishSendCommand command = commandsFactory.buildXSiteStateTransferFinishSendCommand(siteName, statusOk);
rpcManager.sendTo(origin, command, DeliverOrder.NONE);
}
}
@Override
public CommandsFactory getCommandsFactory() {
return commandsFactory;
}
@Override
public RpcManager getRpcManager() {
return rpcManager;
}
@Override
public IracManager getIracManager() {
return iracManager;
}
@Override
public ScheduledExecutorService getScheduledExecutorService() {
return timeoutExecutor;
}
@Override
public Executor getExecutor() {
return nonBlockingExecutor;
}
private void checkCoordinatorAlive(String siteName, Address origin) {
if (rpcManager.getAddress().equals(rpcManager.getMembers().get(0)) && !rpcManager.getMembers().contains(origin)) {
stateTransferManager.running().becomeCoordinator(siteName);
}
}
private IntSet localPrimarySegments() {
return IntSets.from(clusteringDependentLogic.getCacheTopology()
.getWriteConsistentHash()
.getPrimarySegmentsForOwner(rpcManager.getAddress()));
}
private Flowable<XSiteState> publishDataContainerEntries(IntSet segments) {
return Flowable.fromIterable(() -> dataContainer.iterator(segments))
// TODO Investigate removing the filter, we clear L1 entries before becoming an owner
.filter(NOT_L1_ENTRY)
.map(XSiteState::fromDataContainer);
}
private Flowable<XSiteState> publishStoreEntries(IntSet segments, boolean syncBackup) {
//async backup only needs the key
Publisher<MarshallableEntry<Object, Object>> loaderPublisher =
persistenceManager.publishEntries(segments, this::missingInDataContainer, syncBackup, syncBackup,
PersistenceManager.AccessMode.PRIVATE);
return Flowable.fromPublisher(loaderPublisher).map(XSiteState::fromCacheLoader);
}
private boolean missingInDataContainer(Object key) {
return dataContainer.peek(key) == null;
}
}
| 7,769
| 37.465347
| 140
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/ContainerMixedSiteStatus.java
|
package org.infinispan.xsite.status;
import java.util.Collection;
import java.util.List;
/**
* A mixed {@link SiteStatus}.
*
* Used per container and it describes the caches in which the site is online, offline and mixed.
*
* @author Pedro Ruivo
* @since 8.2
*/
public class ContainerMixedSiteStatus extends AbstractMixedSiteStatus<String> {
private final List<String> mixedCaches;
public ContainerMixedSiteStatus(Collection<String> onlineCacheNameCollection,
Collection<String> offlineCacheNameCollection,
Collection<String> mixedCacheNameCollection) {
super(onlineCacheNameCollection, offlineCacheNameCollection);
this.mixedCaches = toImmutable(mixedCacheNameCollection);
}
public List<String> getMixedCaches() {
return mixedCaches;
}
}
| 854
| 28.482759
| 97
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/SiteState.java
|
package org.infinispan.xsite.status;
/**
* The site state.
*
* @author Pedro Ruivo
* @since 11.0
*/
public enum SiteState {
NOT_FOUND,
ONLINE,
OFFLINE
}
| 168
| 11.071429
| 36
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/OfflineSiteStatus.java
|
package org.infinispan.xsite.status;
/**
* {@link SiteStatus} implementation for offline sites.
*
* This class is a singleton and its instance is accessible via {@link #getInstance()}.
*
* @author Pedro Ruivo
* @since 8.2
*/
public class OfflineSiteStatus implements SiteStatus {
private OfflineSiteStatus() {
}
public static OfflineSiteStatus getInstance() {
return SingletonHolder.INSTANCE;
}
@Override
public boolean isOnline() {
return false;
}
@Override
public boolean isOffline() {
return true;
}
private static class SingletonHolder {
private static final OfflineSiteStatus INSTANCE = new OfflineSiteStatus();
}
}
| 695
| 18.885714
| 87
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/CacheMixedSiteStatus.java
|
package org.infinispan.xsite.status;
import java.util.List;
import org.infinispan.remoting.transport.Address;
/**
* A mixed {@link SiteStatus}.
* <p>
* Used per cache and it describes the nodes in which the site is online and offline.
*
* @author Pedro Ruivo
* @since 8.2
*/
public class CacheMixedSiteStatus extends AbstractMixedSiteStatus<Address> {
public CacheMixedSiteStatus(List<Address> onlineMembers, List<Address> offlineMembers) {
super(onlineMembers, offlineMembers);
}
}
| 505
| 24.3
| 91
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/NoOpTakeOfflineManager.java
|
package org.infinispan.xsite.status;
import java.util.Collections;
import java.util.Map;
import org.infinispan.configuration.cache.TakeOfflineConfiguration;
import org.infinispan.remoting.transport.XSiteResponse;
/**
* An empty {@link TakeOfflineManager} implementation for caches which don't backup any data to remote sites.
*
* @author Pedro Ruivo
* @since 11.0
*/
public class NoOpTakeOfflineManager implements TakeOfflineManager {
private static final NoOpTakeOfflineManager INSTANCE = new NoOpTakeOfflineManager();
private NoOpTakeOfflineManager() {
}
public static NoOpTakeOfflineManager getInstance() {
return INSTANCE;
}
@Override
public void registerRequest(XSiteResponse response) {
//no-op
}
@Override
public SiteState getSiteState(String siteName) {
return SiteState.NOT_FOUND;
}
@Override
public void amendConfiguration(String siteName, Integer afterFailures, Long minTimeToWait) {
//no-op
}
@Override
public TakeOfflineConfiguration getConfiguration(String siteName) {
//non-existing
return null;
}
@Override
public Map<String, Boolean> status() {
return Collections.emptyMap();
}
@Override
public BringSiteOnlineResponse bringSiteOnline(String siteName) {
return BringSiteOnlineResponse.NO_SUCH_SITE;
}
@Override
public TakeSiteOfflineResponse takeSiteOffline(String siteName) {
return TakeSiteOfflineResponse.NO_SUCH_SITE;
}
}
| 1,493
| 23.096774
| 109
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/OnlineSiteStatus.java
|
package org.infinispan.xsite.status;
/**
* {@link SiteStatus} implementation for online sites.
*
* This class is a singleton and its instance is accessible via {@link #getInstance()}.
*
* @author Pedro Ruivo
* @since 8.2
*/
public class OnlineSiteStatus implements SiteStatus {
private OnlineSiteStatus() {
}
public static OnlineSiteStatus getInstance() {
return SingletonHolder.INSTANCE;
}
@Override
public boolean isOnline() {
return true;
}
@Override
public boolean isOffline() {
return false;
}
private static class SingletonHolder {
private static final OnlineSiteStatus INSTANCE = new OnlineSiteStatus();
}
}
| 689
| 18.714286
| 87
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/TakeSiteOfflineResponse.java
|
package org.infinispan.xsite.status;
/**
* The return value of {@link TakeOfflineManager#takeSiteOffline(String)}.
*
* @author Pedro Ruivo
* @since 11.0
*/
public enum TakeSiteOfflineResponse {
NO_SUCH_SITE,
ALREADY_OFFLINE,
TAKEN_OFFLINE
}
| 256
| 17.357143
| 74
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/CacheSiteStatusBuilder.java
|
package org.infinispan.xsite.status;
import java.util.List;
import org.infinispan.remoting.transport.Address;
/**
* A per-cache {@link SiteStatus} builder.
* <p>
* It builds a {@link SiteStatus} based on the number of node with the site online and offline.
*
* @author Pedro Ruivo
* @since 8.2
*/
public class CacheSiteStatusBuilder extends AbstractSiteStatusBuilder<Address> {
public CacheSiteStatusBuilder() {
super();
}
/**
* Adds a member with an online/offline connection to the server based on the {@code online} parameter.
*
* @param address The member {@link Address}.
* @param online {@code true} if the member has online connection, {@code false} otherwise.
*/
public void addMember(Address address, boolean online) {
if (online) {
onlineOn(address);
} else {
offlineOn(address);
}
}
@Override
protected SiteStatus createMixedStatus(List<Address> onlineElements, List<Address> offlineElements) {
return new CacheMixedSiteStatus(onlineElements, offlineElements);
}
}
| 1,082
| 26.075
| 106
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/BringSiteOnlineResponse.java
|
package org.infinispan.xsite.status;
/**
* The return value of {@link TakeOfflineManager#bringSiteOnline(String)}.
*
* @author Pedro Ruivo
* @since 11.0
*/
public enum BringSiteOnlineResponse {
NO_SUCH_SITE,
ALREADY_ONLINE,
BROUGHT_ONLINE
}
| 256
| 17.357143
| 74
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/TakeOfflineManager.java
|
package org.infinispan.xsite.status;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.infinispan.configuration.cache.TakeOfflineConfiguration;
import org.infinispan.configuration.cache.TakeOfflineConfigurationBuilder;
import org.infinispan.factories.impl.MBeanMetadata;
import org.infinispan.metrics.impl.CustomMetricsSupplier;
import org.infinispan.remoting.transport.XSiteResponse;
/**
* It keeps tracks of cross-site requests to take sites offline when certain failures conditions happen.
* <p>
* Those condition are configured in {@link TakeOfflineConfiguration}.
*
* @author Pedro Ruivo
* @since 11.0
*/
public interface TakeOfflineManager extends CustomMetricsSupplier {
/**
* Registers a cross-site request made.
* <p>
* Handles the response for the request and takes action in case of failure.
*
* @param response The cross-site response.
*/
void registerRequest(XSiteResponse<?> response);
/**
* Returns the site state for site {@code siteName}.
* <p>
* The site can be {@link SiteState#ONLINE} or {@link SiteState#OFFLINE}. If it doesn't exist, {@link
* SiteState#NOT_FOUND} is returned.
*
* @param siteName The remote site name.
* @return The {@link SiteState}.
*/
SiteState getSiteState(String siteName);
/**
* It changes the {@link TakeOfflineConfiguration} for site {@code siteName}.
* <p>
* If the {@code siteName} doesn't exist, this method is a no-op.
*
* @param siteName The remote site name.
* @param afterFailures The new {@link TakeOfflineConfigurationBuilder#afterFailures(int)} or {@code null} for no
* changes.
* @param minTimeToWait The new {@link TakeOfflineConfigurationBuilder#minTimeToWait(long)} or {@code null} for no
* changes.
*/
void amendConfiguration(String siteName, Integer afterFailures, Long minTimeToWait);
/**
* It returns the current {@link TakeOfflineConfiguration} for site {@code siteName}.
*
* @param siteName The remote site name.
* @return The current {@link TakeOfflineConfiguration} or {@code null} if the site {@code siteName} doesn't exist.
*/
TakeOfflineConfiguration getConfiguration(String siteName);
/**
* It returns a {@link Map} with the sites name and their state (Online or Offline).
* <p>
* If a site is online, then its value is {@link Boolean#TRUE}, otherwise is {@link Boolean#FALSE}.
*
* @return A {@link Map} with the site state.
*/
Map<String, Boolean> status();
/**
* It changes the site {@code siteName} to online.
* <p>
* If the site is already online, then {@link BringSiteOnlineResponse#ALREADY_ONLINE} is returned. If it doesn't
* exits, {@link BringSiteOnlineResponse#NO_SUCH_SITE} is returned.
*
* @param siteName The remote site name.
* @return The {@link BringSiteOnlineResponse}.
*/
BringSiteOnlineResponse bringSiteOnline(String siteName);
/**
* It changes the site {@code siteName} to offline.
* <p>
* If the site is already offline, then {@link TakeSiteOfflineResponse#ALREADY_OFFLINE} is returned. If it doesn't
* exits, {@link TakeSiteOfflineResponse#NO_SUCH_SITE} is returned.
*
* @param siteName The remote site name.
* @return The {@link TakeSiteOfflineResponse}.
*/
TakeSiteOfflineResponse takeSiteOffline(String siteName);
@Override
default Collection<MBeanMetadata.AttributeMetadata> getCustomMetrics() {
return Collections.emptyList();
}
}
| 3,600
| 35.01
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/AbstractMixedSiteStatus.java
|
package org.infinispan.xsite.status;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Abstract class to create mixed {@link SiteStatus}.
* <p>
* Mixed {@link SiteStatus} are status in which some considers the site to be online and other to be offline.
*
* @author Pedro Ruivo
* @since 8.2
*/
public abstract class AbstractMixedSiteStatus<E> implements SiteStatus {
protected final List<E> online;
protected final List<E> offline;
protected AbstractMixedSiteStatus(Collection<E> online, Collection<E> offline) {
this.online = toImmutable(online);
this.offline = toImmutable(offline);
}
protected static <E> List<E> toImmutable(Collection<E> collection) {
return Collections.unmodifiableList(new ArrayList<>(collection));
}
@Override
public final boolean isOnline() {
return false;
}
@Override
public final boolean isOffline() {
return false;
}
public List<E> getOnline() {
return online;
}
public List<E> getOffline() {
return offline;
}
}
| 1,112
| 22.1875
| 109
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/SiteStatus.java
|
package org.infinispan.xsite.status;
/**
* A site status.
* <p>
* A site could be online, offline or none of the previous. In the later case, it is consider in a mixed status and both
* {@link #isOnline()} and {@link #isOffline()} returns {@code false}.
*
* @author Pedro Ruivo
* @since 8.2
*/
public interface SiteStatus {
/**
* @return {@code true} if the site is online.
*/
boolean isOnline();
/**
* @return {@code true} if the site is offline.
*/
boolean isOffline();
}
| 516
| 19.68
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/AbstractSiteStatusBuilder.java
|
package org.infinispan.xsite.status;
import java.util.LinkedList;
import java.util.List;
/**
* A {@link SiteStatus} builder based on its online and offline members.
*
* @author Pedro Ruivo
* @since 8.2
*/
public abstract class AbstractSiteStatusBuilder<E> {
private final List<E> onlineElements;
private final List<E> offlineElements;
protected AbstractSiteStatusBuilder() {
offlineElements = new LinkedList<>();
onlineElements = new LinkedList<>();
}
/**
* Adds the element with an online connection to the site.
*
* @param member The member.
*/
public final void onlineOn(E member) {
onlineElements.add(member);
}
/**
* Adds the member with an offline connection to the site.
*
* @param member The member.
*/
public final void offlineOn(E member) {
offlineElements.add(member);
}
/**
* @return {@link SiteStatus} created.
*/
public final SiteStatus build() {
if (isOnline()) {
return OnlineSiteStatus.getInstance();
} else if (isOffline()) {
return OfflineSiteStatus.getInstance();
} else {
return createMixedStatus(onlineElements, offlineElements);
}
}
protected boolean isOnline() {
return !onlineElements.isEmpty() && offlineElements.isEmpty();
}
protected boolean isOffline() {
return onlineElements.isEmpty() && !offlineElements.isEmpty();
}
protected abstract SiteStatus createMixedStatus(List<E> onlineElements, List<E> offlineElements);
}
| 1,546
| 23.171875
| 100
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/ContainerSiteStatusBuilder.java
|
package org.infinispan.xsite.status;
import java.util.LinkedList;
import java.util.List;
/**
* A per-container {@link SiteStatus} builder.
* <p>
* It builds a {@link SiteStatus} based on the caches which have the site online, offline or mixed status.
*
* @author Pedro Ruivo
* @since 8.2
*/
public class ContainerSiteStatusBuilder extends AbstractSiteStatusBuilder<String> {
private final List<String> mixedCaches;
public ContainerSiteStatusBuilder() {
super();
mixedCaches = new LinkedList<>();
}
/**
* Adds the cache with an mixed connection to the site.
*
* @param cacheName The cache name.
*/
public void mixedOn(String cacheName) {
mixedCaches.add(cacheName);
}
/**
* Adds the cache with the {@link SiteStatus} connection to the site.
*
* @param cacheName The cache name.
* @param status {@link SiteStatus} of the site.
*/
public void addCacheName(String cacheName, SiteStatus status) {
if (status.isOnline()) {
onlineOn(cacheName);
} else if (status.isOffline()) {
offlineOn(cacheName);
} else {
mixedOn(cacheName);
}
}
@Override
protected boolean isOnline() {
return super.isOnline() && mixedCaches.isEmpty();
}
@Override
protected boolean isOffline() {
return super.isOffline() && mixedCaches.isEmpty();
}
@Override
protected SiteStatus createMixedStatus(List<String> onlineElements, List<String> offlineElements) {
return new ContainerMixedSiteStatus(onlineElements, offlineElements, mixedCaches);
}
}
| 1,607
| 24.52381
| 106
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/status/DefaultTakeOfflineManager.java
|
package org.infinispan.xsite.status;
import static org.infinispan.util.logging.events.Messages.MESSAGES;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.time.TimeService;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.TakeOfflineConfiguration;
import org.infinispan.container.impl.InternalDataContainer;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.impl.MBeanMetadata;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.metrics.impl.MetricUtils;
import org.infinispan.remoting.CacheUnreachableException;
import org.infinispan.remoting.RemoteException;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.XSiteResponse;
import org.infinispan.remoting.transport.jgroups.SuspectException;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.util.logging.events.EventLogCategory;
import org.infinispan.util.logging.events.EventLogManager;
import org.infinispan.util.logging.events.EventLogger;
import org.infinispan.xsite.OfflineStatus;
import org.infinispan.xsite.XSiteBackup;
import org.infinispan.xsite.notification.SiteStatusListener;
import org.jgroups.UnreachableException;
/**
* The default implementation of {@link TakeOfflineManager}.
* <p>
* It automatically takes a site offline when certain failures condition happens.
*
* @author Pedro Ruivo
* @since 11.0
*/
@Scope(Scopes.NAMED_CACHE)
public class DefaultTakeOfflineManager implements TakeOfflineManager, XSiteResponse.XSiteResponseCompleted {
private static final Log log = LogFactory.getLog(DefaultTakeOfflineManager.class);
private final String cacheName;
private final Map<String, OfflineStatus> offlineStatus;
@Inject TimeService timeService;
@Inject Configuration config;
@Inject EventLogManager eventLogManager;
@Inject RpcManager rpcManager;
@Inject InternalDataContainer<Object, Object> dataContainer;
public DefaultTakeOfflineManager(String cacheName) {
this.cacheName = cacheName;
offlineStatus = new ConcurrentHashMap<>(8);
}
public static boolean isCommunicationError(Throwable throwable) {
Throwable error = throwable;
if (throwable instanceof ExecutionException) {
error = throwable.getCause();
}
return error instanceof TimeoutException ||
error instanceof org.infinispan.util.concurrent.TimeoutException ||
error instanceof UnreachableException ||
error instanceof CacheUnreachableException ||
error instanceof SuspectException;
}
private static Optional<CacheConfigurationException> findConfigurationError(Throwable throwable) {
Throwable error = throwable;
if (throwable instanceof ExecutionException || throwable instanceof RemoteException) {
error = throwable.getCause();
}
return error instanceof CacheConfigurationException ? //incorrect cache configuration in remote site?
Optional.of((CacheConfigurationException) error) :
Optional.empty();
}
@Start
public void start() {
String localSiteName = rpcManager.getTransport().localSiteName();
config.sites().allBackupsStream()
.filter(bc -> !localSiteName.equals(bc.site()))
.forEach(bc -> {
String siteName = bc.site();
OfflineStatus offline = new OfflineStatus(bc.takeOffline(), timeService, new Listener(siteName));
offlineStatus.put(siteName, offline);
});
}
@Override
public void registerRequest(XSiteResponse<?> response) {
response.whenCompleted(this);
}
@Override
public SiteState getSiteState(String siteName) {
OfflineStatus offline = offlineStatus.get(siteName);
if (offline == null) {
return SiteState.NOT_FOUND;
}
return offline.isOffline() ? SiteState.OFFLINE : SiteState.ONLINE;
}
@Override
public void amendConfiguration(String siteName, Integer afterFailures, Long minTimeToWait) {
OfflineStatus status = offlineStatus.get(siteName);
if (status == null) {
return;
}
status.amend(afterFailures, minTimeToWait);
}
@Override
public TakeOfflineConfiguration getConfiguration(String siteName) {
OfflineStatus status = offlineStatus.get(siteName);
return status == null ? null : status.getTakeOffline();
}
@Override
public Map<String, Boolean> status() {
Map<String, Boolean> result = new HashMap<>(offlineStatus.size());
for (Map.Entry<String, OfflineStatus> os : offlineStatus.entrySet()) {
result.put(os.getKey(), !os.getValue().isOffline());
}
return result;
}
@Override
public BringSiteOnlineResponse bringSiteOnline(String siteName) {
OfflineStatus status = offlineStatus.get(siteName);
if (status == null) {
log.tryingToBringOnlineNonexistentSite(siteName);
return BringSiteOnlineResponse.NO_SUCH_SITE;
} else {
return status.bringOnline() ? BringSiteOnlineResponse.BROUGHT_ONLINE : BringSiteOnlineResponse.ALREADY_ONLINE;
}
}
@Override
public TakeSiteOfflineResponse takeSiteOffline(String siteName) {
OfflineStatus status = offlineStatus.get(siteName);
if (status == null) {
return TakeSiteOfflineResponse.NO_SUCH_SITE;
} else {
return status.forceOffline() ? TakeSiteOfflineResponse.TAKEN_OFFLINE
: TakeSiteOfflineResponse.ALREADY_OFFLINE;
}
}
@Override
public Collection<MBeanMetadata.AttributeMetadata> getCustomMetrics() {
List<MBeanMetadata.AttributeMetadata> attributes = new ArrayList<>(offlineStatus.size() * 3);
for (Map.Entry<String, OfflineStatus> entry : offlineStatus.entrySet()) {
String lowerCaseSite = entry.getKey().toLowerCase();
OfflineStatus status = entry.getValue();
attributes.add(MetricUtils.createGauge(lowerCaseSite + "_status", entry.getKey() + " status. 1=online, 0=offline", o -> status.isOffline() ? 0 : 1));
attributes.add(MetricUtils.createGauge(lowerCaseSite + "_failures_count", "Number of consecutive failures to " + entry.getKey(), o -> status.getFailureCount()));
attributes.add(MetricUtils.createGauge(lowerCaseSite + "_millis_since_first_failure", "Milliseconds from first consecutive failure to " + entry.getKey(), o -> status.millisSinceFirstFailure()));
}
return attributes;
}
@Override
public void onCompleted(XSiteBackup backup, long sendTimeNanos, long durationNanos, Throwable throwable) {
OfflineStatus status = offlineStatus.get(backup.getSiteName());
assert status != null;
Optional<CacheConfigurationException> e = findConfigurationError(throwable);
if (e.isPresent()) {
//we have an invalid configuration. change site to offline
log.xsiteInvalidConfigurationRemoteSite(backup.getSiteName(), e.get());
status.forceOffline();
return;
}
if (status.isEnabled()) {
if (isCommunicationError(throwable)) {
status.updateOnCommunicationFailure(TimeUnit.NANOSECONDS.toMillis(sendTimeNanos));
} else if (!status.isOffline()) {
status.reset();
}
}
}
public OfflineStatus getOfflineStatus(String siteName) {
return offlineStatus.get(siteName);
}
@Override
public String toString() {
return "DefaultTakeOfflineManager{cacheName='" + cacheName + "'}";
}
private EventLogger getEventLogger() {
return eventLogManager.getEventLogger().context(cacheName).scope(rpcManager.getAddress());
}
private final class Listener implements SiteStatusListener {
private final String siteName;
Listener(String siteName) {
this.siteName = siteName;
}
@Override
public void siteOnline() {
getEventLogger().info(EventLogCategory.CLUSTER, MESSAGES.siteOnline(siteName));
}
@Override
public void siteOffline() {
getEventLogger().info(EventLogCategory.CLUSTER, MESSAGES.siteOffline(siteName));
log.debug("Touching all in memory entries as a site has gone offline");
long currentTimeMillis = timeService.wallClockTime();
dataContainer.forEachSegment((map, segment) -> map.touchAll(currentTimeMillis));
}
@Override
public String toString() {
return "Listener{" +
"siteName='" + siteName + '\'' +
'}';
}
}
}
| 9,090
| 36.721992
| 203
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/metrics/DefaultXSiteMetricsCollector.java
|
package org.infinispan.xsite.metrics;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
import org.infinispan.commons.stat.SimpleStat;
import org.infinispan.commons.stat.SimpleStateWithTimer;
import org.infinispan.commons.stat.TimerTracker;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* Implementation of {@link XSiteMetricsCollector} to use when asynchronous backups (cross-site replication) are
* configured.
*
* @author Pedro Ruivo
* @since 13.0
*/
@Scope(Scopes.NAMED_CACHE)
public class DefaultXSiteMetricsCollector implements XSiteMetricsCollector {
private static final long NON_EXISTING = -1;
private final Map<String, SiteMetric> siteMetricMap;
private final SimpleStat globalRequestsSent;
public DefaultXSiteMetricsCollector(Configuration configuration) {
siteMetricMap = new ConcurrentHashMap<>();
configuration.sites().allBackupsStream().forEach(c -> siteMetricMap.put(c.site(), new SiteMetric()));
globalRequestsSent = new SimpleStateWithTimer();
}
private static SiteMetric newSiteMetric(String site) {
return new SiteMetric();
}
private static long convert(long value, long defaultValue, TimeUnit timeUnit) {
return value == NON_EXISTING ? defaultValue : timeUnit.convert(value, TimeUnit.NANOSECONDS);
}
@Override
public Collection<String> sites() {
return Collections.unmodifiableCollection(siteMetricMap.keySet());
}
@Override
public void recordRequestSent(String dstSite, long duration, TimeUnit timeUnit) {
assert duration > 0;
long durationNanos = timeUnit.toNanos(duration);
getSiteMetricToRecord(dstSite).getRequestsSent().record(durationNanos);
globalRequestsSent.record(durationNanos);
}
@Override
public long getMinRequestSentDuration(String dstSite, long defaultValue, TimeUnit outTimeUnit) {
SiteMetric metric = siteMetricMap.get(dstSite);
if (metric == null) {
return defaultValue;
}
long val = metric.getRequestsSent().getMin(NON_EXISTING);
return convert(val, defaultValue, outTimeUnit);
}
@Override
public long getMinRequestSentDuration(long defaultValue, TimeUnit outTimeUnit) {
long val = globalRequestsSent.getMin(NON_EXISTING);
return convert(val, defaultValue, outTimeUnit);
}
@Override
public long getMaxRequestSentDuration(String dstSite, long defaultValue, TimeUnit outTimeUnit) {
SiteMetric metric = siteMetricMap.get(dstSite);
if (metric == null) {
return defaultValue;
}
long val = metric.getRequestsSent().getMax(NON_EXISTING);
return convert(val, defaultValue, outTimeUnit);
}
@Override
public long getMaxRequestSentDuration(long defaultValue, TimeUnit outTimeUnit) {
long val = globalRequestsSent.getMax(NON_EXISTING);
return convert(val, defaultValue, outTimeUnit);
}
@Override
public long getAvgRequestSentDuration(String dstSite, long defaultValue, TimeUnit outTimeUnit) {
SiteMetric metric = siteMetricMap.get(dstSite);
if (metric == null) {
return defaultValue;
}
long val = metric.getRequestsSent().getAverage(NON_EXISTING);
return convert(val, defaultValue, outTimeUnit);
}
@Override
public long getAvgRequestSentDuration(long defaultValue, TimeUnit outTimeUnit) {
long val = globalRequestsSent.getAverage(NON_EXISTING);
return convert(val, defaultValue, outTimeUnit);
}
@Override
public long countRequestsSent(String dstSite) {
SiteMetric metric = siteMetricMap.get(dstSite);
return metric == null ? 0 : metric.getRequestsSent().count();
}
@Override
public long countRequestsSent() {
return globalRequestsSent.count();
}
@Override
public void resetRequestsSent() {
globalRequestsSent.reset();
siteMetricMap.values().forEach(siteMetric -> siteMetric.getRequestsSent().reset());
}
@Override
public void registerTimer(String dstSite, TimerTracker timer) {
getSiteMetricToRecord(dstSite).getRequestsSent().setTimer(timer);
}
@Override
public void registerTimer(TimerTracker timer) {
globalRequestsSent.setTimer(timer);
}
@Override
public void recordRequestsReceived(String srcSite) {
getSiteMetricToRecord(srcSite).getRequestsReceived().increment();
}
@Override
public long countRequestsReceived(String srcSite) {
SiteMetric metric = siteMetricMap.get(srcSite);
return metric == null ? 0 : metric.getRequestsReceived().sum();
}
@Override
public long countRequestsReceived() {
return siteMetricMap.values().stream()
.map(SiteMetric::getRequestsReceived)
.map(LongAdder::sum)
.reduce(0L, Long::sum);
}
@Override
public void resetRequestReceived() {
siteMetricMap.values().forEach(siteMetric -> siteMetric.getRequestsReceived().reset());
}
private SiteMetric getSiteMetricToRecord(String dstSite) {
return siteMetricMap.computeIfAbsent(dstSite, DefaultXSiteMetricsCollector::newSiteMetric);
}
/**
* Per site statistics (requests sent/received and response times)
*/
private static class SiteMetric {
private final SimpleStat requestsSent = new SimpleStateWithTimer();
private final LongAdder requestsReceived = new LongAdder();
public SimpleStat getRequestsSent() {
return requestsSent;
}
public LongAdder getRequestsReceived() {
return requestsReceived;
}
}
}
| 5,840
| 31.814607
| 112
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/metrics/NoOpXSiteMetricsCollector.java
|
package org.infinispan.xsite.metrics;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import org.infinispan.commons.stat.TimerTracker;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* An no-op implementation for {@link XSiteMetricsCollector}.
* <p>
* Used when cross-site replication isn't enabled on a cache.
*
* @author Pedro Ruivo
* @since 13.0
*/
@Scope(Scopes.NAMED_CACHE)
public class NoOpXSiteMetricsCollector implements XSiteMetricsCollector {
private static final NoOpXSiteMetricsCollector INSTANCE = new NoOpXSiteMetricsCollector();
private NoOpXSiteMetricsCollector() {
}
public static NoOpXSiteMetricsCollector getInstance() {
return INSTANCE;
}
@Override
public Collection<String> sites() {
return Collections.emptyList();
}
@Override
public void recordRequestSent(String dstSite, long duration, TimeUnit timeUnit) {
//no-op
}
@Override
public long getMinRequestSentDuration(String dstSite, long defaultValue, TimeUnit outTimeUnit) {
return defaultValue;
}
@Override
public long getMinRequestSentDuration(long defaultValue, TimeUnit outTimeUnit) {
return defaultValue;
}
@Override
public long getMaxRequestSentDuration(String dstSite, long defaultValue, TimeUnit outTimeUnit) {
return defaultValue;
}
@Override
public long getMaxRequestSentDuration(long defaultValue, TimeUnit outTimeUnit) {
return defaultValue;
}
@Override
public long getAvgRequestSentDuration(String dstSite, long defaultValue, TimeUnit outTimeUnit) {
return defaultValue;
}
@Override
public long getAvgRequestSentDuration(long defaultValue, TimeUnit outTimeUnit) {
return defaultValue;
}
@Override
public long countRequestsSent(String dstSite) {
return 0;
}
@Override
public long countRequestsSent() {
return 0;
}
@Override
public void resetRequestsSent() {
//no-op
}
@Override
public void registerTimer(String dstSite, TimerTracker timer) {
//no-op
}
@Override
public void registerTimer(TimerTracker timer) {
//no-op
}
@Override
public void recordRequestsReceived(String srcSite) {
//no-op;
}
@Override
public long countRequestsReceived(String srcSite) {
return 0;
}
@Override
public long countRequestsReceived() {
return 0;
}
@Override
public void resetRequestReceived() {
//no-op
}
}
| 2,576
| 21.215517
| 99
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/metrics/XSiteMetricsCollector.java
|
package org.infinispan.xsite.metrics;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import org.infinispan.commons.stat.TimerTracker;
/**
* Collects metrics about cross-site replication operations.
*
* @author Pedro Ruivo
* @since 13.0
*/
public interface XSiteMetricsCollector {
Collection<String> sites();
// -- requests sent statistics -- //
void recordRequestSent(String dstSite, long duration, TimeUnit timeUnit);
long getMinRequestSentDuration(String dstSite, long defaultValue, TimeUnit outTimeUnit);
long getMinRequestSentDuration(long defaultValue, TimeUnit outTimeUnit);
long getMaxRequestSentDuration(String dstSite, long defaultValue, TimeUnit outTimeUnit);
long getMaxRequestSentDuration(long defaultValue, TimeUnit outTimeUnit);
long getAvgRequestSentDuration(String dstSite, long defaultValue, TimeUnit outTimeUnit);
long getAvgRequestSentDuration(long defaultValue, TimeUnit outTimeUnit);
long countRequestsSent(String dstSite);
long countRequestsSent();
void resetRequestsSent();
void registerTimer(String dstSite, TimerTracker timer);
void registerTimer(TimerTracker timer);
// -- requests received statistics -- //
void recordRequestsReceived(String srcSite);
long countRequestsReceived(String srcSite);
long countRequestsReceived();
void resetRequestReceived();
}
| 1,388
| 24.722222
| 91
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/xsite/commands/XSiteOfflineStatusCommand.java
|
package org.infinispan.xsite.commands;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.util.ByteString;
import org.infinispan.xsite.BackupSender;
import org.infinispan.xsite.status.SiteState;
import org.infinispan.xsite.status.TakeOfflineManager;
/**
* Get the offline status of a {@link BackupSender}.
*
* @author Ryan Emerson
* @since 11.0
*/
public class XSiteOfflineStatusCommand extends BaseRpcCommand {
public static final int COMMAND_ID = 99;
private String siteName;
// For CommandIdUniquenessTest only
public XSiteOfflineStatusCommand() {
this(null);
}
public XSiteOfflineStatusCommand(ByteString cacheName) {
this(cacheName, null);
}
public XSiteOfflineStatusCommand(ByteString cacheName, String siteName) {
super(cacheName);
this.siteName = siteName;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
TakeOfflineManager takeOfflineManager = registry.getTakeOfflineManager().running();
return CompletableFuture.completedFuture(takeOfflineManager.getSiteState(siteName) != SiteState.ONLINE);
}
@Override
public final boolean isReturnValueExpected() {
return true;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeUTF(siteName);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
siteName = input.readUTF();
}
@Override
public String toString() {
return "XSiteOfflineStatusCommand{" +
"siteName='" + siteName + '\'' +
'}';
}
}
| 1,971
| 25.293333
| 110
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.