Vladsz83 commented on code in PR #11391: URL: https://github.com/apache/ignite/pull/11391#discussion_r1673782737
########## modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotCheckDistributedProcess.java: ########## @@ -0,0 +1,549 @@ +/* + * 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.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.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Function; +import java.util.stream.Collectors; +import org.apache.ignite.IgniteCheckedException; +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 SnapshotCheckDistributedProcess { + /** */ + private static final IgniteInternalFuture FINISHED_FUT = new GridFinishedFuture<>(); + + /** */ + private final IgniteLogger log; + + /** */ + private final GridKernalContext kctx; + + /** Snapshot check requests per snapshot on every node. */ + 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, ArrayList<SnapshotMetadata>> phase1CheckMetas; + + /** Partition hashes second phase subprocess. */ + private final DistributedProcess<SnapshotCheckProcessRequest, HashMap<PartitionKeyV2, PartitionHashRecordV2>> phase2PartsHashes; + + /** */ + public SnapshotCheckDistributedProcess(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) -> nodeLeft(((DiscoveryEvent)evt).eventNode()), EVT_NODE_FAILED, EVT_NODE_LEFT); + } + + /** + * Stops the process with the passes 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. + */ + public void interrupt(Throwable th, @Nullable Function<SnapshotCheckProcessRequest, Boolean> rqFilter) { + if (requests.isEmpty()) + return; + + requests.values().forEach(rq -> { + if (rqFilter == null || rqFilter.apply(rq)) { + rq.error(th); + + clean(rq.requestId(), th, null, null); + } + }); + } + + /** Stops the related validation if the node is a mandatory one. */ + private void nodeLeft(ClusterNode node) { + if (node.isClient() || requests.isEmpty()) + return; + + interrupt( + new ClusterTopologyCheckedException("Snapshot checking stopped. A node left the cluster: " + node + '.'), + rq -> rq.nodes().contains(node.id()) + ); + } + + /** Phase 2 and process finish. */ + private IgniteInternalFuture<?> reduceValidatePartsAndFinish( + UUID procId, + Map<UUID, HashMap<PartitionKeyV2, PartitionHashRecordV2>> results, + Map<UUID, Throwable> errors + ) { + clean(procId, null, results, errors); + + return FINISHED_FUT; + } + + /** Phase 2 beginning. */ + private IgniteInternalFuture<HashMap<PartitionKeyV2, PartitionHashRecordV2>> validateParts( + SnapshotCheckProcessRequest incReq) { + SnapshotCheckProcessRequest locReq; + + if (stopAndCleanOnError(incReq, null) || (locReq = requests.get(incReq.snapshotName())) == null) + return FINISHED_FUT; + + assert locReq.equals(incReq); + + // Store metas to collect cluster operation result laster. + GridFutureAdapter<SnapshotPartitionsVerifyTaskResult> clusterOpFut = clusterOpFuts.get(incReq.requestId()); + + if (clusterOpFut != null) + locReq.metas = incReq.metas; + + // Local meta might be null if current node started after the snapshot creation or placement. + if (!incReq.nodes.contains(kctx.localNodeId()) || locReq.meta() == null) + return FINISHED_FUT; + + GridFutureAdapter<HashMap<PartitionKeyV2, PartitionHashRecordV2>> locPartsChkFut = new GridFutureAdapter<>(); + + locReq.fut(locPartsChkFut); + + ExecutorService executor = kctx.cache().context().snapshotMgr().snapshotExecutorService(); + + executor.submit(() -> stopFutureOnAnyFailure(locPartsChkFut, () -> { + // An error can occure when the local future is still null. + if (locReq.error() != null) + locPartsChkFut.onDone(locReq.error()); + + if (locPartsChkFut.isDone()) + return; + + File snpDir = kctx.cache().context().snapshotMgr().snapshotLocalDir(locReq.snapshotName(), locReq.snapshotPath()); + + try { + Map<PartitionKeyV2, PartitionHashRecordV2> res = kctx.cache().context().snapshotMgr().checker() + .checkPartitions(locReq.meta(), snpDir, locReq.groups(), false, true, false); + + locPartsChkFut.onDone(res instanceof HashMap ? (HashMap<PartitionKeyV2, PartitionHashRecordV2>)res + : new HashMap<>(res)); + } + catch (IgniteCheckedException e) { + throw new IgniteException("Failed to calculate snapshot partition hashes, req: " + incReq, e); + } + + // No need to wait to the cealup if current node is just a worker. + if (!kctx.localNodeId().equals(locReq.opCoordId) && clusterOpFut == null) + clean(locReq.reqId, null, null, null); + })); + + return locPartsChkFut; + } + + /** + * If required, stops and clean related validation if errors occured + * + * @return {@code True} if the validation stopped and cleaned. {@code False} otherwise. + */ + private boolean stopAndCleanOnError(SnapshotCheckProcessRequest req, + @Nullable Map<UUID, Throwable> occuredErrors) { + assert req != null; + + if (!F.isEmpty(occuredErrors)) { + occuredErrors = occuredErrors.entrySet().stream() Review Comment: Well, it should. But the process works on any node. Theoretically, any unrelated, unexpected exception might occur on any node. Let's keep an assert. -- 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]
