You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shardingsphere.apache.org by zh...@apache.org on 2023/09/08 03:48:07 UTC

[shardingsphere] branch master updated: Verify inventory finished before starting consistency check (#28388)

This is an automated email from the ASF dual-hosted git repository.

zhaojinchao pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shardingsphere.git


The following commit(s) were added to refs/heads/master by this push:
     new a0196aaa7d5 Verify inventory finished before starting consistency check (#28388)
a0196aaa7d5 is described below

commit a0196aaa7d5df343d7d4c0ae67d9257ea7097a0f
Author: Hongsheng Zhong <zh...@apache.org>
AuthorDate: Fri Sep 8 11:48:00 2023 +0800

    Verify inventory finished before starting consistency check (#28388)
    
    * Run completion callback in dedicated thread pool
    
    * Extract PipelineJobProgressDetector.isInventoryFinished
    
    * Update REGISTER STORAGE UNIT template for migration
    
    * Verify inventory finished before starting consistency check
    
    * Persist inventory progress after inventory done
---
 .../pipeline/common/execute/ExecuteEngine.java     |  6 +++--
 .../AbstractSingleTableInventoryCalculator.java    |  2 --
 .../job/progress/PipelineJobProgressDetector.java  | 27 ++++++++++++++++++---
 .../persist/PipelineJobProgressPersistService.java | 28 ++++++++++++++++++----
 .../runner/InventoryIncrementalTasksRunner.java    |  6 +++--
 .../handler/update/CheckMigrationJobUpdater.java   |  9 +++++++
 .../pipeline/cases/PipelineContainerComposer.java  |  2 ++
 .../resources/env/common/migration-command.xml     | 12 ++++++----
 8 files changed, 74 insertions(+), 18 deletions(-)

diff --git a/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/common/execute/ExecuteEngine.java b/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/common/execute/ExecuteEngine.java
index 118be941f41..a8c49be7539 100644
--- a/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/common/execute/ExecuteEngine.java
+++ b/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/common/execute/ExecuteEngine.java
@@ -43,6 +43,8 @@ public final class ExecuteEngine {
     
     private static final String THREAD_SUFFIX = "-%d";
     
+    private static final ExecutorService CALLBACK_EXECUTOR = Executors.newSingleThreadScheduledExecutor(ExecutorThreadFactoryBuilder.build(THREAD_PREFIX + "callback" + THREAD_SUFFIX));
+    
     private final ExecutorService executorService;
     
     /**
@@ -118,14 +120,14 @@ public final class ExecuteEngine {
     public static void trigger(final Collection<CompletableFuture<?>> futures, final ExecuteCallback executeCallback) {
         BlockingQueue<CompletableFuture<?>> futureQueue = new LinkedBlockingQueue<>();
         for (CompletableFuture<?> each : futures) {
-            each.whenComplete(new BiConsumer<Object, Throwable>() {
+            each.whenCompleteAsync(new BiConsumer<Object, Throwable>() {
                 
                 @SneakyThrows(InterruptedException.class)
                 @Override
                 public void accept(final Object unused, final Throwable throwable) {
                     futureQueue.put(each);
                 }
-            });
+            }, CALLBACK_EXECUTOR);
         }
         for (int i = 1, count = futures.size(); i <= count; i++) {
             CompletableFuture<?> future = futureQueue.take();
diff --git a/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/consistencycheck/table/calculator/AbstractSingleTableInventoryCalculator.java b/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/consistencycheck/table/calculator/AbstractSingleTableInventoryCalculator.java
index 1129b6a4c2e..631c1d3a11d 100644
--- a/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/consistencycheck/table/calculator/AbstractSingleTableInventoryCalculator.java
+++ b/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/consistencycheck/table/calculator/AbstractSingleTableInventoryCalculator.java
@@ -49,7 +49,6 @@ public abstract class AbstractSingleTableInventoryCalculator implements SingleTa
             log.info("cancel, statement is null or closed");
             return;
         }
-        long startTimeMillis = System.currentTimeMillis();
         try {
             statement.cancel();
         } catch (final SQLFeatureNotSupportedException ex) {
@@ -59,7 +58,6 @@ public abstract class AbstractSingleTableInventoryCalculator implements SingleTa
             // CHECKSTYLE:ON
             log.info("cancel failed: {}", ex.getMessage());
         }
-        log.info("cancel cost {} ms", System.currentTimeMillis() - startTimeMillis);
     }
     
     /**
diff --git a/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/job/progress/PipelineJobProgressDetector.java b/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/job/progress/PipelineJobProgressDetector.java
index 2dabee73cf1..36f8cf3b46e 100644
--- a/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/job/progress/PipelineJobProgressDetector.java
+++ b/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/job/progress/PipelineJobProgressDetector.java
@@ -21,9 +21,11 @@ import lombok.AccessLevel;
 import lombok.NoArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.shardingsphere.data.pipeline.common.ingest.position.FinishedPosition;
+import org.apache.shardingsphere.data.pipeline.common.job.progress.InventoryIncrementalJobItemProgress;
 import org.apache.shardingsphere.data.pipeline.core.task.PipelineTask;
 
 import java.util.Collection;
+import java.util.Objects;
 
 /**
  * Pipeline job progress detector.
@@ -33,15 +35,34 @@ import java.util.Collection;
 public final class PipelineJobProgressDetector {
     
     /**
-     * All inventory tasks is finished.
+     * Whether all inventory tasks is finished.
      *
      * @param inventoryTasks to check inventory tasks
-     * @return is finished
+     * @return finished or not
      */
-    public static boolean allInventoryTasksFinished(final Collection<PipelineTask> inventoryTasks) {
+    public static boolean isAllInventoryTasksFinished(final Collection<PipelineTask> inventoryTasks) {
         if (inventoryTasks.isEmpty()) {
             log.warn("inventoryTasks is empty");
         }
         return inventoryTasks.stream().allMatch(each -> each.getTaskProgress().getPosition() instanceof FinishedPosition);
     }
+    
+    /**
+     * Whether inventory is finished or not.
+     *
+     * @param jobShardingCount job sharding count
+     * @param jobItemProgresses job item progresses
+     * @return finished or not
+     */
+    public static boolean isInventoryFinished(final int jobShardingCount, final Collection<InventoryIncrementalJobItemProgress> jobItemProgresses) {
+        return isAllProgressesFilled(jobShardingCount, jobItemProgresses) && isAllInventoryTasksCompleted(jobItemProgresses);
+    }
+    
+    private static boolean isAllProgressesFilled(final int jobShardingCount, final Collection<InventoryIncrementalJobItemProgress> jobItemProgresses) {
+        return jobShardingCount == jobItemProgresses.size() && jobItemProgresses.stream().allMatch(Objects::nonNull);
+    }
+    
+    private static boolean isAllInventoryTasksCompleted(final Collection<InventoryIncrementalJobItemProgress> jobItemProgresses) {
+        return jobItemProgresses.stream().flatMap(each -> each.getInventory().getProgresses().values().stream()).allMatch(each -> each.getPosition() instanceof FinishedPosition);
+    }
 }
diff --git a/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/job/progress/persist/PipelineJobProgressPersistService.java b/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/job/progress/persist/PipelineJobProgressPersistService.java
index c071aaed9c0..478cd13bb6c 100644
--- a/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/job/progress/persist/PipelineJobProgressPersistService.java
+++ b/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/job/progress/persist/PipelineJobProgressPersistService.java
@@ -80,11 +80,29 @@ public final class PipelineJobProgressPersistService {
      * @param shardingItem sharding item
      */
     public static void notifyPersist(final String jobId, final int shardingItem) {
+        getPersistContext(jobId, shardingItem).ifPresent(PipelineJobProgressPersistService::notifyPersist);
+    }
+    
+    private static void notifyPersist(final PipelineJobProgressPersistContext persistContext) {
+        persistContext.getHasNewEvents().set(true);
+    }
+    
+    private static Optional<PipelineJobProgressPersistContext> getPersistContext(final String jobId, final int shardingItem) {
         Map<Integer, PipelineJobProgressPersistContext> persistContextMap = JOB_PROGRESS_PERSIST_MAP.getOrDefault(jobId, Collections.emptyMap());
-        PipelineJobProgressPersistContext persistContext = persistContextMap.get(shardingItem);
-        if (null != persistContext) {
-            persistContext.getHasNewEvents().set(true);
-        }
+        return Optional.ofNullable(persistContextMap.get(shardingItem));
+    }
+    
+    /**
+     * Persist now.
+     *
+     * @param jobId job ID
+     * @param shardingItem sharding item
+     */
+    public static void persistNow(final String jobId, final int shardingItem) {
+        getPersistContext(jobId, shardingItem).ifPresent(persistContext -> {
+            notifyPersist(persistContext);
+            PersistJobContextRunnable.persist(jobId, shardingItem, persistContext);
+        });
     }
     
     private static final class PersistJobContextRunnable implements Runnable {
@@ -96,7 +114,7 @@ public final class PipelineJobProgressPersistService {
             }
         }
         
-        private void persist(final String jobId, final int shardingItem, final PipelineJobProgressPersistContext persistContext) {
+        private static synchronized void persist(final String jobId, final int shardingItem, final PipelineJobProgressPersistContext persistContext) {
             Long beforePersistingProgressMillis = persistContext.getBeforePersistingProgressMillis().get();
             if ((null == beforePersistingProgressMillis || System.currentTimeMillis() - beforePersistingProgressMillis < TimeUnit.SECONDS.toMillis(DELAY_SECONDS))
                     && !persistContext.getHasNewEvents().get()) {
diff --git a/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/task/runner/InventoryIncrementalTasksRunner.java b/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/task/runner/InventoryIncrementalTasksRunner.java
index 064a88f9588..d1af5e08d90 100644
--- a/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/task/runner/InventoryIncrementalTasksRunner.java
+++ b/kernel/data-pipeline/core/src/main/java/org/apache/shardingsphere/data/pipeline/core/task/runner/InventoryIncrementalTasksRunner.java
@@ -25,6 +25,7 @@ import org.apache.shardingsphere.data.pipeline.common.execute.ExecuteCallback;
 import org.apache.shardingsphere.data.pipeline.common.execute.ExecuteEngine;
 import org.apache.shardingsphere.data.pipeline.common.ingest.position.FinishedPosition;
 import org.apache.shardingsphere.data.pipeline.common.job.JobStatus;
+import org.apache.shardingsphere.data.pipeline.core.job.progress.persist.PipelineJobProgressPersistService;
 import org.apache.shardingsphere.infra.util.close.QuietlyCloser;
 import org.apache.shardingsphere.data.pipeline.core.job.PipelineJobIdUtils;
 import org.apache.shardingsphere.data.pipeline.core.job.progress.PipelineJobProgressDetector;
@@ -78,7 +79,7 @@ public class InventoryIncrementalTasksRunner implements PipelineTasksRunner {
             return;
         }
         TypedSPILoader.getService(PipelineJobAPI.class, PipelineJobIdUtils.parseJobType(jobItemContext.getJobId()).getType()).persistJobItemProgress(jobItemContext);
-        if (PipelineJobProgressDetector.allInventoryTasksFinished(inventoryTasks)) {
+        if (PipelineJobProgressDetector.isAllInventoryTasksFinished(inventoryTasks)) {
             log.info("All inventory tasks finished.");
             executeIncrementalTask();
         } else {
@@ -124,8 +125,9 @@ public class InventoryIncrementalTasksRunner implements PipelineTasksRunner {
     }
     
     protected void inventorySuccessCallback() {
-        if (PipelineJobProgressDetector.allInventoryTasksFinished(inventoryTasks)) {
+        if (PipelineJobProgressDetector.isAllInventoryTasksFinished(inventoryTasks)) {
             log.info("onSuccess, all inventory tasks finished.");
+            PipelineJobProgressPersistService.persistNow(jobItemContext.getJobId(), jobItemContext.getShardingItem());
             executeIncrementalTask();
         } else {
             log.info("onSuccess, inventory tasks not finished");
diff --git a/kernel/data-pipeline/distsql/handler/src/main/java/org/apache/shardingsphere/migration/distsql/handler/update/CheckMigrationJobUpdater.java b/kernel/data-pipeline/distsql/handler/src/main/java/org/apache/shardingsphere/migration/distsql/handler/update/CheckMigrationJobUpdater.java
index 35e684178e3..0c2ec012b5f 100644
--- a/kernel/data-pipeline/distsql/handler/src/main/java/org/apache/shardingsphere/migration/distsql/handler/update/CheckMigrationJobUpdater.java
+++ b/kernel/data-pipeline/distsql/handler/src/main/java/org/apache/shardingsphere/migration/distsql/handler/update/CheckMigrationJobUpdater.java
@@ -17,12 +17,15 @@
 
 package org.apache.shardingsphere.migration.distsql.handler.update;
 
+import org.apache.shardingsphere.data.pipeline.core.exception.param.PipelineInvalidParameterException;
+import org.apache.shardingsphere.data.pipeline.core.job.progress.PipelineJobProgressDetector;
 import org.apache.shardingsphere.data.pipeline.scenario.consistencycheck.api.impl.ConsistencyCheckJobAPI;
 import org.apache.shardingsphere.data.pipeline.scenario.consistencycheck.api.pojo.CreateConsistencyCheckJobParameter;
 import org.apache.shardingsphere.data.pipeline.scenario.migration.api.impl.MigrationJobAPI;
 import org.apache.shardingsphere.data.pipeline.scenario.migration.config.MigrationJobConfiguration;
 import org.apache.shardingsphere.distsql.handler.ral.update.RALUpdater;
 import org.apache.shardingsphere.distsql.parser.segment.AlgorithmSegment;
+import org.apache.shardingsphere.infra.exception.core.ShardingSpherePreconditions;
 import org.apache.shardingsphere.migration.distsql.statement.CheckMigrationStatement;
 
 import java.sql.SQLException;
@@ -44,9 +47,15 @@ public final class CheckMigrationJobUpdater implements RALUpdater<CheckMigration
         Properties algorithmProps = null == typeStrategy ? null : typeStrategy.getProps();
         String jobId = sqlStatement.getJobId();
         MigrationJobConfiguration jobConfig = migrationJobAPI.getJobConfiguration(jobId);
+        verifyInventoryFinished(jobConfig);
         checkJobAPI.createJobAndStart(new CreateConsistencyCheckJobParameter(jobId, algorithmTypeName, algorithmProps, jobConfig.getSourceDatabaseType(), jobConfig.getTargetDatabaseType()));
     }
     
+    private void verifyInventoryFinished(final MigrationJobConfiguration jobConfig) {
+        ShardingSpherePreconditions.checkState(PipelineJobProgressDetector.isInventoryFinished(jobConfig.getJobShardingCount(), migrationJobAPI.getJobProgress(jobConfig).values()),
+                () -> new PipelineInvalidParameterException("Inventory is not finished."));
+    }
+    
     @Override
     public Class<CheckMigrationStatement> getType() {
         return CheckMigrationStatement.class;
diff --git a/test/e2e/operation/pipeline/src/test/java/org/apache/shardingsphere/test/e2e/data/pipeline/cases/PipelineContainerComposer.java b/test/e2e/operation/pipeline/src/test/java/org/apache/shardingsphere/test/e2e/data/pipeline/cases/PipelineContainerComposer.java
index 420b42823e2..7095b587f94 100644
--- a/test/e2e/operation/pipeline/src/test/java/org/apache/shardingsphere/test/e2e/data/pipeline/cases/PipelineContainerComposer.java
+++ b/test/e2e/operation/pipeline/src/test/java/org/apache/shardingsphere/test/e2e/data/pipeline/cases/PipelineContainerComposer.java
@@ -393,7 +393,9 @@ public final class PipelineContainerComposer implements AutoCloseable {
             Set<String> statusSet = jobStatus.stream().map(each -> String.valueOf(each.get("status"))).collect(Collectors.toSet());
             if (statusSet.contains(JobStatus.PREPARING.name()) || statusSet.contains(JobStatus.RUNNING.name())) {
                 Awaitility.await().pollDelay(2L, TimeUnit.SECONDS).until(() -> true);
+                continue;
             }
+            break;
         }
     }
     
diff --git a/test/e2e/operation/pipeline/src/test/resources/env/common/migration-command.xml b/test/e2e/operation/pipeline/src/test/resources/env/common/migration-command.xml
index d0d62eb7f7b..7b455d37552 100644
--- a/test/e2e/operation/pipeline/src/test/resources/env/common/migration-command.xml
+++ b/test/e2e/operation/pipeline/src/test/resources/env/common/migration-command.xml
@@ -37,7 +37,8 @@
         REGISTER MIGRATION SOURCE STORAGE UNIT ds_0 (
         URL="${ds0}",
         USER="${user}",
-        PASSWORD="${password}"
+        PASSWORD="${password}",
+        PROPERTIES("maximumPoolSize"="50","idleTimeout"="30000")
         );
     </register-migration-source-storage-unit-template>
     
@@ -45,15 +46,18 @@
         REGISTER STORAGE UNIT ds_2 (
         URL="${ds2}",
         USER="${user}",
-        PASSWORD="${password}"
+        PASSWORD="${password}",
+        PROPERTIES("maximumPoolSize"="50","idleTimeout"="30000")
         ),ds_3 (
         URL="${ds3}",
         USER="${user}",
-        PASSWORD="${password}"
+        PASSWORD="${password}",
+        PROPERTIES("maximumPoolSize"="50","idleTimeout"="30000")
         ),ds_4 (
         URL="${ds4}",
         USER="${user}",
-        PASSWORD="${password}"
+        PASSWORD="${password}",
+        PROPERTIES("maximumPoolSize"="50","idleTimeout"="30000")
         )
     </register-migration-target-storage-unit-template>