Search in sources :

Example 16 with GridDhtPartitionTopology

use of org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology in project ignite by apache.

the class GridDhtPartitionDemander method handleSupplyMessage.

/**
 * Handles supply message from {@code nodeId} with specified {@code topicId}.
 *
 * Supply message contains entries to populate rebalancing partitions.
 *
 * There is a cyclic process:
 * Populate rebalancing partitions with entries from Supply message.
 * If not all partitions specified in {@link #rebalanceFut} were rebalanced or marked as missed
 * send new Demand message to request next batch of entries.
 *
 * @param nodeId Node id.
 * @param supplyMsg Supply message.
 */
public void handleSupplyMessage(final UUID nodeId, final GridDhtPartitionSupplyMessage supplyMsg) {
    AffinityTopologyVersion topVer = supplyMsg.topologyVersion();
    RebalanceFuture fut = rebalanceFut;
    ClusterNode node = ctx.node(nodeId);
    fut.cancelLock.readLock().lock();
    try {
        String errMsg = null;
        if (fut.isDone())
            errMsg = "rebalance completed";
        else if (node == null)
            errMsg = "supplier has left cluster";
        else if (!rebalanceFut.isActual(supplyMsg.rebalanceId()))
            errMsg = "topology changed";
        if (errMsg != null) {
            if (log.isDebugEnabled()) {
                log.debug("Supply message has been ignored (" + errMsg + ") [" + demandRoutineInfo(nodeId, supplyMsg) + ']');
            }
            return;
        }
        if (log.isDebugEnabled())
            log.debug("Received supply message [" + demandRoutineInfo(nodeId, supplyMsg) + ']');
        // Check whether there were error during supplying process.
        Throwable msgExc = null;
        final GridDhtPartitionTopology top = grp.topology();
        if (supplyMsg.classError() != null)
            msgExc = supplyMsg.classError();
        else if (supplyMsg.error() != null)
            msgExc = supplyMsg.error();
        if (msgExc != null) {
            GridDhtPartitionMap partMap = top.localPartitionMap();
            Set<Integer> unstableParts = supplyMsg.infos().keySet().stream().filter(p -> partMap.get(p) == MOVING).collect(Collectors.toSet());
            U.error(log, "Rebalancing routine has failed, some partitions could be unavailable for reading" + " [" + demandRoutineInfo(nodeId, supplyMsg) + ", unavailablePartitions=" + S.compact(unstableParts) + ']', msgExc);
            fut.error(nodeId);
            return;
        }
        fut.receivedBytes.addAndGet(supplyMsg.messageSize());
        if (grp.sharedGroup()) {
            for (GridCacheContext cctx : grp.caches()) {
                if (cctx.statisticsEnabled()) {
                    long keysCnt = supplyMsg.keysForCache(cctx.cacheId());
                    if (keysCnt != -1)
                        cctx.cache().metrics0().onRebalancingKeysCountEstimateReceived(keysCnt);
                    // Can not be calculated per cache.
                    cctx.cache().metrics0().onRebalanceBatchReceived(supplyMsg.messageSize());
                }
            }
        } else {
            GridCacheContext cctx = grp.singleCacheContext();
            if (cctx.statisticsEnabled()) {
                if (supplyMsg.estimatedKeysCount() != -1)
                    cctx.cache().metrics0().onRebalancingKeysCountEstimateReceived(supplyMsg.estimatedKeysCount());
                cctx.cache().metrics0().onRebalanceBatchReceived(supplyMsg.messageSize());
            }
        }
        try {
            AffinityAssignment aff = grp.affinity().cachedAffinity(topVer);
            // Preload.
            for (Map.Entry<Integer, CacheEntryInfoCollection> e : supplyMsg.infos().entrySet()) {
                int p = e.getKey();
                if (aff.get(p).contains(ctx.localNode())) {
                    GridDhtLocalPartition part;
                    try {
                        part = top.localPartition(p, topVer, true);
                    } catch (GridDhtInvalidPartitionException err) {
                        assert !topVer.equals(top.lastTopologyChangeVersion());
                        if (log.isDebugEnabled()) {
                            log.debug("Failed to get partition for rebalancing [" + "grp=" + grp.cacheOrGroupName() + ", err=" + err + ", p=" + p + ", topVer=" + topVer + ", lastTopVer=" + top.lastTopologyChangeVersion() + ']');
                        }
                        continue;
                    }
                    assert part != null;
                    boolean last = supplyMsg.last().containsKey(p);
                    if (part.state() == MOVING) {
                        boolean reserved = part.reserve();
                        assert reserved : "Failed to reserve partition [igniteInstanceName=" + ctx.igniteInstanceName() + ", grp=" + grp.cacheOrGroupName() + ", part=" + part + ']';
                        part.beforeApplyBatch(last);
                        try {
                            long[] byteRcv = { 0 };
                            GridIterableAdapter<GridCacheEntryInfo> infosWrap = new GridIterableAdapter<>(new IteratorWrapper<GridCacheEntryInfo>(e.getValue().infos().iterator()) {

                                /**
                                 * {@inheritDoc}
                                 */
                                @Override
                                public GridCacheEntryInfo nextX() throws IgniteCheckedException {
                                    GridCacheEntryInfo i = super.nextX();
                                    byteRcv[0] += i.marshalledSize(ctx.cacheObjectContext(i.cacheId()));
                                    return i;
                                }
                            });
                            try {
                                if (grp.mvccEnabled())
                                    mvccPreloadEntries(topVer, node, p, infosWrap);
                                else {
                                    preloadEntries(topVer, part, infosWrap);
                                    rebalanceFut.onReceivedKeys(p, e.getValue().infos().size(), node);
                                }
                            } catch (GridDhtInvalidPartitionException ignored) {
                                if (log.isDebugEnabled())
                                    log.debug("Partition became invalid during rebalancing (will ignore): " + p);
                            }
                            fut.processed.get(p).increment();
                            fut.onReceivedBytes(p, byteRcv[0], node);
                            // If message was last for this partition, then we take ownership.
                            if (last)
                                ownPartition(fut, p, nodeId, supplyMsg);
                        } finally {
                            part.release();
                        }
                    } else {
                        if (last)
                            fut.partitionDone(nodeId, p, false);
                        if (log.isDebugEnabled())
                            log.debug("Skipping rebalancing partition (state is not MOVING): " + '[' + demandRoutineInfo(nodeId, supplyMsg) + ", p=" + p + ']');
                    }
                } else {
                    fut.partitionDone(nodeId, p, false);
                    if (log.isDebugEnabled())
                        log.debug("Skipping rebalancing partition (affinity changed): " + '[' + demandRoutineInfo(nodeId, supplyMsg) + ", p=" + p + ']');
                }
            }
            // Only request partitions based on latest topology version.
            for (Integer miss : supplyMsg.missed()) {
                if (aff.get(miss).contains(ctx.localNode()))
                    fut.partitionMissed(nodeId, miss);
            }
            for (Integer miss : supplyMsg.missed()) fut.partitionDone(nodeId, miss, false);
            GridDhtPartitionDemandMessage d = new GridDhtPartitionDemandMessage(supplyMsg.rebalanceId(), supplyMsg.topologyVersion(), grp.groupId());
            d.timeout(grp.preloader().timeout());
            if (!fut.isDone()) {
                // Send demand message.
                try {
                    ctx.io().sendOrderedMessage(node, d.topic(), d.convertIfNeeded(node.version()), grp.ioPolicy(), grp.preloader().timeout());
                    if (log.isDebugEnabled())
                        log.debug("Send next demand message [" + demandRoutineInfo(nodeId, supplyMsg) + "]");
                } catch (ClusterTopologyCheckedException e) {
                    if (log.isDebugEnabled())
                        log.debug("Supplier has left [" + demandRoutineInfo(nodeId, supplyMsg) + ", errMsg=" + e.getMessage() + ']');
                }
            } else {
                if (log.isDebugEnabled())
                    log.debug("Will not request next demand message [" + demandRoutineInfo(nodeId, supplyMsg) + ", rebalanceFuture=" + fut + ']');
            }
        } catch (IgniteSpiException | IgniteCheckedException e) {
            fut.error(nodeId);
            LT.error(log, e, "Error during rebalancing [" + demandRoutineInfo(nodeId, supplyMsg) + ", err=" + e + ']');
        }
    } finally {
        fut.cancelLock.readLock().unlock();
    }
}
Also used : IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) Collectors.counting(java.util.stream.Collectors.counting) IteratorWrapper(org.apache.ignite.internal.util.lang.GridIterableAdapter.IteratorWrapper) CacheRebalanceMode(org.apache.ignite.cache.CacheRebalanceMode) EVT_CACHE_REBALANCE_STARTED(org.apache.ignite.events.EventType.EVT_CACHE_REBALANCE_STARTED) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) EVT_CACHE_REBALANCE_STOPPED(org.apache.ignite.events.EventType.EVT_CACHE_REBALANCE_STOPPED) EVT_CACHE_REBALANCE_PART_LOADED(org.apache.ignite.events.EventType.EVT_CACHE_REBALANCE_PART_LOADED) MetricUtils.metricName(org.apache.ignite.internal.processors.metric.impl.MetricUtils.metricName) Collectors.toSet(java.util.stream.Collectors.toSet) CACHE_GROUP_METRICS_PREFIX(org.apache.ignite.internal.processors.cache.CacheGroupMetricsImpl.CACHE_GROUP_METRICS_PREFIX) GridCacheEntryInfo(org.apache.ignite.internal.processors.cache.GridCacheEntryInfo) IgniteInClosure(org.apache.ignite.lang.IgniteInClosure) AtomicReferenceFieldUpdater(java.util.concurrent.atomic.AtomicReferenceFieldUpdater) GridToStringExclude(org.apache.ignite.internal.util.tostring.GridToStringExclude) Collection(java.util.Collection) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) DR_PRELOAD(org.apache.ignite.internal.processors.dr.GridDrType.DR_PRELOAD) Set(java.util.Set) NavigableSet(java.util.NavigableSet) UUID(java.util.UUID) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) Collectors(java.util.stream.Collectors) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) Stream(java.util.stream.Stream) GridDhtPartitionTopology(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology) CU(org.apache.ignite.internal.util.typedef.internal.CU) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) IntHashMap(org.apache.ignite.internal.util.collection.IntHashMap) Objects.nonNull(java.util.Objects.nonNull) GridCacheEntryEx(org.apache.ignite.internal.processors.cache.GridCacheEntryEx) EVT_CACHE_REBALANCE_OBJECT_LOADED(org.apache.ignite.events.EventType.EVT_CACHE_REBALANCE_OBJECT_LOADED) GridCachePartitionExchangeManager(org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager) LongAdder(java.util.concurrent.atomic.LongAdder) DR_NONE(org.apache.ignite.internal.processors.dr.GridDrType.DR_NONE) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) Collectors.partitioningBy(java.util.stream.Collectors.partitioningBy) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) CacheEntryInfoCollection(org.apache.ignite.internal.processors.cache.CacheEntryInfoCollection) CheckpointProgress(org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointProgress) GridCompoundFuture(org.apache.ignite.internal.util.future.GridCompoundFuture) IgnitePredicateX(org.apache.ignite.internal.util.lang.IgnitePredicateX) U(org.apache.ignite.internal.util.typedef.internal.U) HashMap(java.util.HashMap) IgniteLogger(org.apache.ignite.IgniteLogger) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) AtomicReference(java.util.concurrent.atomic.AtomicReference) CacheGroupContext(org.apache.ignite.internal.processors.cache.CacheGroupContext) LT(org.apache.ignite.internal.util.typedef.internal.LT) ArrayList(java.util.ArrayList) AffinityAssignment(org.apache.ignite.internal.processors.affinity.AffinityAssignment) HashSet(java.util.HashSet) ClusterNode(org.apache.ignite.cluster.ClusterNode) CI1(org.apache.ignite.internal.util.typedef.CI1) GridTimeoutObjectAdapter(org.apache.ignite.internal.processors.timeout.GridTimeoutObjectAdapter) S(org.apache.ignite.internal.util.typedef.internal.S) MOVING(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionState.MOVING) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) PAGE_SNAPSHOT_TAKEN(org.apache.ignite.internal.processors.cache.persistence.CheckpointState.PAGE_SNAPSHOT_TAKEN) FINISHED(org.apache.ignite.internal.processors.cache.persistence.CheckpointState.FINISHED) F(org.apache.ignite.internal.util.typedef.F) GridIterableAdapter(org.apache.ignite.internal.util.lang.GridIterableAdapter) Iterator(java.util.Iterator) GridTimeoutObject(org.apache.ignite.internal.processors.timeout.GridTimeoutObject) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) TTL_ETERNAL(org.apache.ignite.internal.processors.cache.GridCacheUtils.TTL_ETERNAL) GridMutableLong(org.apache.ignite.internal.util.GridMutableLong) GridDhtInvalidPartitionException(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtInvalidPartitionException) MetricRegistry(org.apache.ignite.internal.processors.metric.MetricRegistry) GridToStringInclude(org.apache.ignite.internal.util.tostring.GridToStringInclude) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) GridDhtLocalPartition(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtLocalPartition) GridCacheSharedContext(org.apache.ignite.internal.processors.cache.GridCacheSharedContext) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) WalStateManager(org.apache.ignite.internal.processors.cache.WalStateManager) GridPlainRunnable(org.apache.ignite.internal.util.lang.GridPlainRunnable) CacheMetricsImpl(org.apache.ignite.internal.processors.cache.CacheMetricsImpl) GridCacheMvccEntryInfo(org.apache.ignite.internal.processors.cache.GridCacheMvccEntryInfo) Collections(java.util.Collections) TxState(org.apache.ignite.internal.processors.cache.mvcc.txlog.TxState) PRELOAD_SIZE_UNDER_CHECKPOINT_LOCK(org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManagerImpl.PRELOAD_SIZE_UNDER_CHECKPOINT_LOCK) AffinityAssignment(org.apache.ignite.internal.processors.affinity.AffinityAssignment) GridDhtPartitionTopology(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) CacheEntryInfoCollection(org.apache.ignite.internal.processors.cache.CacheEntryInfoCollection) GridDhtLocalPartition(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtLocalPartition) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) ClusterNode(org.apache.ignite.cluster.ClusterNode) GridCacheEntryInfo(org.apache.ignite.internal.processors.cache.GridCacheEntryInfo) GridDhtInvalidPartitionException(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtInvalidPartitionException) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) GridIterableAdapter(org.apache.ignite.internal.util.lang.GridIterableAdapter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IntHashMap(org.apache.ignite.internal.util.collection.IntHashMap) HashMap(java.util.HashMap) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)

Example 17 with GridDhtPartitionTopology

use of org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology in project ignite by apache.

the class GridDhtAtomicCache method update.

/**
 * @param node Node.
 * @param locked Entries.
 * @param req Request.
 * @param res Response.
 * @param dhtUpdRes DHT update result
 * @param taskName Task name.
 * @return Operation result.
 * @throws GridCacheEntryRemovedException If got obsolete entry.
 */
private DhtAtomicUpdateResult update(ClusterNode node, List<GridDhtCacheEntry> locked, GridNearAtomicAbstractUpdateRequest req, GridNearAtomicUpdateResponse res, DhtAtomicUpdateResult dhtUpdRes, String taskName) throws GridCacheEntryRemovedException {
    GridDhtPartitionTopology top = topology();
    boolean hasNear = req.nearCache();
    // Assign next version for update inside entries lock.
    GridCacheVersion ver = dhtUpdRes.dhtFuture() != null ? /*retry*/
    dhtUpdRes.dhtFuture().writeVer : nextVersion();
    if (hasNear)
        res.nearVersion(ver);
    if (msgLog.isDebugEnabled()) {
        msgLog.debug("Assigned update version [futId=" + req.futureId() + ", writeVer=" + ver + ']');
    }
    assert ver != null : "Got null version for update request: " + req;
    boolean sndPrevVal = !top.rebalanceFinished(req.topologyVersion());
    if (dhtUpdRes.dhtFuture() == null)
        dhtUpdRes.dhtFuture(createDhtFuture(ver, req));
    IgniteCacheExpiryPolicy expiry = expiryPolicy(req.expiry());
    GridCacheReturn retVal = null;
    if (// Several keys ...
    req.size() > 1 && writeThrough() && // and store is enabled ...
    !req.skipStore() && // and this is not local store ...
    !ctx.store().isLocal() && // (conflict resolver should be used for local store)
    !// and no DR.
    ctx.dr().receiveEnabled()) {
        // This method can only be used when there are no replicated entries in the batch.
        updateWithBatch(node, hasNear, req, res, locked, ver, ctx.isDrEnabled(), taskName, expiry, sndPrevVal, dhtUpdRes);
        if (req.operation() == TRANSFORM)
            retVal = dhtUpdRes.returnValue();
    } else {
        updateSingle(node, hasNear, req, res, locked, ver, ctx.isDrEnabled(), taskName, expiry, sndPrevVal, dhtUpdRes);
        retVal = dhtUpdRes.returnValue();
    }
    GridDhtAtomicAbstractUpdateFuture dhtFut = dhtUpdRes.dhtFuture();
    if (retVal == null)
        retVal = new GridCacheReturn(ctx, node.isLocal(), true, null, null, true);
    res.returnValue(retVal);
    if (dhtFut != null) {
        if (req.writeSynchronizationMode() == PRIMARY_SYNC && // To avoid deadlock disable back-pressure for sender data node.
        !ctx.discovery().cacheGroupAffinityNode(node, ctx.groupId()) && !dhtFut.isDone()) {
            final IgniteRunnable tracker = GridNioBackPressureControl.threadTracker();
            if (tracker instanceof GridNioMessageTracker) {
                ((GridNioMessageTracker) tracker).onMessageReceived();
                dhtFut.listen(new IgniteInClosure<IgniteInternalFuture<Void>>() {

                    @Override
                    public void apply(IgniteInternalFuture<Void> fut) {
                        ((GridNioMessageTracker) tracker).onMessageProcessed();
                    }
                });
            }
        }
        ctx.mvcc().addAtomicFuture(dhtFut.id(), dhtFut);
    }
    dhtUpdRes.expiryPolicy(expiry);
    return dhtUpdRes;
}
Also used : GridCacheReturn(org.apache.ignite.internal.processors.cache.GridCacheReturn) GridDhtPartitionTopology(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) GridNioMessageTracker(org.apache.ignite.internal.util.nio.GridNioMessageTracker) IgniteRunnable(org.apache.ignite.lang.IgniteRunnable) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) IgniteCacheExpiryPolicy(org.apache.ignite.internal.processors.cache.IgniteCacheExpiryPolicy)

Example 18 with GridDhtPartitionTopology

use of org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology in project ignite by apache.

the class PlatformCache method getLocalPartition.

/**
 * Gets local partition.
 *
 * @param part Partition id.
 * @return Partition when local, null otherwise.
 */
private GridDhtLocalPartition getLocalPartition(int part) throws IgniteCheckedException {
    GridCacheContext cctx = cache.context();
    if (part < 0 || part >= cctx.affinity().partitions())
        throw new IgniteCheckedException("Invalid partition number: " + part);
    GridDhtPartitionTopology top = cctx.topology();
    AffinityTopologyVersion ver = top.readyTopologyVersion();
    return top.localPartition(part, ver, false);
}
Also used : GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridDhtPartitionTopology(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)

Example 19 with GridDhtPartitionTopology

use of org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology in project ignite by apache.

the class ClientCreateCacheGroupOnJoinNodeMapsTest method testNodeMapsVolatile.

/**
 */
@Test
public void testNodeMapsVolatile() throws Exception {
    final IgniteEx srv = startGrids(2);
    srv.cluster().active(true);
    awaitPartitionMapExchange();
    final IgniteEx client = startGrid("client");
    final GridDhtPartitionTopology top0 = grid(0).cachex(DEFAULT_CACHE_NAME).context().topology();
    final GridDhtPartitionTopology top1 = grid(1).cachex(DEFAULT_CACHE_NAME).context().topology();
    GridDhtPartitionFullMap map0 = U.field(top0, "node2part");
    GridDhtPartitionFullMap map1 = U.field(top1, "node2part");
    assertEquals(2, map0.size());
    assertEquals(2, map1.size());
    srv.cluster().active(false);
}
Also used : GridDhtPartitionTopology(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology) IgniteEx(org.apache.ignite.internal.IgniteEx) GridDhtPartitionFullMap(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionFullMap) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 20 with GridDhtPartitionTopology

use of org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology in project ignite by apache.

the class GridDhtTransactionalCacheAdapter method lockAllAsync.

/**
 * @param cacheCtx Cache context.
 * @param nearNode Near node.
 * @param req Request.
 * @param filter0 Filter.
 * @return Future.
 */
public IgniteInternalFuture<GridNearLockResponse> lockAllAsync(final GridCacheContext<?, ?> cacheCtx, final ClusterNode nearNode, final GridNearLockRequest req, @Nullable final CacheEntryPredicate[] filter0) {
    final List<KeyCacheObject> keys = req.keys();
    CacheEntryPredicate[] filter = filter0;
    // Set message into thread context.
    GridDhtTxLocal tx = null;
    try {
        int cnt = keys.size();
        if (req.inTx()) {
            GridCacheVersion dhtVer = ctx.tm().mappedVersion(req.version());
            if (dhtVer != null)
                tx = ctx.tm().tx(dhtVer);
        }
        final List<GridCacheEntryEx> entries = new ArrayList<>(cnt);
        // Unmarshal filter first.
        if (filter == null)
            filter = req.filter();
        GridDhtLockFuture fut = null;
        GridDhtPartitionTopology top = null;
        if (req.firstClientRequest()) {
            assert nearNode.isClient();
            top = topology();
            top.readLock();
            if (!top.topologyVersionFuture().isDone()) {
                top.readUnlock();
                return null;
            }
        }
        try {
            if (top != null && needRemap(req.topologyVersion(), top.readyTopologyVersion())) {
                if (log.isDebugEnabled()) {
                    log.debug("Client topology version mismatch, need remap lock request [" + "reqTopVer=" + req.topologyVersion() + ", locTopVer=" + top.readyTopologyVersion() + ", req=" + req + ']');
                }
                GridNearLockResponse res = sendClientLockRemapResponse(nearNode, req, top.lastTopologyChangeVersion());
                return new GridFinishedFuture<>(res);
            }
            if (req.inTx()) {
                if (tx == null) {
                    tx = new GridDhtTxLocal(ctx.shared(), topology().readyTopologyVersion(), nearNode.id(), req.version(), req.futureId(), req.miniId(), req.threadId(), /*implicitTx*/
                    false, /*implicitSingleTx*/
                    false, ctx.systemTx(), false, ctx.ioPolicy(), PESSIMISTIC, req.isolation(), req.timeout(), req.isInvalidate(), !req.skipStore(), false, req.txSize(), null, securitySubjectId(ctx), req.taskNameHash(), req.txLabel(), null);
                    if (req.syncCommit())
                        tx.syncMode(FULL_SYNC);
                    tx = ctx.tm().onCreated(null, tx);
                    if (tx == null || !tx.init()) {
                        String msg = "Failed to acquire lock (transaction has been completed): " + req.version();
                        U.warn(log, msg);
                        if (tx != null)
                            tx.rollbackDhtLocal();
                        return new GridDhtFinishedFuture<>(new IgniteTxRollbackCheckedException(msg));
                    }
                    tx.topologyVersion(req.topologyVersion());
                }
                GridDhtPartitionsExchangeFuture lastFinishedFut = ctx.shared().exchange().lastFinishedFuture();
                CacheOperationContext opCtx = ctx.operationContextPerCall();
                CacheInvalidStateException validateCacheE = lastFinishedFut.validateCache(ctx, opCtx != null && opCtx.recovery(), req.txRead(), null, keys);
                if (validateCacheE != null)
                    throw validateCacheE;
            } else {
                fut = new GridDhtLockFuture(ctx, nearNode.id(), req.version(), req.topologyVersion(), cnt, req.txRead(), req.needReturnValue(), req.timeout(), tx, req.threadId(), req.createTtl(), req.accessTtl(), filter, req.skipStore(), req.keepBinary());
                // Add before mapping.
                if (!ctx.mvcc().addFuture(fut))
                    throw new IllegalStateException("Duplicate future ID: " + fut);
            }
        } finally {
            if (top != null)
                top.readUnlock();
        }
        boolean timedOut = false;
        for (KeyCacheObject key : keys) {
            if (timedOut)
                break;
            while (true) {
                // Specify topology version to make sure containment is checked
                // based on the requested version, not the latest.
                GridDhtCacheEntry entry = entryExx(key, req.topologyVersion());
                try {
                    if (fut != null) {
                        // This method will add local candidate.
                        // Entry cannot become obsolete after this method succeeded.
                        fut.addEntry(key == null ? null : entry);
                        if (fut.isDone()) {
                            timedOut = true;
                            break;
                        }
                    }
                    entries.add(entry);
                    break;
                } catch (GridCacheEntryRemovedException ignore) {
                    if (log.isDebugEnabled())
                        log.debug("Got removed entry when adding lock (will retry): " + entry);
                } catch (GridDistributedLockCancelledException e) {
                    if (log.isDebugEnabled())
                        log.debug("Got lock request for cancelled lock (will ignore): " + entry);
                    fut.onError(e);
                    return new GridDhtFinishedFuture<>(e);
                }
            }
        }
        // Handle implicit locks for pessimistic transactions.
        if (req.inTx()) {
            ctx.tm().txContext(tx);
            if (log.isDebugEnabled())
                log.debug("Performing DHT lock [tx=" + tx + ", entries=" + entries + ']');
            IgniteInternalFuture<GridCacheReturn> txFut = tx.lockAllAsync(cacheCtx, entries, req.messageId(), req.txRead(), req.needReturnValue(), req.createTtl(), req.accessTtl(), req.skipStore(), req.keepBinary(), req.nearCache());
            final GridDhtTxLocal t = tx;
            return new GridDhtEmbeddedFuture(txFut, new C2<GridCacheReturn, Exception, IgniteInternalFuture<GridNearLockResponse>>() {

                @Override
                public IgniteInternalFuture<GridNearLockResponse> apply(GridCacheReturn o, Exception e) {
                    if (e != null)
                        e = U.unwrap(e);
                    // Transaction can be emptied by asynchronous rollback.
                    assert e != null || !t.empty();
                    // Create response while holding locks.
                    final GridNearLockResponse resp = createLockReply(nearNode, entries, req, t, t.xidVersion(), e);
                    assert !t.implicit() : t;
                    assert !t.onePhaseCommit() : t;
                    sendLockReply(nearNode, t, req, resp);
                    return new GridFinishedFuture<>(resp);
                }
            });
        } else {
            assert fut != null;
            // This will send remote messages.
            fut.map();
            final GridCacheVersion mappedVer = fut.version();
            return new GridDhtEmbeddedFuture<>(new C2<Boolean, Exception, GridNearLockResponse>() {

                @Override
                public GridNearLockResponse apply(Boolean b, Exception e) {
                    if (e != null)
                        e = U.unwrap(e);
                    else if (!b)
                        e = new GridCacheLockTimeoutException(req.version());
                    GridNearLockResponse res = createLockReply(nearNode, entries, req, null, mappedVer, e);
                    sendLockReply(nearNode, null, req, res);
                    return res;
                }
            }, fut);
        }
    } catch (IgniteCheckedException | RuntimeException e) {
        U.error(log, req, e);
        if (tx != null) {
            try {
                tx.rollbackDhtLocal();
            } catch (IgniteCheckedException ex) {
                U.error(log, "Failed to rollback the transaction: " + tx, ex);
            }
        }
        try {
            GridNearLockResponse res = createLockReply(nearNode, Collections.emptyList(), req, tx, tx != null ? tx.xidVersion() : req.version(), e);
            sendLockReply(nearNode, null, req, res);
        } catch (Exception ex) {
            U.error(log, "Failed to send response for request message: " + req, ex);
        }
        return new GridDhtFinishedFuture<>(new IgniteCheckedException(e));
    }
}
Also used : GridDhtPartitionTopology(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology) CacheOperationContext(org.apache.ignite.internal.processors.cache.CacheOperationContext) GridDistributedLockCancelledException(org.apache.ignite.internal.processors.cache.distributed.GridDistributedLockCancelledException) ArrayList(java.util.ArrayList) GridNearLockResponse(org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockResponse) GridCacheLockTimeoutException(org.apache.ignite.internal.processors.cache.GridCacheLockTimeoutException) IgniteTxRollbackCheckedException(org.apache.ignite.internal.transactions.IgniteTxRollbackCheckedException) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) CacheInvalidStateException(org.apache.ignite.internal.processors.cache.CacheInvalidStateException) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) GridDhtPartitionsExchangeFuture(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture) GridCacheReturn(org.apache.ignite.internal.processors.cache.GridCacheReturn) IgniteTxRollbackCheckedException(org.apache.ignite.internal.transactions.IgniteTxRollbackCheckedException) IgniteTxTimeoutCheckedException(org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) NodeStoppingException(org.apache.ignite.internal.NodeStoppingException) GridCacheLockTimeoutException(org.apache.ignite.internal.processors.cache.GridCacheLockTimeoutException) ClusterTopologyException(org.apache.ignite.cluster.ClusterTopologyException) GridDistributedLockCancelledException(org.apache.ignite.internal.processors.cache.distributed.GridDistributedLockCancelledException) CacheInvalidStateException(org.apache.ignite.internal.processors.cache.CacheInvalidStateException) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) GridDhtInvalidPartitionException(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtInvalidPartitionException) GridClosureException(org.apache.ignite.internal.util.lang.GridClosureException) GridCacheEntryEx(org.apache.ignite.internal.processors.cache.GridCacheEntryEx) CacheEntryPredicate(org.apache.ignite.internal.processors.cache.CacheEntryPredicate)

Aggregations

GridDhtPartitionTopology (org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology)64 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)24 GridDhtLocalPartition (org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtLocalPartition)21 ClusterNode (org.apache.ignite.cluster.ClusterNode)20 Map (java.util.Map)18 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)18 CacheGroupContext (org.apache.ignite.internal.processors.cache.CacheGroupContext)17 HashMap (java.util.HashMap)15 ArrayList (java.util.ArrayList)14 Ignite (org.apache.ignite.Ignite)14 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)12 Test (org.junit.Test)12 IgniteEx (org.apache.ignite.internal.IgniteEx)11 UUID (java.util.UUID)10 IgniteKernal (org.apache.ignite.internal.IgniteKernal)10 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)9 IgniteException (org.apache.ignite.IgniteException)9 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)9 GridDhtPartitionMap (org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionMap)9 HashSet (java.util.HashSet)8