Vladsz83 commented on code in PR #11391:
URL: https://github.com/apache/ignite/pull/11391#discussion_r1695090334


##########
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotCheckProcess.java:
##########
@@ -0,0 +1,466 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache.persistence.snapshot;
+
+import java.io.File;
+import java.io.Serializable;
+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.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.events.DiscoveryEvent;
+import org.apache.ignite.internal.GridKernalContext;
+import org.apache.ignite.internal.IgniteInternalFuture;
+import org.apache.ignite.internal.cluster.ClusterTopologyCheckedException;
+import org.apache.ignite.internal.management.cache.IdleVerifyResultV2;
+import org.apache.ignite.internal.management.cache.PartitionKeyV2;
+import 
org.apache.ignite.internal.processors.cache.verify.PartitionHashRecordV2;
+import org.apache.ignite.internal.util.distributed.DistributedProcess;
+import org.apache.ignite.internal.util.future.GridFinishedFuture;
+import org.apache.ignite.internal.util.future.GridFutureAdapter;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.CU;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.ignite.events.EventType.EVT_NODE_FAILED;
+import static org.apache.ignite.events.EventType.EVT_NODE_LEFT;
+import static 
org.apache.ignite.internal.util.distributed.DistributedProcess.DistributedProcessType.SNAPSHOT_CHECK_METAS;
+import static 
org.apache.ignite.internal.util.distributed.DistributedProcess.DistributedProcessType.SNAPSHOT_VALIDATE_PARTS;
+
+/** Distributed process of snapshot checking (with the partition hashes). */
+public class SnapshotCheckProcess {
+    /** */
+    private final IgniteLogger log;
+
+    /** */
+    private final GridKernalContext kctx;
+
+    /** Snapshot check requests per snapshot on every node. */
+    private final Map<String, SnapshotCheckProcessRequest> requests = new 
ConcurrentHashMap<>();
+
+    /** Cluster-wide operation futures per snapshot called from current node. 
*/
+    private final Map<UUID, 
GridFutureAdapter<SnapshotPartitionsVerifyTaskResult>> clusterOpFuts = new 
ConcurrentHashMap<>();
+
+    /** Check metas first phase subprocess. */
+    private final DistributedProcess<SnapshotCheckProcessRequest, 
CheckResultDTO> phase1CheckMetas;
+
+    /** Partition hashes second phase subprocess.  */
+    private final DistributedProcess<SnapshotCheckProcessRequest, 
CheckResultDTO> phase2PartsHashes;
+
+    /** */
+    public SnapshotCheckProcess(GridKernalContext kctx) {
+        this.kctx = kctx;
+
+        log = kctx.log(getClass());
+
+        phase1CheckMetas = new DistributedProcess<>(kctx, 
SNAPSHOT_CHECK_METAS, this::prepareAndCheckMetas,
+            this::reducePreparationAndMetasCheck);
+
+        phase2PartsHashes = new DistributedProcess<>(kctx, 
SNAPSHOT_VALIDATE_PARTS, this::validateParts,
+            this::reduceValidatePartsAndFinish);
+
+        kctx.event().addLocalEventListener((evt) -> {
+            DiscoveryEvent devt = (DiscoveryEvent)evt;
+
+            if (devt.eventNode().isClient() || requests.isEmpty())
+                return;
+
+            interrupt(
+                new ClusterTopologyCheckedException("Snapshot checking 
stopped. A node left the cluster: " + devt.eventNode() + '.'),
+                req -> req.nodes().contains(devt.eventNode().id())
+            );
+        }, EVT_NODE_FAILED, EVT_NODE_LEFT);
+    }
+
+    /** */
+    Map<String, SnapshotCheckProcessRequest> requests() {
+        return Collections.unmodifiableMap(requests);
+    }
+
+    /**
+     * Stops the process with the passed exception.
+     *
+     * @param th The interrupt reason.
+     * @param rqFilter If not {@code null}, used to filter which 
requests/process to stop. If {@code null}, stops all the validations.
+     */
+    void interrupt(Throwable th, @Nullable 
Function<SnapshotCheckProcessRequest, Boolean> rqFilter) {
+        requests.values().forEach(req -> {
+            if (rqFilter == null || rqFilter.apply(req)) {
+                req.error(th);
+
+                clean(req.requestId(), th, null, null);
+            }
+        });
+    }
+
+    /** Phase 2 and process finish. */
+    private IgniteInternalFuture<?> reduceValidatePartsAndFinish(
+        UUID procId,
+        Map<UUID, CheckResultDTO> results,
+        Map<UUID, Throwable> errors
+    ) {
+        clean(procId, null, results, errors);
+
+        return new GridFinishedFuture<>();
+    }
+
+    /** Phase 2 beginning.  */
+    private IgniteInternalFuture<CheckResultDTO> 
validateParts(SnapshotCheckProcessRequest req) {
+        if (req.error() != null)
+            return new GridFinishedFuture<>(req.error());
+
+        SnapshotCheckProcessRequest locReq = currentRequest(null, 
req.requestId());
+
+        if (locReq == null)
+            return new GridFinishedFuture<>();
+
+        assert locReq.equals(req);
+
+        // Store metas on the originator to redulte relusts later.
+        if (req.operationalNodeId().equals(kctx.localNodeId()))
+            locReq.metas = req.metas;
+
+        // Local meta might be null if current node started after the snapshot 
creation or placement.
+        if (!req.nodes.contains(kctx.localNodeId()) || locReq.meta() == null)
+            return new GridFinishedFuture<>();
+
+        GridFutureAdapter<CheckResultDTO> locPartsChkFut = new 
GridFutureAdapter<>();
+
+        locReq.fut(locPartsChkFut);
+
+        if (!locPartsChkFut.isDone()) {
+            File snpDir = 
kctx.cache().context().snapshotMgr().snapshotLocalDir(locReq.snapshotName(), 
locReq.snapshotPath());
+
+            
kctx.cache().context().snapshotMgr().checker().checkPartitions(locReq.meta(), 
snpDir, locReq.groups(), false, true, false)
+                .whenComplete((res, err) -> {
+                    if (err != null)
+                        locPartsChkFut.onDone(err);
+                    else
+                        locPartsChkFut.onDone(new CheckResultDTO(res));
+                });
+        }
+
+        return locPartsChkFut;
+    }
+
+    /** Cleans certain snapshot validation. */
+    private void clean(
+        UUID reqId,
+        @Nullable Throwable opErr,
+        @Nullable Map<UUID, CheckResultDTO> results,
+        @Nullable Map<UUID, Throwable> errors
+    ) {
+        GridFutureAdapter<SnapshotPartitionsVerifyTaskResult> clusterOpFut = 
clusterOpFuts.get(reqId);
+
+        SnapshotCheckProcessRequest locReq = currentRequest(null, reqId);
+
+        Throwable err = opErr;
+
+        if (locReq != null) {
+            if (err == null && locReq.error() != null)
+                err = locReq.error();
+
+            GridFutureAdapter<?> locWorkingFut = locReq.fut();
+
+            boolean justFinished = locWorkingFut != null && 
locWorkingFut.onDone(err);
+
+            requests.remove(locReq.snapshotName());
+
+            if (justFinished && log.isInfoEnabled())
+                log.info("Finished snapshot local validation, req: " + locReq 
+ '.');
+        }
+
+        if (clusterOpFut == null || clusterOpFut.isDone())
+            return;
+
+        Map<ClusterNode, Exception> errors0 = collectErrors(errors, locReq != 
null ? locReq.nodes() : null);
+
+        if (err == null && !F.isEmpty(results)) {
+            assert results.values().stream().noneMatch(res -> res != null && 
res.metas != null);
+            assert locReq != null;
+
+            Map<ClusterNode, Map<PartitionKeyV2, PartitionHashRecordV2>> 
results0 = collectPartsHashes(results,
+                locReq != null ? locReq.nodes() : null);
+
+            IdleVerifyResultV2 chkRes = 
SnapshotChecker.reduceHashesResults(results0, errors0);
+
+            clusterOpFut.onDone(new 
SnapshotPartitionsVerifyTaskResult(locReq.metas, chkRes));
+        }
+        else
+            finishClusterFutureWithErr(clusterOpFut, err, errors0);
+    }
+    
+    /** */
+    private Map<ClusterNode, Exception> collectErrors(@Nullable Map<UUID, 
Throwable> errors, @Nullable Set<UUID> requiredNodes) {
+        if (F.isEmpty(errors))
+            return Collections.emptyMap();
+
+        return errors.entrySet().stream()
+            .filter(e -> (requiredNodes == null || 
requiredNodes.contains(e.getKey())) && e.getValue() != null)
+            .collect(Collectors.toMap(e -> 
kctx.cluster().get().node(e.getKey()), e -> asException(e.getValue())));
+    }
+
+    /** */
+    private Map<ClusterNode, Map<PartitionKeyV2, PartitionHashRecordV2>> 
collectPartsHashes(
+        @Nullable Map<UUID, CheckResultDTO> results,
+        Collection<UUID> requiredNodes
+    ) {
+        if (F.isEmpty(results))
+            return Collections.emptyMap();
+
+        return results.entrySet().stream()
+            .filter(e -> requiredNodes.contains(e.getKey()) && e.getValue() != 
null)
+            .collect(Collectors.toMap(e -> 
kctx.cluster().get().node(e.getKey()), e -> e.getValue().partsHashes));
+    }
+
+    /**
+     * @param snpName Snapshot name of the validation process. If {@code 
null}, ignored.
+     * @param procId  If {@code snpName} is {@code null}, is used to find the 
operation request.
+     * @return Current snapshot checking request by {@code snpName} or {@code 
procId}.
+     */
+    private @Nullable SnapshotCheckProcessRequest currentRequest(@Nullable 
String snpName, UUID procId) {
+        return snpName == null
+            ? requests.values().stream().filter(req -> 
req.requestId().equals(procId)).findFirst().orElse(null)
+            : requests.get(snpName);
+    }
+
+    /** Phase 1 beginning: prepare, collect and check local metas. */
+    private IgniteInternalFuture<CheckResultDTO> 
prepareAndCheckMetas(SnapshotCheckProcessRequest req) {
+        SnapshotCheckProcessRequest locReq = 
requests.computeIfAbsent(req.snapshotName(), snpName -> req);
+
+        if (!locReq.equals(req)) {

Review Comment:
   It also calls `super.equals(other)`. Doesn't it?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to