Search in sources :

Example 1 with DistributionInfo

use of org.infinispan.distribution.DistributionInfo in project infinispan by infinispan.

the class FunctionalTxTest method testBeforeTopology.

private void testBeforeTopology(BiFunction<FunctionalMap.ReadWriteMap<String, Integer>, String, Integer> op, int expectedIncrement) throws Exception {
    cache(0).put("key", 1);
    // Blocking on receiver side. We cannot block the StateResponseCommand on the server side since
    // the InternalCacheEntries in its state are the same instances of data stored in DataContainer
    // - therefore when the command is blocked on sender the command itself would be mutated by applying
    // the transaction below.
    BlockingStateConsumer bsc2 = TestingUtil.wrapComponent(cache(2), StateConsumer.class, BlockingStateConsumer::new);
    tm(2).begin();
    FunctionalMap.ReadWriteMap<String, Integer> rw = ReadWriteMapImpl.create(FunctionalMapImpl.create(this.<String, Integer>cache(2).getAdvancedCache()));
    assertEquals(Integer.valueOf(1), op.apply(rw, "key"));
    Transaction tx = tm(2).suspend();
    chf.setOwnerIndexes(0, 2);
    EmbeddedCacheManager cm = createClusteredCacheManager(false, GlobalConfigurationBuilder.defaultClusteredBuilder(), cb, new TransportFlags());
    registerCacheManager(cm);
    Future<?> future = fork(() -> {
        cache(3);
    });
    bsc2.await();
    DistributionInfo distributionInfo = cache(2).getAdvancedCache().getDistributionManager().getCacheTopology().getDistribution("key");
    assertFalse(distributionInfo.isReadOwner());
    assertTrue(distributionInfo.isWriteBackup());
    tm(2).resume(tx);
    tm(2).commit();
    bsc2.unblock();
    future.get(10, TimeUnit.SECONDS);
    InternalCacheEntry<Object, Object> ice = cache(2).getAdvancedCache().getDataContainer().get("key");
    assertEquals("Current ICE: " + ice, 1 + expectedIncrement, ice.getValue());
}
Also used : Transaction(javax.transaction.Transaction) FunctionalMap(org.infinispan.functional.FunctionalMap) TransportFlags(org.infinispan.test.fwk.TransportFlags) EmbeddedCacheManager(org.infinispan.manager.EmbeddedCacheManager) DistributionInfo(org.infinispan.distribution.DistributionInfo)

Example 2 with DistributionInfo

use of org.infinispan.distribution.DistributionInfo in project infinispan by infinispan.

the class ClusteringInterceptor method visitTouchCommand.

@Override
public Object visitTouchCommand(InvocationContext ctx, TouchCommand command) throws Throwable {
    if (command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL | FlagBitSets.SKIP_REMOTE_LOOKUP)) {
        return invokeNext(ctx, command);
    }
    LocalizedCacheTopology cacheTopology = checkTopologyId(command);
    DistributionInfo info = cacheTopology.getSegmentDistribution(command.getSegment());
    // Scattered any node could be a backup, so we have to touch all members
    List<Address> owners = isScattered ? cacheTopology.getActualMembers() : info.readOwners();
    if (touchMode == TouchMode.ASYNC) {
        if (ctx.isOriginLocal()) {
            // Send to all the owners
            rpcManager.sendToMany(owners, command, DeliverOrder.NONE);
        }
        return invokeNext(ctx, command);
    }
    if (info.isPrimary()) {
        AbstractTouchResponseCollector collector = isScattered ? ScatteredTouchResponseCollector.INSTANCE : TouchResponseCollector.INSTANCE;
        CompletionStage<Boolean> remoteInvocation = rpcManager.invokeCommand(owners, command, collector, rpcManager.getSyncRpcOptions());
        return invokeNextThenApply(ctx, command, (rCtx, rCommand, rValue) -> {
            Boolean touchedLocally = (Boolean) rValue;
            if (touchedLocally) {
                return asyncValue(remoteInvocation);
            }
            // If primary can't touch - it doesn't matter about others
            return Boolean.FALSE;
        });
    } else if (ctx.isOriginLocal()) {
        // Send to the primary owner
        CompletionStage<ValidResponse> remoteInvocation = rpcManager.invokeCommand(info.primary(), command, SingleResponseCollector.validOnly(), rpcManager.getSyncRpcOptions());
        return asyncValue(remoteInvocation).thenApply(ctx, command, (rCtx, rCommand, rResponse) -> ((ValidResponse) rResponse).getResponseValue());
    }
    return invokeNext(ctx, command);
}
Also used : CacheNotFoundResponse(org.infinispan.remoting.responses.CacheNotFoundResponse) UnsureResponse(org.infinispan.remoting.responses.UnsureResponse) CompletableFuture(java.util.concurrent.CompletableFuture) AllOwnersLostException(org.infinispan.statetransfer.AllOwnersLostException) LockManager(org.infinispan.util.concurrent.locks.LockManager) FlagBitSets(org.infinispan.context.impl.FlagBitSets) InvocationContext(org.infinispan.context.InvocationContext) SingleResponseCollector(org.infinispan.remoting.transport.impl.SingleResponseCollector) OutdatedTopologyException(org.infinispan.statetransfer.OutdatedTopologyException) Map(java.util.Map) Address(org.infinispan.remoting.transport.Address) Response(org.infinispan.remoting.responses.Response) CommandsFactory(org.infinispan.commands.CommandsFactory) CacheException(org.infinispan.commons.CacheException) Iterator(java.util.Iterator) InternalDataContainer(org.infinispan.container.impl.InternalDataContainer) ValidResponseCollector(org.infinispan.remoting.transport.ValidResponseCollector) TouchMode(org.infinispan.expiration.TouchMode) ValidResponse(org.infinispan.remoting.responses.ValidResponse) EntryFactory(org.infinispan.container.impl.EntryFactory) Inject(org.infinispan.factories.annotations.Inject) Consumer(java.util.function.Consumer) List(java.util.List) TouchCommand(org.infinispan.expiration.impl.TouchCommand) CompletionStage(java.util.concurrent.CompletionStage) SuccessfulResponse(org.infinispan.remoting.responses.SuccessfulResponse) CLUSTER(org.infinispan.util.logging.Log.CLUSTER) LocalizedCacheTopology(org.infinispan.distribution.LocalizedCacheTopology) DistributionInfo(org.infinispan.distribution.DistributionInfo) DeliverOrder(org.infinispan.remoting.inboundhandler.DeliverOrder) FlagAffectedCommand(org.infinispan.commands.FlagAffectedCommand) TopologyAffectedCommand(org.infinispan.commands.TopologyAffectedCommand) DistributionManager(org.infinispan.distribution.DistributionManager) Address(org.infinispan.remoting.transport.Address) ValidResponse(org.infinispan.remoting.responses.ValidResponse) LocalizedCacheTopology(org.infinispan.distribution.LocalizedCacheTopology) DistributionInfo(org.infinispan.distribution.DistributionInfo) CompletionStage(java.util.concurrent.CompletionStage)

Example 3 with DistributionInfo

use of org.infinispan.distribution.DistributionInfo in project infinispan by infinispan.

the class ScatteredDistributionInterceptor method visitGetAllCommand.

@Override
public Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable {
    LocalizedCacheTopology cacheTopology = checkTopology(command);
    if (command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL | FlagBitSets.SKIP_REMOTE_LOOKUP | FlagBitSets.SKIP_OWNERSHIP_CHECK)) {
        return invokeNext(ctx, command);
    }
    if (ctx.isOriginLocal()) {
        Map<Address, List<Object>> remoteKeys = new HashMap<>();
        for (Object key : command.getKeys()) {
            if (ctx.lookupEntry(key) != null) {
                continue;
            }
            DistributionInfo info = cacheTopology.getDistribution(key);
            if (info.primary() == null) {
                throw OutdatedTopologyException.RETRY_NEXT_TOPOLOGY;
            } else if (!info.isPrimary()) {
                remoteKeys.computeIfAbsent(info.primary(), k -> new ArrayList<>()).add(key);
            }
        }
        if (remoteKeys.isEmpty()) {
            return invokeNext(ctx, command);
        }
        ClusteredGetAllFuture sync = new ClusteredGetAllFuture(remoteKeys.size());
        for (Map.Entry<Address, List<Object>> remote : remoteKeys.entrySet()) {
            List<Object> keys = remote.getValue();
            ClusteredGetAllCommand clusteredGetAllCommand = cf.buildClusteredGetAllCommand(keys, command.getFlagsBitSet(), null);
            clusteredGetAllCommand.setTopologyId(command.getTopologyId());
            SingletonMapResponseCollector collector = SingletonMapResponseCollector.ignoreLeavers();
            CompletionStage<Map<Address, Response>> rpcFuture = rpcManager.invokeCommand(remote.getKey(), clusteredGetAllCommand, collector, rpcManager.getSyncRpcOptions());
            rpcFuture.whenComplete(((responseMap, throwable) -> handleGetAllResponse(responseMap, throwable, ctx, keys, sync)));
        }
        return asyncInvokeNext(ctx, command, sync);
    } else {
        // remote
        for (Object key : command.getKeys()) {
            if (ctx.lookupEntry(key) == null) {
                return UnsureResponse.INSTANCE;
            }
        }
        return invokeNext(ctx, command);
    }
}
Also used : WriteCommand(org.infinispan.commands.write.WriteCommand) Arrays(java.util.Arrays) GetCacheEntryCommand(org.infinispan.commands.read.GetCacheEntryCommand) CacheNotFoundResponse(org.infinispan.remoting.responses.CacheNotFoundResponse) LogFactory(org.infinispan.util.logging.LogFactory) RemoteMetadata(org.infinispan.container.entries.RemoteMetadata) ClusteredGetAllCommand(org.infinispan.commands.remote.ClusteredGetAllCommand) Map(java.util.Map) RemoveCommand(org.infinispan.commands.write.RemoveCommand) ConsistentHash(org.infinispan.distribution.ch.ConsistentHash) EmbeddedMetadata(org.infinispan.metadata.EmbeddedMetadata) ReadWriteManyEntriesCommand(org.infinispan.commands.functional.ReadWriteManyEntriesCommand) UnsuccessfulResponse(org.infinispan.remoting.responses.UnsuccessfulResponse) Set(java.util.Set) GroupManager(org.infinispan.distribution.group.impl.GroupManager) CacheTopology(org.infinispan.topology.CacheTopology) ResponseCollector(org.infinispan.remoting.transport.ResponseCollector) DONT_LOAD(org.infinispan.commands.VisitableCommand.LoadType.DONT_LOAD) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) SuccessfulResponse(org.infinispan.remoting.responses.SuccessfulResponse) InternalCacheValue(org.infinispan.container.entries.InternalCacheValue) AbstractVisitor(org.infinispan.commands.AbstractVisitor) ArrayCollector(org.infinispan.commons.util.ArrayCollector) InternalCacheEntry(org.infinispan.container.entries.InternalCacheEntry) CacheEntryRemoved(org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved) PersistenceManager(org.infinispan.persistence.manager.PersistenceManager) ComputeCommand(org.infinispan.commands.write.ComputeCommand) MetadataAwareCommand(org.infinispan.commands.MetadataAwareCommand) EvictionManager(org.infinispan.eviction.EvictionManager) ReadOnlyKeyCommand(org.infinispan.commands.functional.ReadOnlyKeyCommand) ArrayList(java.util.ArrayList) WriteOnlyManyEntriesCommand(org.infinispan.commands.functional.WriteOnlyManyEntriesCommand) Start(org.infinispan.factories.annotations.Start) MapResponseCollector(org.infinispan.remoting.transport.impl.MapResponseCollector) PassthroughSingleResponseCollector(org.infinispan.remoting.transport.impl.PassthroughSingleResponseCollector) SingleResponseCollector(org.infinispan.remoting.transport.impl.SingleResponseCollector) DataWriteCommand(org.infinispan.commands.write.DataWriteCommand) FunctionalNotifier(org.infinispan.functional.impl.FunctionalNotifier) ValueMatcher(org.infinispan.commands.write.ValueMatcher) ClearCommand(org.infinispan.commands.write.ClearCommand) Address(org.infinispan.remoting.transport.Address) ExceptionResponse(org.infinispan.remoting.responses.ExceptionResponse) CacheEntry(org.infinispan.container.entries.CacheEntry) NotifyHelper(org.infinispan.notifications.cachelistener.NotifyHelper) WriteOnlyKeyValueCommand(org.infinispan.commands.functional.WriteOnlyKeyValueCommand) ValidResponse(org.infinispan.remoting.responses.ValidResponse) CacheNotifier(org.infinispan.notifications.cachelistener.CacheNotifier) Inject(org.infinispan.factories.annotations.Inject) ReadWriteKeyCommand(org.infinispan.commands.functional.ReadWriteKeyCommand) ReadWriteManyCommand(org.infinispan.commands.functional.ReadWriteManyCommand) NullCacheEntry(org.infinispan.container.entries.NullCacheEntry) AggregateCompletionStage(org.infinispan.util.concurrent.AggregateCompletionStage) ReplaceCommand(org.infinispan.commands.write.ReplaceCommand) EntryVersion(org.infinispan.container.versioning.EntryVersion) UnsureResponse(org.infinispan.remoting.responses.UnsureResponse) MultiTargetCollector(org.infinispan.util.concurrent.CommandAckCollector.MultiTargetCollector) GetKeysInGroupCommand(org.infinispan.commands.remote.GetKeysInGroupCommand) ActivationManager(org.infinispan.eviction.impl.ActivationManager) RepeatableReadEntry(org.infinispan.container.entries.RepeatableReadEntry) InvocationContext(org.infinispan.context.InvocationContext) CompletableFutures(org.infinispan.util.concurrent.CompletableFutures) OutdatedTopologyException(org.infinispan.statetransfer.OutdatedTopologyException) RpcOptions(org.infinispan.remoting.rpc.RpcOptions) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ReadWriteKeyValueCommand(org.infinispan.commands.functional.ReadWriteKeyValueCommand) MetadataImmortalCacheEntry(org.infinispan.container.entries.metadata.MetadataImmortalCacheEntry) DataOperationOrderer(org.infinispan.util.concurrent.DataOperationOrderer) InequalVersionComparisonResult(org.infinispan.container.versioning.InequalVersionComparisonResult) InvocationSuccessFunction(org.infinispan.interceptors.InvocationSuccessFunction) List(java.util.List) SingletonMapResponseCollector(org.infinispan.remoting.transport.impl.SingletonMapResponseCollector) InvocationFinallyAction(org.infinispan.interceptors.InvocationFinallyAction) PutKeyValueCommand(org.infinispan.commands.write.PutKeyValueCommand) FlagAffectedCommand(org.infinispan.commands.FlagAffectedCommand) TopologyAffectedCommand(org.infinispan.commands.TopologyAffectedCommand) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Metadata(org.infinispan.metadata.Metadata) CompletionStages(org.infinispan.util.concurrent.CompletionStages) GetAllCommand(org.infinispan.commands.read.GetAllCommand) Function(java.util.function.Function) AllOwnersLostException(org.infinispan.statetransfer.AllOwnersLostException) FlagBitSets(org.infinispan.context.impl.FlagBitSets) KeyPartitioner(org.infinispan.distribution.ch.KeyPartitioner) ClusteredGetCommand(org.infinispan.commands.remote.ClusteredGetCommand) IracPutKeyValueCommand(org.infinispan.commands.write.IracPutKeyValueCommand) Log(org.infinispan.util.logging.Log) AbstractDataCommand(org.infinispan.commands.read.AbstractDataCommand) SegmentSpecificCommand(org.infinispan.commands.SegmentSpecificCommand) MetadataImmortalCacheValue(org.infinispan.container.entries.metadata.MetadataImmortalCacheValue) ResponseCollectors(org.infinispan.remoting.transport.ResponseCollectors) Response(org.infinispan.remoting.responses.Response) ClusteringInterceptor(org.infinispan.interceptors.impl.ClusteringInterceptor) GetKeyValueCommand(org.infinispan.commands.read.GetKeyValueCommand) CacheException(org.infinispan.commons.CacheException) Iterator(java.util.Iterator) EvictCommand(org.infinispan.commands.write.EvictCommand) WriteOnlyManyCommand(org.infinispan.commands.functional.WriteOnlyManyCommand) PutMapCommand(org.infinispan.commands.write.PutMapCommand) ReadOnlyManyCommand(org.infinispan.commands.functional.ReadOnlyManyCommand) ComputeIfAbsentCommand(org.infinispan.commands.write.ComputeIfAbsentCommand) LocalizedCacheTopology(org.infinispan.distribution.LocalizedCacheTopology) Configuration(org.infinispan.configuration.cache.Configuration) DistributionInfo(org.infinispan.distribution.DistributionInfo) Operation(org.infinispan.util.concurrent.DataOperationOrderer.Operation) WriteOnlyKeyCommand(org.infinispan.commands.functional.WriteOnlyKeyCommand) VisitableCommand(org.infinispan.commands.VisitableCommand) DeliverOrder(org.infinispan.remoting.inboundhandler.DeliverOrder) Collections(java.util.Collections) TimeService(org.infinispan.commons.time.TimeService) ScatteredVersionManager(org.infinispan.scattered.ScatteredVersionManager) Address(org.infinispan.remoting.transport.Address) HashMap(java.util.HashMap) LocalizedCacheTopology(org.infinispan.distribution.LocalizedCacheTopology) DistributionInfo(org.infinispan.distribution.DistributionInfo) ClusteredGetAllCommand(org.infinispan.commands.remote.ClusteredGetAllCommand) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) HashMap(java.util.HashMap) SingletonMapResponseCollector(org.infinispan.remoting.transport.impl.SingletonMapResponseCollector)

Example 4 with DistributionInfo

use of org.infinispan.distribution.DistributionInfo in project infinispan by infinispan.

the class ScatteredDistributionInterceptor method handleWriteManyOnOrigin.

private <C extends WriteCommand, Container, Item> Object handleWriteManyOnOrigin(InvocationContext ctx, C command, WriteManyCommandHelper<C, Container, Item> helper) {
    LocalizedCacheTopology cacheTopology = checkTopology(command);
    Map<Address, Container> remoteEntries = new HashMap<>();
    for (Item item : helper.getItems(command)) {
        Object key = helper.item2key(item);
        DistributionInfo info = cacheTopology.getDistribution(key);
        Address primary = info.primary();
        if (primary == null) {
            throw AllOwnersLostException.INSTANCE;
        } else {
            Container currentEntries = remoteEntries.computeIfAbsent(primary, k -> helper.newContainer());
            helper.accumulate(currentEntries, item);
        }
    }
    Object[] results = command.loadType() == DONT_LOAD ? null : new Object[command.getAffectedKeys().size()];
    MergingCompletableFuture<Object> allFuture = new SyncMergingCompletableFuture<>(remoteEntries.size(), results, helper::transformResult);
    int offset = 0;
    Container localEntries = remoteEntries.remove(rpcManager.getAddress());
    if (localEntries != null) {
        helper.containerSize(localEntries);
        C localCommand = helper.copyForLocal(command, localEntries);
        localCommand.setTopologyId(command.getTopologyId());
        LocalWriteManyHandler handler = new LocalWriteManyHandler(allFuture, localCommand.getAffectedKeys(), cacheTopology);
        invokeNextAndFinally(ctx, localCommand, handler);
    }
    // This will be null in a non-biased variant
    MultiTargetCollector multiTargetCollector = createMultiTargetCollector(command, remoteEntries.size());
    for (Map.Entry<Address, Container> ownerEntry : remoteEntries.entrySet()) {
        Address owner = ownerEntry.getKey();
        // TODO: copyForLocal just creates the command with given entries, not using the segment-aware map
        Container container = ownerEntry.getValue();
        C toPrimary = helper.copyForLocal(command, container);
        toPrimary.setTopologyId(command.getTopologyId());
        CompletionStage<ValidResponse> rpcFuture = manyWriteOnRemotePrimary(owner, toPrimary, multiTargetCollector);
        int myOffset = offset;
        offset += helper.containerSize(container);
        rpcFuture.whenComplete((response, t) -> {
            if (t != null) {
                allFuture.completeExceptionally(t);
                return;
            }
            Object responseValue = response.getResponseValue();
            // Note: we could use PrimaryResponseHandler, but we would have to add the reference to allFuture, offset...
            InternalCacheValue[] values;
            try {
                if (command.loadType() == DONT_LOAD) {
                    if (!(responseValue instanceof InternalCacheValue[])) {
                        allFuture.completeExceptionally(new CacheException("Response from " + owner + ": expected InternalCacheValue[] but it is " + responseValue));
                        return;
                    }
                    values = (InternalCacheValue[]) responseValue;
                } else {
                    if (!(responseValue instanceof Object[]) || (((Object[]) responseValue).length != 2)) {
                        allFuture.completeExceptionally(new CacheException("Response from " + owner + ": expected Object[2] but it is " + responseValue));
                        return;
                    }
                    // We use Object[] { InternalCacheValue[], Object[] } structure to get benefit of same-type array marshalling
                    // TODO optimize returning entry itself
                    // Note: some interceptors relying on the return value *could* have a problem interpreting this
                    values = (InternalCacheValue[]) ((Object[]) responseValue)[0];
                    MergingCompletableFuture.moveListItemsToFuture(((Object[]) responseValue)[1], allFuture, myOffset);
                }
                AggregateCompletionStage<Void> aggregateCompletionStage = CompletionStages.aggregateCompletionStage();
                synchronized (allFuture) {
                    if (allFuture.isDone()) {
                        return;
                    }
                    int i = 0;
                    for (Object key : helper.toKeys(container)) {
                        // we will serve as the backup
                        InternalCacheEntry ice = values[i++].toInternalCacheEntry(key);
                        entryFactory.wrapExternalEntry(ctx, key, ice, true, true);
                        RepeatableReadEntry entry = (RepeatableReadEntry) ctx.lookupEntry(key);
                        // we don't care about setCreated() since backup owner should not fire listeners
                        entry.setChanged(true);
                        aggregateCompletionStage.dependsOn(commitSingleEntryIfNewer(entry, ctx, command));
                        if (entry.isCommitted() && !command.hasAnyFlag(FlagBitSets.PUT_FOR_STATE_TRANSFER)) {
                            scheduleKeyInvalidation(entry.getKey(), entry.getMetadata().version(), entry.isRemoved());
                        }
                    }
                    assert i == values.length;
                }
                aggregateCompletionStage.freeze().thenRun(allFuture::countDown);
            } catch (Throwable t2) {
                allFuture.completeExceptionally(t2);
            }
        });
    }
    return asyncValue(allFuture);
}
Also used : Address(org.infinispan.remoting.transport.Address) HashMap(java.util.HashMap) CacheException(org.infinispan.commons.CacheException) ValidResponse(org.infinispan.remoting.responses.ValidResponse) RepeatableReadEntry(org.infinispan.container.entries.RepeatableReadEntry) MultiTargetCollector(org.infinispan.util.concurrent.CommandAckCollector.MultiTargetCollector) LocalizedCacheTopology(org.infinispan.distribution.LocalizedCacheTopology) DistributionInfo(org.infinispan.distribution.DistributionInfo) InternalCacheValue(org.infinispan.container.entries.InternalCacheValue) InternalCacheEntry(org.infinispan.container.entries.InternalCacheEntry) Map(java.util.Map) HashMap(java.util.HashMap)

Example 5 with DistributionInfo

use of org.infinispan.distribution.DistributionInfo in project infinispan by infinispan.

the class BaseDistributionInterceptor method primaryReturnHandler.

protected Object primaryReturnHandler(InvocationContext ctx, AbstractDataWriteCommand command, Object localResult) {
    if (!command.isSuccessful()) {
        if (log.isTraceEnabled())
            log.tracef("Skipping the replication of the conditional command as it did not succeed on primary owner (%s).", command);
        return localResult;
    }
    LocalizedCacheTopology cacheTopology = checkTopologyId(command);
    int segment = SegmentSpecificCommand.extractSegment(command, command.getKey(), keyPartitioner);
    DistributionInfo distributionInfo = cacheTopology.getSegmentDistribution(segment);
    Collection<Address> owners = distributionInfo.writeOwners();
    if (owners.size() == 1) {
        // There are no backups, skip the replication part.
        return localResult;
    }
    // Cache the matcher and reset it if we get OOTE (or any other exception) from backup
    ValueMatcher originalMatcher = command.getValueMatcher();
    // Ignore the previous value on the backup owners
    command.setValueMatcher(ValueMatcher.MATCH_ALWAYS);
    if (!isSynchronous(command)) {
        if (isReplicated) {
            rpcManager.sendToAll(command, DeliverOrder.PER_SENDER);
        } else {
            rpcManager.sendToMany(owners, command, DeliverOrder.PER_SENDER);
        }
        // Switch to the retry policy, in case the primary owner changes before we commit locally
        command.setValueMatcher(originalMatcher.matcherForRetry());
        return localResult;
    }
    VoidResponseCollector collector = VoidResponseCollector.ignoreLeavers();
    RpcOptions rpcOptions = rpcManager.getSyncRpcOptions();
    // Mark the command as a backup write so it can skip some checks
    command.addFlags(FlagBitSets.BACKUP_WRITE);
    CompletionStage<Void> remoteInvocation = isReplicated ? rpcManager.invokeCommandOnAll(command, collector, rpcOptions) : rpcManager.invokeCommand(owners, command, collector, rpcOptions);
    return asyncValue(remoteInvocation.handle((ignored, t) -> {
        // Unset the backup write bit as the command will be retried
        command.setFlagsBitSet(command.getFlagsBitSet() & ~FlagBitSets.BACKUP_WRITE);
        // Switch to the retry policy, in case the primary owner changed and the write already succeeded on the new primary
        command.setValueMatcher(originalMatcher.matcherForRetry());
        CompletableFutures.rethrowExceptionIfPresent(t);
        return localResult;
    }));
}
Also used : WriteCommand(org.infinispan.commands.write.WriteCommand) Arrays(java.util.Arrays) GetCacheEntryCommand(org.infinispan.commands.read.GetCacheEntryCommand) CacheNotFoundResponse(org.infinispan.remoting.responses.CacheNotFoundResponse) LogFactory(org.infinispan.util.logging.LogFactory) UnsureResponse(org.infinispan.remoting.responses.UnsureResponse) GetKeysInGroupCommand(org.infinispan.commands.remote.GetKeysInGroupCommand) InvocationContext(org.infinispan.context.InvocationContext) CompletableFutures(org.infinispan.util.concurrent.CompletableFutures) TxInvocationContext(org.infinispan.context.impl.TxInvocationContext) OutdatedTopologyException(org.infinispan.statetransfer.OutdatedTopologyException) Map(java.util.Map) RpcOptions(org.infinispan.remoting.rpc.RpcOptions) ConsistentHash(org.infinispan.distribution.ch.ConsistentHash) Collection(java.util.Collection) InvocationSuccessFunction(org.infinispan.interceptors.InvocationSuccessFunction) ResponseCollector(org.infinispan.remoting.transport.ResponseCollector) List(java.util.List) SingletonMapResponseCollector(org.infinispan.remoting.transport.impl.SingletonMapResponseCollector) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) SuccessfulResponse(org.infinispan.remoting.responses.SuccessfulResponse) InternalCacheValue(org.infinispan.container.entries.InternalCacheValue) FlagAffectedCommand(org.infinispan.commands.FlagAffectedCommand) TopologyAffectedCommand(org.infinispan.commands.TopologyAffectedCommand) ArrayCollector(org.infinispan.commons.util.ArrayCollector) InternalCacheEntry(org.infinispan.container.entries.InternalCacheEntry) HashMap(java.util.HashMap) GetAllCommand(org.infinispan.commands.read.GetAllCommand) RemoteValueRetrievedListener(org.infinispan.distribution.RemoteValueRetrievedListener) Function(java.util.function.Function) ReadOnlyKeyCommand(org.infinispan.commands.functional.ReadOnlyKeyCommand) InternalExpirationManager(org.infinispan.expiration.impl.InternalExpirationManager) ArrayList(java.util.ArrayList) Start(org.infinispan.factories.annotations.Start) MapResponseCollector(org.infinispan.remoting.transport.impl.MapResponseCollector) FlagBitSets(org.infinispan.context.impl.FlagBitSets) AbstractDataWriteCommand(org.infinispan.commands.write.AbstractDataWriteCommand) KeyPartitioner(org.infinispan.distribution.ch.KeyPartitioner) SingleResponseCollector(org.infinispan.remoting.transport.impl.SingleResponseCollector) ClusteredGetCommand(org.infinispan.commands.remote.ClusteredGetCommand) Log(org.infinispan.util.logging.Log) BiConsumer(java.util.function.BiConsumer) VoidResponseCollector(org.infinispan.remoting.transport.impl.VoidResponseCollector) AbstractDataCommand(org.infinispan.commands.read.AbstractDataCommand) SegmentSpecificCommand(org.infinispan.commands.SegmentSpecificCommand) DataWriteCommand(org.infinispan.commands.write.DataWriteCommand) ValueMatcher(org.infinispan.commands.write.ValueMatcher) ClearCommand(org.infinispan.commands.write.ClearCommand) Address(org.infinispan.remoting.transport.Address) ExceptionResponse(org.infinispan.remoting.responses.ExceptionResponse) Response(org.infinispan.remoting.responses.Response) ClusteringInterceptor(org.infinispan.interceptors.impl.ClusteringInterceptor) ReplicableCommand(org.infinispan.commands.ReplicableCommand) GetKeyValueCommand(org.infinispan.commands.read.GetKeyValueCommand) CacheEntry(org.infinispan.container.entries.CacheEntry) ValidResponse(org.infinispan.remoting.responses.ValidResponse) Inject(org.infinispan.factories.annotations.Inject) ReadOnlyManyCommand(org.infinispan.commands.functional.ReadOnlyManyCommand) LocalizedCacheTopology(org.infinispan.distribution.LocalizedCacheTopology) GlobalTransaction(org.infinispan.transaction.xa.GlobalTransaction) DistributionInfo(org.infinispan.distribution.DistributionInfo) VisitableCommand(org.infinispan.commands.VisitableCommand) DeliverOrder(org.infinispan.remoting.inboundhandler.DeliverOrder) Collections(java.util.Collections) BaseClusteredReadCommand(org.infinispan.commands.remote.BaseClusteredReadCommand) TimeService(org.infinispan.commons.time.TimeService) NullCacheEntry(org.infinispan.container.entries.NullCacheEntry) RpcOptions(org.infinispan.remoting.rpc.RpcOptions) Address(org.infinispan.remoting.transport.Address) ValueMatcher(org.infinispan.commands.write.ValueMatcher) VoidResponseCollector(org.infinispan.remoting.transport.impl.VoidResponseCollector) LocalizedCacheTopology(org.infinispan.distribution.LocalizedCacheTopology) DistributionInfo(org.infinispan.distribution.DistributionInfo)

Aggregations

DistributionInfo (org.infinispan.distribution.DistributionInfo)37 LocalizedCacheTopology (org.infinispan.distribution.LocalizedCacheTopology)21 HashMap (java.util.HashMap)14 Address (org.infinispan.remoting.transport.Address)13 CompletionStage (java.util.concurrent.CompletionStage)11 InternalCacheEntry (org.infinispan.container.entries.InternalCacheEntry)11 Map (java.util.Map)10 CacheEntry (org.infinispan.container.entries.CacheEntry)10 Collection (java.util.Collection)8 NullCacheEntry (org.infinispan.container.entries.NullCacheEntry)8 Inject (org.infinispan.factories.annotations.Inject)8 Function (java.util.function.Function)7 InternalCacheValue (org.infinispan.container.entries.InternalCacheValue)7 DeliverOrder (org.infinispan.remoting.inboundhandler.DeliverOrder)7 ValidResponse (org.infinispan.remoting.responses.ValidResponse)7 RpcOptions (org.infinispan.remoting.rpc.RpcOptions)7 CompletableFutures (org.infinispan.util.concurrent.CompletableFutures)7 Log (org.infinispan.util.logging.Log)7 LogFactory (org.infinispan.util.logging.LogFactory)7 List (java.util.List)6