You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by tr...@apache.org on 2021/03/20 01:08:08 UTC

[flink] branch master updated (9ee91ef -> 3dd938d)

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

trohrmann pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/flink.git.


    from 9ee91ef  [FLINK-21875][hotfix] Fix compilation error in IntelliJ. Removing reliance on shaded classes. (#15290)
     new bc0f2c6  [FLINK-21602] Add CreatingExecutionGraph state
     new c4545e0  [FLINK-21602] Let AdaptiveScheduler create the ExecutionGraph in the ioExecutor
     new 53ac701  [hotfix] Let delayed AdaptiveScheduler.runIfState method return ScheduledFuture
     new ca968d3  [hotfix] Let Restarting and WaitingForResources cancel scheduled tasks onLeave
     new 8b5e172  [FLINK-21602] Remove generic parameter from SlotAllocator
     new 2f4813d  [FLINK-21602] Make SlotAllocator.tryReserveSlots failable
     new c7a4203  [FLINK-21602] Add DeclarativeSlotPool. and AllocatedSlotPool.containsFreeSlot
     new ce55b21  [FLINK-21602] Let SlotSharingSlotAllocator check whether resources are available before reserving them
     new 848e6d8  [hotfix] Make TestExecutorResource generic in the ExecutorService
     new 0809487  [hotfix] Make SlotAllocator configurable for the AdaptiveScheduler
     new 1f5f9aa  [FLINK-21602] Split ExecutionGraph generation and slot assignments into two steps
     new fb94512  [hotfix] Factor ExecutionGraph creation out into ExecutionGraphFactory
     new 6b2e05f  [hotfix] Annotate CheckpointsCleaner with @ThreadSafe
     new ae42e74  [hotfix] Rename SchedulerNG.getTerminationFuture into getJobTerminationFuture
     new a1798ec  [FLINK-21602] Allow SchedulerNG to terminate asynchronously
     new d6750d6  [hotfix] Add FutureUtils.switchExecutor utility
     new 3dd938d  [FLINK-21602] Track asynchronous background tasks in the AdaptiveScheduler

The 17 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../runtime/checkpoint/CheckpointsCleaner.java     |   3 +
 .../flink/runtime/concurrent/FutureUtils.java      |  22 ++
 .../apache/flink/runtime/jobmaster/JobMaster.java  |  50 ++-
 .../jobmaster/slotpool/AllocatedSlotPool.java      |  10 +
 .../jobmaster/slotpool/DeclarativeSlotPool.java    |  10 +
 .../slotpool/DefaultAllocatedSlotPool.java         |   5 +
 .../slotpool/DefaultDeclarativeSlotPool.java       |   5 +
 .../scheduler/DefaultExecutionGraphFactory.java    | 169 ++++++++++
 .../flink/runtime/scheduler/DefaultScheduler.java  |  24 +-
 .../runtime/scheduler/DefaultSchedulerFactory.java |  22 +-
 .../runtime/scheduler/ExecutionGraphFactory.java   |  59 ++++
 .../flink/runtime/scheduler/SchedulerBase.java     | 162 ++-------
 .../flink/runtime/scheduler/SchedulerNG.java       |   7 +-
 .../scheduler/adaptive/AdaptiveScheduler.java      | 362 ++++++++++-----------
 .../adaptive/AdaptiveSchedulerFactory.java         |  37 ++-
 .../runtime/scheduler/adaptive/BackgroundTask.java | 130 ++++++++
 .../scheduler/adaptive/CreatingExecutionGraph.java | 274 ++++++++++++++++
 .../runtime/scheduler/adaptive/Executing.java      |  15 +
 .../ParallelismAndResourceAssignments.java         |  50 ---
 .../runtime/scheduler/adaptive/Restarting.java     |  20 +-
 .../scheduler/adaptive/WaitingForResources.java    |  47 +--
 .../allocator/IsSlotAvailableAndFreeFunction.java  |  35 ++
 .../adaptive/allocator/ReservedSlots.java          |  42 +++
 .../adaptive/allocator/SlotAllocator.java          |  22 +-
 .../allocator/SlotSharingSlotAllocator.java        |  92 ++++--
 .../adaptive/allocator/VertexParallelism.java      |   4 +-
 .../VertexParallelismWithSlotSharing.java          |   5 +
 .../flink/runtime/concurrent/FutureUtilsTest.java  |  67 +++-
 .../executiongraph/ExecutionGraphSuspendTest.java  |  22 +-
 .../flink/runtime/jobmaster/JobMasterTest.java     |  31 ++
 .../slotpool/DefaultAllocatedSlotPoolTest.java     |  28 ++
 .../jobmaster/slotpool/SlotPoolTestUtils.java      |  12 +-
 .../slotpool/TestingDeclarativeSlotPool.java       |   9 +
 .../TestingDeclarativeSlotPoolBuilder.java         |   8 +
 .../OperatorCoordinatorSchedulerTest.java          |   4 +-
 .../DefaultExecutionGraphFactoryTest.java          | 156 +++++++++
 .../DefaultSchedulerBatchSchedulingTest.java       |  19 --
 .../runtime/scheduler/DefaultSchedulerTest.java    |  94 +-----
 .../GloballyTerminalJobStatusListener.java         |  44 +++
 .../runtime/scheduler/SchedulerTestingUtils.java   |  22 +-
 .../runtime/scheduler/TestingSchedulerNG.java      |  39 ++-
 .../adaptive/AdaptiveSchedulerBuilder.java         |  38 ++-
 .../scheduler/adaptive/AdaptiveSchedulerTest.java  | 289 ++++++++--------
 .../scheduler/adaptive/BackgroundTaskTest.java     | 156 +++++++++
 .../adaptive/CreatingExecutionGraphTest.java       | 250 ++++++++++++++
 .../runtime/scheduler/adaptive/ExecutingTest.java  |  27 +-
 .../runtime/scheduler/adaptive/RestartingTest.java |   5 +-
 .../adaptive/StateTrackingMockExecutionGraph.java  |  16 +-
 .../adaptive/WaitingForResourcesTest.java          | 126 ++-----
 .../allocator/SlotSharingSlotAllocatorTest.java    |  57 +++-
 .../adaptive/allocator/TestingSlotAllocator.java   | 120 +++++++
 .../TaskExecutorPartitionLifecycleTest.java        |   4 +-
 .../core/testutils/CompletedScheduledFuture.java   |  79 +++++
 .../ManuallyTriggeredScheduledExecutorService.java |  85 -----
 .../apache/flink/core/testutils/ScheduledTask.java | 115 +++++++
 .../testutils/executor/TestExecutorResource.java   |  11 +-
 56 files changed, 2584 insertions(+), 1032 deletions(-)
 create mode 100644 flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultExecutionGraphFactory.java
 create mode 100644 flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/ExecutionGraphFactory.java
 create mode 100644 flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/BackgroundTask.java
 create mode 100644 flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraph.java
 delete mode 100644 flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/ParallelismAndResourceAssignments.java
 create mode 100644 flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/IsSlotAvailableAndFreeFunction.java
 create mode 100644 flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/ReservedSlots.java
 create mode 100644 flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultExecutionGraphFactoryTest.java
 create mode 100644 flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/GloballyTerminalJobStatusListener.java
 create mode 100644 flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/BackgroundTaskTest.java
 create mode 100644 flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraphTest.java
 create mode 100644 flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/TestingSlotAllocator.java
 create mode 100644 flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/CompletedScheduledFuture.java
 create mode 100644 flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/ScheduledTask.java

[flink] 13/17: [hotfix] Annotate CheckpointsCleaner with @ThreadSafe

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 6b2e05fa6dc60a0ef6cde9398c2a776d2c7d9b32
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Tue Mar 16 11:58:52 2021 +0100

    [hotfix] Annotate CheckpointsCleaner with @ThreadSafe
---
 .../java/org/apache/flink/runtime/checkpoint/CheckpointsCleaner.java   | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointsCleaner.java b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointsCleaner.java
index ff2c6be..ab222e7 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointsCleaner.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointsCleaner.java
@@ -21,6 +21,8 @@ package org.apache.flink.runtime.checkpoint;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import javax.annotation.concurrent.ThreadSafe;
+
 import java.io.Serializable;
 import java.util.concurrent.Executor;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -29,6 +31,7 @@ import java.util.concurrent.atomic.AtomicInteger;
  * Delegate class responsible for checkpoints cleaning and counting the number of checkpoints yet to
  * clean.
  */
+@ThreadSafe
 public class CheckpointsCleaner implements Serializable {
     private static final Logger LOG = LoggerFactory.getLogger(CheckpointsCleaner.class);
 

[flink] 14/17: [hotfix] Rename SchedulerNG.getTerminationFuture into getJobTerminationFuture

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit ae42e745e9deee3c564ffe6b52e6d6c8abab46ce
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Wed Mar 17 09:00:47 2021 +0100

    [hotfix] Rename SchedulerNG.getTerminationFuture into getJobTerminationFuture
    
    This is a preparational step to better distinguish the job termination future from
    the Scheduler termination future. Moreover, the return type was changed to
    CompletableFuture<JobStatus> to be more expressive.
---
 .../apache/flink/runtime/scheduler/SchedulerBase.java  |  7 +++----
 .../apache/flink/runtime/scheduler/SchedulerNG.java    |  2 +-
 .../runtime/scheduler/adaptive/AdaptiveScheduler.java  |  8 ++++----
 .../flink/runtime/scheduler/DefaultSchedulerTest.java  |  2 +-
 .../flink/runtime/scheduler/TestingSchedulerNG.java    | 18 +++++++++---------
 5 files changed, 18 insertions(+), 19 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java
index 3ddb55f..56c06ae 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java
@@ -83,7 +83,6 @@ import org.apache.flink.runtime.util.IntArrayList;
 import org.apache.flink.util.ExceptionUtils;
 import org.apache.flink.util.FlinkException;
 import org.apache.flink.util.IterableUtils;
-import org.apache.flink.util.function.FunctionUtils;
 
 import org.slf4j.Logger;
 
@@ -407,7 +406,7 @@ public abstract class SchedulerBase implements SchedulerNG, CheckpointScheduling
     protected void failJob(Throwable cause) {
         incrementVersionsOfAllVertices();
         executionGraph.failJob(cause);
-        getTerminationFuture().thenRun(() -> archiveGlobalFailure(cause));
+        getJobTerminationFuture().thenRun(() -> archiveGlobalFailure(cause));
     }
 
     protected final SchedulingTopology getSchedulingTopology() {
@@ -523,8 +522,8 @@ public abstract class SchedulerBase implements SchedulerNG, CheckpointScheduling
     }
 
     @Override
-    public CompletableFuture<Void> getTerminationFuture() {
-        return executionGraph.getTerminationFuture().thenApply(FunctionUtils.nullFn());
+    public CompletableFuture<JobStatus> getJobTerminationFuture() {
+        return executionGraph.getTerminationFuture();
     }
 
     protected final void archiveGlobalFailure(@Nullable Throwable failure) {
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerNG.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerNG.java
index 9896f2a..505714d 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerNG.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerNG.java
@@ -72,7 +72,7 @@ public interface SchedulerNG {
 
     void cancel();
 
-    CompletableFuture<Void> getTerminationFuture();
+    CompletableFuture<JobStatus> getJobTerminationFuture();
 
     void handleGlobalFailure(Throwable cause);
 
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
index a7783db..db88e05 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
@@ -160,7 +160,7 @@ public class AdaptiveScheduler
     private final CheckpointIDCounter checkpointIdCounter;
     private final CheckpointsCleaner checkpointsCleaner;
 
-    private final CompletableFuture<Void> terminationFuture = new CompletableFuture<>();
+    private final CompletableFuture<JobStatus> jobTerminationFuture = new CompletableFuture<>();
 
     private final RestartBackoffTimeStrategy restartBackoffTimeStrategy;
 
@@ -292,8 +292,8 @@ public class AdaptiveScheduler
     }
 
     @Override
-    public CompletableFuture<Void> getTerminationFuture() {
-        return terminationFuture;
+    public CompletableFuture<JobStatus> getJobTerminationFuture() {
+        return jobTerminationFuture;
     }
 
     @Override
@@ -829,7 +829,7 @@ public class AdaptiveScheduler
                             : null);
         }
 
-        terminationFuture.complete(null);
+        jobTerminationFuture.complete(archivedExecutionGraph.getState());
     }
 
     private void stopCheckpointServicesSafely(JobStatus terminalState) {
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java
index e924538..dc2a1ee 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java
@@ -1155,7 +1155,7 @@ public class DefaultSchedulerTest extends TestLogger {
     }
 
     private void waitForTermination(final DefaultScheduler scheduler) throws Exception {
-        scheduler.getTerminationFuture().get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        scheduler.getJobTerminationFuture().get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
     }
 
     private static JobGraph singleNonParallelJobVertexJobGraph() {
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/TestingSchedulerNG.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/TestingSchedulerNG.java
index 2527e20..c87ac20 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/TestingSchedulerNG.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/TestingSchedulerNG.java
@@ -51,19 +51,19 @@ import java.util.function.Consumer;
 
 /** Testing implementation of the {@link SchedulerNG}. */
 public class TestingSchedulerNG implements SchedulerNG {
-    private final CompletableFuture<Void> terminationFuture;
+    private final CompletableFuture<JobStatus> jobTerminationFuture;
     private final Runnable startSchedulingRunnable;
     private final Consumer<Throwable> suspendConsumer;
     private final BiFunction<String, Boolean, CompletableFuture<String>> triggerSavepointFunction;
     private final Consumer<Throwable> handleGlobalFailureConsumer;
 
     private TestingSchedulerNG(
-            CompletableFuture<Void> terminationFuture,
+            CompletableFuture<JobStatus> jobTerminationFuture,
             Runnable startSchedulingRunnable,
             Consumer<Throwable> suspendConsumer,
             BiFunction<String, Boolean, CompletableFuture<String>> triggerSavepointFunction,
             Consumer<Throwable> handleGlobalFailureConsumer) {
-        this.terminationFuture = terminationFuture;
+        this.jobTerminationFuture = jobTerminationFuture;
         this.startSchedulingRunnable = startSchedulingRunnable;
         this.suspendConsumer = suspendConsumer;
         this.triggerSavepointFunction = triggerSavepointFunction;
@@ -88,8 +88,8 @@ public class TestingSchedulerNG implements SchedulerNG {
     public void cancel() {}
 
     @Override
-    public CompletableFuture<Void> getTerminationFuture() {
-        return terminationFuture;
+    public CompletableFuture<JobStatus> getJobTerminationFuture() {
+        return jobTerminationFuture;
     }
 
     @Override
@@ -224,15 +224,15 @@ public class TestingSchedulerNG implements SchedulerNG {
 
     /** Builder for the TestingSchedulerNG. */
     public static final class Builder {
-        private CompletableFuture<Void> terminationFuture = new CompletableFuture<>();
+        private CompletableFuture<JobStatus> jobTerminationFuture = new CompletableFuture<>();
         private Runnable startSchedulingRunnable = () -> {};
         private Consumer<Throwable> suspendConsumer = ignored -> {};
         private BiFunction<String, Boolean, CompletableFuture<String>> triggerSavepointFunction =
                 (ignoredA, ignoredB) -> new CompletableFuture<>();
         private Consumer<Throwable> handleGlobalFailureConsumer = (ignored) -> {};
 
-        public Builder setTerminationFuture(CompletableFuture<Void> terminationFuture) {
-            this.terminationFuture = terminationFuture;
+        public Builder setJobTerminationFuture(CompletableFuture<JobStatus> jobTerminationFuture) {
+            this.jobTerminationFuture = jobTerminationFuture;
             return this;
         }
 
@@ -260,7 +260,7 @@ public class TestingSchedulerNG implements SchedulerNG {
 
         public TestingSchedulerNG build() {
             return new TestingSchedulerNG(
-                    terminationFuture,
+                    jobTerminationFuture,
                     startSchedulingRunnable,
                     suspendConsumer,
                     triggerSavepointFunction,

[flink] 03/17: [hotfix] Let delayed AdaptiveScheduler.runIfState method return ScheduledFuture

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 53ac701e22d27fe537bd9fb790ac67e1033f4842
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Sun Mar 14 13:28:53 2021 +0100

    [hotfix] Let delayed AdaptiveScheduler.runIfState method return ScheduledFuture
    
    By letting the AdaptiveScheduler.runIfState method return a ScheduledFuture it is now
    possible to cancel scheduled actions.
---
 .../scheduler/adaptive/AdaptiveScheduler.java      |   5 +-
 .../scheduler/adaptive/CreatingExecutionGraph.java |   4 +-
 .../runtime/scheduler/adaptive/Restarting.java     |   4 +-
 .../scheduler/adaptive/WaitingForResources.java    |   4 +-
 .../adaptive/CreatingExecutionGraphTest.java       |   6 +-
 .../runtime/scheduler/adaptive/RestartingTest.java |   5 +-
 .../adaptive/WaitingForResourcesTest.java          |  66 +++++-------
 .../core/testutils/CompletedScheduledFuture.java   |  79 ++++++++++++++
 .../ManuallyTriggeredScheduledExecutorService.java |  85 ---------------
 .../apache/flink/core/testutils/ScheduledTask.java | 115 +++++++++++++++++++++
 10 files changed, 241 insertions(+), 132 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
index f03e162..be7b068 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
@@ -127,6 +127,7 @@ import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.CompletionException;
 import java.util.concurrent.Executor;
 import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -962,8 +963,8 @@ public class AdaptiveScheduler
     }
 
     @Override
-    public void runIfState(State expectedState, Runnable action, Duration delay) {
-        componentMainThreadExecutor.schedule(
+    public ScheduledFuture<?> runIfState(State expectedState, Runnable action, Duration delay) {
+        return componentMainThreadExecutor.schedule(
                 () -> runIfState(expectedState, action), delay.toMillis(), TimeUnit.MILLISECONDS);
     }
 
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraph.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraph.java
index b6f8df4..5e21ba6 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraph.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraph.java
@@ -30,6 +30,7 @@ import javax.annotation.Nullable;
 
 import java.time.Duration;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ScheduledFuture;
 
 /**
  * State which waits for the creation of the {@link ExecutionGraph}. If the creation fails, then the
@@ -149,8 +150,9 @@ public class CreatingExecutionGraph implements State {
          *     the action
          * @param action action to run if the expected state equals the actual state
          * @param delay delay after which to run the action
+         * @return a ScheduledFuture representing pending completion of the task
          */
-        void runIfState(State expectedState, Runnable action, Duration delay);
+        ScheduledFuture<?> runIfState(State expectedState, Runnable action, Duration delay);
 
         /**
          * Try to assign slots to the created {@link ExecutionGraph}. If it is possible, then this
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Restarting.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Restarting.java
index 5a49c48..307dfa02 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Restarting.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Restarting.java
@@ -28,6 +28,7 @@ import org.apache.flink.util.Preconditions;
 import org.slf4j.Logger;
 
 import java.time.Duration;
+import java.util.concurrent.ScheduledFuture;
 
 /** State which describes a job which is currently being restarted. */
 class Restarting extends StateWithExecutionGraph {
@@ -105,8 +106,9 @@ class Restarting extends StateWithExecutionGraph {
          *     the delay
          * @param action action to run if the state equals the expected state
          * @param delay delay after which the action should be executed
+         * @return a ScheduledFuture representing pending completion of the task
          */
-        void runIfState(State expectedState, Runnable action, Duration delay);
+        ScheduledFuture<?> runIfState(State expectedState, Runnable action, Duration delay);
     }
 
     static class Factory implements StateFactory<Restarting> {
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResources.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResources.java
index 848d729..9489ddd 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResources.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResources.java
@@ -28,6 +28,7 @@ import org.slf4j.Logger;
 import javax.annotation.Nullable;
 
 import java.time.Duration;
+import java.util.concurrent.ScheduledFuture;
 
 /**
  * State which describes that the scheduler is waiting for resources in order to execute the job.
@@ -142,8 +143,9 @@ class WaitingForResources implements State, ResourceConsumer {
          *     the action
          * @param action action to run if the expected state equals the actual state
          * @param delay delay after which to run the action
+         * @return a ScheduledFuture representing pending completion of the task
          */
-        void runIfState(State expectedState, Runnable action, Duration delay);
+        ScheduledFuture<?> runIfState(State expectedState, Runnable action, Duration delay);
     }
 
     static class Factory implements StateFactory<WaitingForResources> {
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraphTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraphTest.java
index 3d467fb..a352734 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraphTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraphTest.java
@@ -20,6 +20,7 @@ package org.apache.flink.runtime.scheduler.adaptive;
 
 import org.apache.flink.api.common.JobID;
 import org.apache.flink.api.common.JobStatus;
+import org.apache.flink.core.testutils.CompletedScheduledFuture;
 import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
 import org.apache.flink.runtime.executiongraph.ExecutionGraph;
 import org.apache.flink.util.FlinkException;
@@ -31,6 +32,7 @@ import javax.annotation.Nullable;
 
 import java.time.Duration;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ScheduledFuture;
 import java.util.function.Consumer;
 import java.util.function.Function;
 
@@ -187,10 +189,12 @@ public class CreatingExecutionGraphTest extends TestLogger {
         }
 
         @Override
-        public void runIfState(State expectedState, Runnable action, Duration delay) {
+        public ScheduledFuture<?> runIfState(State expectedState, Runnable action, Duration delay) {
             if (!hadStateTransitionHappened) {
                 action.run();
             }
+
+            return CompletedScheduledFuture.create(null);
         }
 
         @Override
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/RestartingTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/RestartingTest.java
index dd53263..2358709 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/RestartingTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/RestartingTest.java
@@ -19,6 +19,7 @@
 package org.apache.flink.runtime.scheduler.adaptive;
 
 import org.apache.flink.api.common.JobStatus;
+import org.apache.flink.core.testutils.CompletedScheduledFuture;
 import org.apache.flink.runtime.JobException;
 import org.apache.flink.runtime.client.JobExecutionException;
 import org.apache.flink.runtime.executiongraph.ExecutionGraph;
@@ -29,6 +30,7 @@ import org.apache.flink.util.TestLogger;
 import org.junit.Test;
 
 import java.time.Duration;
+import java.util.concurrent.ScheduledFuture;
 import java.util.function.Consumer;
 
 import static org.apache.flink.runtime.scheduler.adaptive.WaitingForResourcesTest.assertNonNull;
@@ -172,10 +174,11 @@ public class RestartingTest extends TestLogger {
         }
 
         @Override
-        public void runIfState(State expectedState, Runnable action, Duration delay) {
+        public ScheduledFuture<?> runIfState(State expectedState, Runnable action, Duration delay) {
             if (!hadStateTransition) {
                 action.run();
             }
+            return CompletedScheduledFuture.create(null);
         }
 
         @Override
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResourcesTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResourcesTest.java
index 8586551..c70dc2e 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResourcesTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResourcesTest.java
@@ -19,6 +19,7 @@
 package org.apache.flink.runtime.scheduler.adaptive;
 
 import org.apache.flink.api.common.JobStatus;
+import org.apache.flink.core.testutils.ScheduledTask;
 import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
 import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
 import org.apache.flink.runtime.executiongraph.ErrorInfo;
@@ -33,12 +34,12 @@ import javax.annotation.Nullable;
 import java.time.Duration;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.concurrent.ScheduledFuture;
 import java.util.function.Consumer;
 import java.util.function.Supplier;
 
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.Matchers.greaterThan;
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 
@@ -57,12 +58,7 @@ public class WaitingForResourcesTest extends TestLogger {
 
             new WaitingForResources(ctx, log, RESOURCE_COUNTER, Duration.ZERO);
             // run delayed actions
-            for (ScheduledRunnable scheduledRunnable : ctx.getScheduledRunnables()) {
-                scheduledRunnable.runAction();
-                if (ctx.hasStateTransition()) {
-                    break;
-                }
-            }
+            ctx.runScheduledTasks();
         }
     }
 
@@ -100,12 +96,7 @@ public class WaitingForResourcesTest extends TestLogger {
             ctx.setExpectCreatingExecutionGraph();
 
             // immediately execute all scheduled runnables
-            assertThat(ctx.getScheduledRunnables().size(), greaterThan(0));
-            for (ScheduledRunnable scheduledRunnable : ctx.getScheduledRunnables()) {
-                if (scheduledRunnable.getExpectedState() == wfr) {
-                    scheduledRunnable.runAction();
-                }
-            }
+            ctx.runScheduledTasks();
         }
     }
 
@@ -172,13 +163,9 @@ public class WaitingForResourcesTest extends TestLogger {
                 new StateValidator<>("finished");
 
         private Supplier<Boolean> hasEnoughResourcesSupplier = () -> false;
-        private final List<ScheduledRunnable> scheduledRunnables = new ArrayList<>();
+        private final List<ScheduledTask<Void>> scheduledTasks = new ArrayList<>();
         private boolean hasStateTransition = false;
 
-        public List<ScheduledRunnable> getScheduledRunnables() {
-            return scheduledRunnables;
-        }
-
         public void setHasEnoughResources(Supplier<Boolean> sup) {
             hasEnoughResourcesSupplier = sup;
         }
@@ -191,6 +178,12 @@ public class WaitingForResourcesTest extends TestLogger {
             creatingExecutionGraphStateValidator.expectInput(none -> {});
         }
 
+        void runScheduledTasks() {
+            for (ScheduledTask<Void> scheduledTask : scheduledTasks) {
+                scheduledTask.execute();
+            }
+        }
+
         @Override
         public void close() throws Exception {
             creatingExecutionGraphStateValidator.close();
@@ -212,8 +205,21 @@ public class WaitingForResourcesTest extends TestLogger {
         }
 
         @Override
-        public void runIfState(State expectedState, Runnable action, Duration delay) {
-            scheduledRunnables.add(new ScheduledRunnable(expectedState, action, delay));
+        public ScheduledFuture<?> runIfState(State expectedState, Runnable action, Duration delay) {
+            final ScheduledTask<Void> scheduledTask =
+                    new ScheduledTask<>(
+                            () -> {
+                                if (!hasStateTransition) {
+                                    action.run();
+                                }
+
+                                return null;
+                            },
+                            delay.toMillis());
+
+            scheduledTasks.add(scheduledTask);
+
+            return scheduledTask;
         }
 
         @Override
@@ -233,26 +239,6 @@ public class WaitingForResourcesTest extends TestLogger {
         }
     }
 
-    private static final class ScheduledRunnable {
-        private final Runnable action;
-        private final State expectedState;
-        private final Duration delay;
-
-        private ScheduledRunnable(State expectedState, Runnable action, Duration delay) {
-            this.expectedState = expectedState;
-            this.action = action;
-            this.delay = delay;
-        }
-
-        public void runAction() {
-            action.run();
-        }
-
-        public State getExpectedState() {
-            return expectedState;
-        }
-    }
-
     static <T> Consumer<T> assertNonNull() {
         return (item) -> assertThat(item, notNullValue());
     }
diff --git a/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/CompletedScheduledFuture.java b/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/CompletedScheduledFuture.java
new file mode 100644
index 0000000..6667612
--- /dev/null
+++ b/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/CompletedScheduledFuture.java
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.core.testutils;
+
+import java.util.concurrent.Delayed;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * Completed {@link ScheduledFuture} implementation.
+ *
+ * @param <T> type of the {@link ScheduledFuture}
+ */
+public final class CompletedScheduledFuture<T> implements ScheduledFuture<T> {
+
+    private final T value;
+
+    private CompletedScheduledFuture(T value) {
+        this.value = value;
+    }
+
+    @Override
+    public long getDelay(TimeUnit unit) {
+        return 0;
+    }
+
+    @Override
+    public int compareTo(Delayed o) {
+        return Long.compare(getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS));
+    }
+
+    @Override
+    public boolean cancel(boolean mayInterruptIfRunning) {
+        return false;
+    }
+
+    @Override
+    public boolean isCancelled() {
+        return false;
+    }
+
+    @Override
+    public boolean isDone() {
+        return true;
+    }
+
+    @Override
+    public T get() throws InterruptedException, ExecutionException {
+        return value;
+    }
+
+    @Override
+    public T get(long timeout, TimeUnit unit)
+            throws InterruptedException, ExecutionException, TimeoutException {
+        return value;
+    }
+
+    public static <T> CompletedScheduledFuture<T> create(T value) {
+        return new CompletedScheduledFuture<>(value);
+    }
+}
diff --git a/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/ManuallyTriggeredScheduledExecutorService.java b/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/ManuallyTriggeredScheduledExecutorService.java
index 1752dc6..7683804 100644
--- a/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/ManuallyTriggeredScheduledExecutorService.java
+++ b/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/ManuallyTriggeredScheduledExecutorService.java
@@ -27,17 +27,12 @@ import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 import java.util.NoSuchElementException;
-import java.util.Objects;
 import java.util.concurrent.Callable;
-import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.Delayed;
-import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
 import java.util.stream.Collectors;
 
 /**
@@ -317,84 +312,4 @@ public class ManuallyTriggeredScheduledExecutorService implements ScheduledExecu
 
         return scheduledTask;
     }
-
-    private static final class ScheduledTask<T> implements ScheduledFuture<T> {
-
-        private final Callable<T> callable;
-
-        private final long delay;
-
-        private final long period;
-
-        private final CompletableFuture<T> result;
-
-        private ScheduledTask(Callable<T> callable, long delay) {
-            this(callable, delay, 0);
-        }
-
-        private ScheduledTask(Callable<T> callable, long delay, long period) {
-            this.callable = Objects.requireNonNull(callable);
-            this.result = new CompletableFuture<>();
-            this.delay = delay;
-            this.period = period;
-        }
-
-        private boolean isPeriodic() {
-            return period > 0;
-        }
-
-        public void execute() {
-            if (!result.isDone()) {
-                if (!isPeriodic()) {
-                    try {
-                        result.complete(callable.call());
-                    } catch (Exception e) {
-                        result.completeExceptionally(e);
-                    }
-                } else {
-                    try {
-                        callable.call();
-                    } catch (Exception e) {
-                        result.completeExceptionally(e);
-                    }
-                }
-            }
-        }
-
-        @Override
-        public long getDelay(TimeUnit unit) {
-            return unit.convert(delay, TimeUnit.MILLISECONDS);
-        }
-
-        @Override
-        public int compareTo(Delayed o) {
-            return Long.compare(getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS));
-        }
-
-        @Override
-        public boolean cancel(boolean mayInterruptIfRunning) {
-            return result.cancel(mayInterruptIfRunning);
-        }
-
-        @Override
-        public boolean isCancelled() {
-            return result.isCancelled();
-        }
-
-        @Override
-        public boolean isDone() {
-            return result.isDone();
-        }
-
-        @Override
-        public T get() throws InterruptedException, ExecutionException {
-            return result.get();
-        }
-
-        @Override
-        public T get(long timeout, @Nonnull TimeUnit unit)
-                throws InterruptedException, ExecutionException, TimeoutException {
-            return result.get(timeout, unit);
-        }
-    }
 }
diff --git a/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/ScheduledTask.java b/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/ScheduledTask.java
new file mode 100644
index 0000000..899b6e1
--- /dev/null
+++ b/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/ScheduledTask.java
@@ -0,0 +1,115 @@
+/*
+ * 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.flink.core.testutils;
+
+import javax.annotation.Nonnull;
+
+import java.util.Objects;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Delayed;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * ScheduledTask represents a task which is executed at a later point in time.
+ *
+ * @param <T> type of the result
+ */
+public final class ScheduledTask<T> implements ScheduledFuture<T> {
+
+    private final Callable<T> callable;
+
+    private final long delay;
+
+    private final long period;
+
+    private final CompletableFuture<T> result;
+
+    public ScheduledTask(Callable<T> callable, long delay) {
+        this(callable, delay, 0);
+    }
+
+    public ScheduledTask(Callable<T> callable, long delay, long period) {
+        this.callable = Objects.requireNonNull(callable);
+        this.result = new CompletableFuture<>();
+        this.delay = delay;
+        this.period = period;
+    }
+
+    private boolean isPeriodic() {
+        return period > 0;
+    }
+
+    public void execute() {
+        if (!result.isDone()) {
+            if (!isPeriodic()) {
+                try {
+                    result.complete(callable.call());
+                } catch (Exception e) {
+                    result.completeExceptionally(e);
+                }
+            } else {
+                try {
+                    callable.call();
+                } catch (Exception e) {
+                    result.completeExceptionally(e);
+                }
+            }
+        }
+    }
+
+    @Override
+    public long getDelay(TimeUnit unit) {
+        return unit.convert(delay, TimeUnit.MILLISECONDS);
+    }
+
+    @Override
+    public int compareTo(Delayed o) {
+        return Long.compare(getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS));
+    }
+
+    @Override
+    public boolean cancel(boolean mayInterruptIfRunning) {
+        return result.cancel(mayInterruptIfRunning);
+    }
+
+    @Override
+    public boolean isCancelled() {
+        return result.isCancelled();
+    }
+
+    @Override
+    public boolean isDone() {
+        return result.isDone();
+    }
+
+    @Override
+    public T get() throws InterruptedException, ExecutionException {
+        return result.get();
+    }
+
+    @Override
+    public T get(long timeout, @Nonnull TimeUnit unit)
+            throws InterruptedException, ExecutionException, TimeoutException {
+        return result.get(timeout, unit);
+    }
+}

[flink] 05/17: [FLINK-21602] Remove generic parameter from SlotAllocator

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 8b5e172118a3f40bc14f9ab1ec969754615813a0
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Sun Mar 14 17:34:41 2021 +0100

    [FLINK-21602] Remove generic parameter from SlotAllocator
    
    The generic parameter will no longer be needed once the parallelism calculation and the
    reservation of slots happens in two separate steps.
---
 .../runtime/scheduler/adaptive/AdaptiveScheduler.java     |  9 ++++-----
 .../scheduler/adaptive/allocator/SlotAllocator.java       |  6 +++---
 .../adaptive/allocator/SlotSharingSlotAllocator.java      | 15 +++++++++++++--
 3 files changed, 20 insertions(+), 10 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
index be7b068..f420ce5 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
@@ -190,7 +190,7 @@ public class AdaptiveScheduler
 
     private final JobStatusListener jobStatusListener;
 
-    private final SlotAllocator<?> slotAllocator;
+    private final SlotAllocator slotAllocator;
 
     private final ScaleUpController scaleUpController;
 
@@ -581,11 +581,10 @@ public class AdaptiveScheduler
         return outstandingResources.isEmpty();
     }
 
-    private <T extends VertexParallelism>
-            ParallelismAndResourceAssignments determineParallelismAndAssignResources(
-                    SlotAllocator<T> slotAllocator) throws JobExecutionException {
+    private ParallelismAndResourceAssignments determineParallelismAndAssignResources(
+            SlotAllocator slotAllocator) throws JobExecutionException {
 
-        final T vertexParallelism =
+        final VertexParallelism vertexParallelism =
                 slotAllocator
                         .determineParallelism(
                                 jobInformation, declarativeSlotPool.getFreeSlotsInformation())
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotAllocator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotAllocator.java
index 3bf1a2a..2519db8 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotAllocator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotAllocator.java
@@ -27,7 +27,7 @@ import java.util.Map;
 import java.util.Optional;
 
 /** Component for calculating the slot requirements and mapping of vertices to slots. */
-public interface SlotAllocator<T extends VertexParallelism> {
+public interface SlotAllocator {
 
     /**
      * Calculates the total resources required for scheduling the given vertices.
@@ -58,7 +58,7 @@ public interface SlotAllocator<T extends VertexParallelism> {
      *     how the vertices could be assigned to slots, if all vertices could be run with the given
      *     slots
      */
-    Optional<T> determineParallelism(
+    Optional<? extends VertexParallelism> determineParallelism(
             JobInformation jobInformation, Collection<? extends SlotInfo> slots);
 
     /**
@@ -67,5 +67,5 @@ public interface SlotAllocator<T extends VertexParallelism> {
      * @param vertexParallelism information on how slots should be assigned to the slots
      * @return mapping of vertices to slots
      */
-    Map<ExecutionVertexID, LogicalSlot> reserveResources(T vertexParallelism);
+    Map<ExecutionVertexID, LogicalSlot> reserveResources(VertexParallelism vertexParallelism);
 }
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
index 7e256ec..26853cf 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
@@ -27,6 +27,7 @@ import org.apache.flink.runtime.jobmaster.SlotRequestId;
 import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlot;
 import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
 import org.apache.flink.runtime.util.ResourceCounter;
+import org.apache.flink.util.Preconditions;
 
 import java.util.ArrayList;
 import java.util.Collection;
@@ -40,7 +41,7 @@ import java.util.Set;
 import java.util.stream.Collectors;
 
 /** {@link SlotAllocator} implementation that supports slot sharing. */
-public class SlotSharingSlotAllocator implements SlotAllocator<VertexParallelismWithSlotSharing> {
+public class SlotSharingSlotAllocator implements SlotAllocator {
 
     private final ReserveSlotFunction reserveSlotFunction;
     private final FreeSlotFunction freeSlotFunction;
@@ -148,7 +149,17 @@ public class SlotSharingSlotAllocator implements SlotAllocator<VertexParallelism
 
     @Override
     public Map<ExecutionVertexID, LogicalSlot> reserveResources(
-            VertexParallelismWithSlotSharing vertexParallelismWithSlotSharing) {
+            VertexParallelism vertexParallelism) {
+        Preconditions.checkArgument(
+                vertexParallelism instanceof VertexParallelismWithSlotSharing,
+                String.format(
+                        "%s expects %s as argument.",
+                        SlotSharingSlotAllocator.class.getSimpleName(),
+                        VertexParallelismWithSlotSharing.class.getSimpleName()));
+
+        final VertexParallelismWithSlotSharing vertexParallelismWithSlotSharing =
+                (VertexParallelismWithSlotSharing) vertexParallelism;
+
         final Map<ExecutionVertexID, LogicalSlot> assignedSlots = new HashMap<>();
 
         for (ExecutionSlotSharingGroupAndSlot executionSlotSharingGroup :

[flink] 17/17: [FLINK-21602] Track asynchronous background tasks in the AdaptiveScheduler

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 3dd938d49ef7b7f0f68853ce0261aa4c43762bc5
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Wed Mar 17 12:26:38 2021 +0100

    [FLINK-21602] Track asynchronous background tasks in the AdaptiveScheduler
    
    The AdaptiveScheduler triggers asynchronous background tasks such as the creation of the ExecutionGraph.
    In order to know when we can stop the checkpointing services we have to keep track of these asynchronous
    tasks and only shut down the services after the tasks are completed. This ensures that there are no
    concurrent accesses to the checkpoint services.
    
    This closes #15251.
---
 .../scheduler/adaptive/AdaptiveScheduler.java      |  86 ++++++------
 .../runtime/scheduler/adaptive/BackgroundTask.java | 130 +++++++++++++++++
 .../scheduler/adaptive/AdaptiveSchedulerTest.java  |  15 +-
 .../scheduler/adaptive/BackgroundTaskTest.java     | 156 +++++++++++++++++++++
 4 files changed, 339 insertions(+), 48 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
index 4615175..162c29b 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
@@ -111,7 +111,6 @@ import java.util.Collection;
 import java.util.Iterator;
 import java.util.Optional;
 import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionException;
 import java.util.concurrent.Executor;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
@@ -186,6 +185,8 @@ public class AdaptiveScheduler
     private final MutableVertexAttemptNumberStore vertexAttemptNumberStore =
             new DefaultVertexAttemptNumberStore();
 
+    private BackgroundTask<ExecutionGraph> backgroundTask = BackgroundTask.finishedBackgroundTask();
+
     public AdaptiveScheduler(
             JobGraph jobGraph,
             Configuration configuration,
@@ -283,9 +284,42 @@ public class AdaptiveScheduler
 
     @Override
     public CompletableFuture<Void> closeAsync() {
+        LOG.debug("Closing the AdaptiveScheduler. Trying to suspend the current job execution.");
+
         state.suspend(new FlinkException("AdaptiveScheduler is being stopped."));
 
-        return FutureUtils.completedVoidFuture();
+        Preconditions.checkState(
+                state instanceof Finished,
+                "Scheduler state should be finished after calling state.suspend.");
+
+        backgroundTask.abort();
+        // wait for the background task to finish and then close services
+        return FutureUtils.runAfterwardsAsync(
+                backgroundTask.getTerminationFuture(),
+                () -> stopCheckpointServicesSafely(jobTerminationFuture.get()),
+                getMainThreadExecutor());
+    }
+
+    private void stopCheckpointServicesSafely(JobStatus terminalState) {
+        LOG.debug("Stopping the checkpoint services with state {}.", terminalState);
+
+        Exception exception = null;
+
+        try {
+            completedCheckpointStore.shutdown(terminalState, checkpointsCleaner);
+        } catch (Exception e) {
+            exception = e;
+        }
+
+        try {
+            checkpointIdCounter.shutdown(terminalState);
+        } catch (Exception e) {
+            exception = ExceptionUtils.firstOrSuppressed(e, exception);
+        }
+
+        if (exception != null) {
+            LOG.warn("Failed to stop checkpoint services.", exception);
+        }
     }
 
     @Override
@@ -746,24 +780,14 @@ public class AdaptiveScheduler
 
     private CompletableFuture<ExecutionGraph> createExecutionGraphAndRestoreStateAsync(
             JobGraph adjustedJobGraph) {
-        return CompletableFuture.supplyAsync(
-                        () -> {
-                            try {
-                                return createExecutionGraphAndRestoreState(adjustedJobGraph);
-                            } catch (Exception exception) {
-                                throw new CompletionException(exception);
-                            }
-                        },
-                        ioExecutor)
-                .handleAsync(
-                        (executionGraph, throwable) -> {
-                            if (throwable != null) {
-                                throw new CompletionException(throwable);
-                            } else {
-                                return executionGraph;
-                            }
-                        },
-                        getMainThreadExecutor());
+        backgroundTask.abort();
+
+        backgroundTask =
+                backgroundTask.runAfter(
+                        () -> createExecutionGraphAndRestoreState(adjustedJobGraph), ioExecutor);
+
+        return FutureUtils.switchExecutor(
+                backgroundTask.getResultFuture(), getMainThreadExecutor());
     }
 
     @Nonnull
@@ -819,8 +843,6 @@ public class AdaptiveScheduler
 
     @Override
     public void onFinished(ArchivedExecutionGraph archivedExecutionGraph) {
-        stopCheckpointServicesSafely(archivedExecutionGraph.getState());
-
         if (jobStatusListener != null) {
             jobStatusListener.jobStatusChanges(
                     jobInformation.getJobID(),
@@ -834,26 +856,6 @@ public class AdaptiveScheduler
         jobTerminationFuture.complete(archivedExecutionGraph.getState());
     }
 
-    private void stopCheckpointServicesSafely(JobStatus terminalState) {
-        Exception exception = null;
-
-        try {
-            completedCheckpointStore.shutdown(terminalState, checkpointsCleaner);
-        } catch (Exception e) {
-            exception = e;
-        }
-
-        try {
-            checkpointIdCounter.shutdown(terminalState);
-        } catch (Exception e) {
-            exception = ExceptionUtils.firstOrSuppressed(e, exception);
-        }
-
-        if (exception != null) {
-            LOG.warn("Failed to stop checkpoint services.", exception);
-        }
-    }
-
     @Override
     public Executing.FailureResult howToHandleFailure(Throwable failure) {
         if (ExecutionFailureHandler.isUnrecoverableError(failure)) {
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/BackgroundTask.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/BackgroundTask.java
new file mode 100644
index 0000000..7452c07
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/BackgroundTask.java
@@ -0,0 +1,130 @@
+/*
+ * 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.flink.runtime.scheduler.adaptive;
+
+import org.apache.flink.runtime.concurrent.FutureUtils;
+import org.apache.flink.util.FlinkException;
+import org.apache.flink.util.function.SupplierWithException;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.Executor;
+
+/**
+ * BackgroundTask encapsulates an asynchronous operation which can produce a result. The result can
+ * be accessed via {@link BackgroundTask#getResultFuture()}. Additionally, the task allows to track
+ * its completion via {@link BackgroundTask#getTerminationFuture()}.
+ *
+ * <p>In order to ensure the order of background tasks, one can use the {@link
+ * BackgroundTask#runAfter} to schedule tasks which are executed after this task has completed.
+ * Tasks which are executed sequentially like this won't be affected by the outcome of previous
+ * tasks. This means that a failed task won't stop succeeding tasks from being executed.
+ *
+ * @param <T> type of the produced result
+ */
+final class BackgroundTask<T> {
+    private final CompletableFuture<Void> terminationFuture;
+
+    private final CompletableFuture<T> resultFuture;
+
+    private volatile boolean isAborted = false;
+
+    private BackgroundTask(
+            CompletableFuture<Void> previousTerminationFuture,
+            SupplierWithException<? extends T, ? extends Exception> task,
+            Executor executor) {
+        resultFuture =
+                previousTerminationFuture.thenApplyAsync(
+                        ignored -> {
+                            if (!isAborted) {
+                                try {
+                                    return task.get();
+                                } catch (Exception exception) {
+                                    throw new CompletionException(exception);
+                                }
+                            } else {
+                                throw new CompletionException(
+                                        new FlinkException("Background task has been aborted."));
+                            }
+                        },
+                        executor);
+
+        terminationFuture = resultFuture.handle((ignored, ignoredThrowable) -> null);
+    }
+
+    private BackgroundTask() {
+        terminationFuture = FutureUtils.completedVoidFuture();
+        resultFuture =
+                FutureUtils.completedExceptionally(
+                        new FlinkException(
+                                "No result has been created because it is a finished background task."));
+    }
+
+    /**
+     * Abort the execution of this background task. This method has only an effect if the background
+     * task has not been started yet.
+     */
+    void abort() {
+        isAborted = true;
+    }
+
+    public CompletableFuture<T> getResultFuture() {
+        return resultFuture;
+    }
+
+    CompletableFuture<Void> getTerminationFuture() {
+        return terminationFuture;
+    }
+
+    /**
+     * Runs the given task after this background task has completed (normally or exceptionally).
+     *
+     * @param task task to run after this background task has completed
+     * @param executor executor to run the task
+     * @param <V> type of the result
+     * @return new {@link BackgroundTask} representing the new task to execute
+     */
+    <V> BackgroundTask<V> runAfter(
+            SupplierWithException<? extends V, ? extends Exception> task, Executor executor) {
+        return new BackgroundTask<>(terminationFuture, task, executor);
+    }
+
+    /**
+     * Creates a finished background task which can be used as the start of a background task chain.
+     *
+     * @param <V> type of the background task
+     * @return A finished background task
+     */
+    static <V> BackgroundTask<V> finishedBackgroundTask() {
+        return new BackgroundTask<>();
+    }
+
+    /**
+     * Creates an initial background task. This means that this background task has no predecessor.
+     *
+     * @param task task to run
+     * @param executor executor to run the task
+     * @param <V> type of the result
+     * @return initial {@link BackgroundTask} representing the task to execute
+     */
+    static <V> BackgroundTask<V> initialBackgroundTask(
+            SupplierWithException<? extends V, ? extends Exception> task, Executor executor) {
+        return new BackgroundTask<>(FutureUtils.completedVoidFuture(), task, executor);
+    }
+}
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
index 9bbf7a5..af7f00d 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
@@ -568,7 +568,7 @@ public class AdaptiveSchedulerTest extends TestLogger {
     }
 
     @Test
-    public void testGoToFinishedShutsDownCheckpointingComponents() throws Exception {
+    public void testCloseShutsDownCheckpointingComponents() throws Exception {
         final CompletableFuture<JobStatus> completedCheckpointStoreShutdownFuture =
                 new CompletableFuture<>();
         final CompletedCheckpointStore completedCheckpointStore =
@@ -586,16 +586,19 @@ public class AdaptiveSchedulerTest extends TestLogger {
                         CheckpointCoordinatorConfiguration.builder().build(), null));
 
         final AdaptiveScheduler scheduler =
-                new AdaptiveSchedulerBuilder(jobGraph, mainThreadExecutor)
+                new AdaptiveSchedulerBuilder(jobGraph, singleThreadMainThreadExecutor)
                         .setCheckpointRecoveryFactory(
                                 new TestingCheckpointRecoveryFactory(
                                         completedCheckpointStore, checkpointIdCounter))
                         .build();
 
-        final ArchivedExecutionGraph archivedExecutionGraph =
-                new ArchivedExecutionGraphBuilder().setState(JobStatus.FAILED).build();
-
-        scheduler.goToFinished(archivedExecutionGraph);
+        singleThreadMainThreadExecutor.execute(
+                () -> {
+                    scheduler.startScheduling();
+                    // transition into the FAILED state
+                    scheduler.handleGlobalFailure(new FlinkException("Test exception"));
+                    scheduler.closeAsync();
+                });
 
         assertThat(completedCheckpointStoreShutdownFuture.get(), is(JobStatus.FAILED));
         assertThat(checkpointIdCounterShutdownFuture.get(), is(JobStatus.FAILED));
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/BackgroundTaskTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/BackgroundTaskTest.java
new file mode 100644
index 0000000..d224ff6
--- /dev/null
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/BackgroundTaskTest.java
@@ -0,0 +1,156 @@
+/*
+ * 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.flink.runtime.scheduler.adaptive;
+
+import org.apache.flink.core.testutils.FlinkMatchers;
+import org.apache.flink.core.testutils.OneShotLatch;
+import org.apache.flink.testutils.executor.TestExecutorResource;
+import org.apache.flink.util.TestLogger;
+
+import org.hamcrest.Matchers;
+import org.junit.ClassRule;
+import org.junit.Test;
+
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+/** Tests for the {@link BackgroundTask}. */
+public class BackgroundTaskTest extends TestLogger {
+
+    @ClassRule
+    public static final TestExecutorResource<ExecutorService> TEST_EXECUTOR_RESOURCE =
+            new TestExecutorResource<>(() -> Executors.newFixedThreadPool(2));
+
+    @Test
+    public void testFinishedBackgroundTaskIsTerminated() {
+        final BackgroundTask<Void> finishedBackgroundTask = BackgroundTask.finishedBackgroundTask();
+
+        assertTrue(finishedBackgroundTask.getTerminationFuture().isDone());
+        finishedBackgroundTask.getTerminationFuture().join();
+    }
+
+    @Test
+    public void testFinishedBackgroundTaskDoesNotContainAResult() {
+        final BackgroundTask<Void> finishedBackgroundTask = BackgroundTask.finishedBackgroundTask();
+
+        assertTrue(finishedBackgroundTask.getResultFuture().isCompletedExceptionally());
+    }
+
+    @Test
+    public void testNormalCompletionOfBackgroundTask() {
+        final String expectedValue = "foobar";
+        final BackgroundTask<String> backgroundTask =
+                BackgroundTask.finishedBackgroundTask()
+                        .runAfter(() -> expectedValue, TEST_EXECUTOR_RESOURCE.getExecutor());
+
+        assertThat(backgroundTask.getResultFuture().join(), Matchers.is(expectedValue));
+        // check that the termination future has completed normally
+        backgroundTask.getTerminationFuture().join();
+    }
+
+    @Test
+    public void testExceptionalCompletionOfBackgroundTask() throws InterruptedException {
+        final Exception expectedException = new Exception("Test exception");
+        final BackgroundTask<String> backgroundTask =
+                BackgroundTask.finishedBackgroundTask()
+                        .runAfter(
+                                () -> {
+                                    throw expectedException;
+                                },
+                                TEST_EXECUTOR_RESOURCE.getExecutor());
+
+        try {
+            backgroundTask.getResultFuture().get();
+            fail("Expected an exceptionally completed result future.");
+        } catch (ExecutionException ee) {
+            assertThat(ee, FlinkMatchers.containsCause(expectedException));
+        }
+        // check that the termination future has completed normally
+        backgroundTask.getTerminationFuture().join();
+    }
+
+    @Test
+    public void testRunAfterExecutesBackgroundTaskAfterPreviousHasCompleted() {
+        final OneShotLatch blockingLatch = new OneShotLatch();
+        final BlockingQueue<Integer> taskCompletions = new ArrayBlockingQueue<>(2);
+        final BackgroundTask<Void> backgroundTask =
+                BackgroundTask.initialBackgroundTask(
+                                () -> {
+                                    blockingLatch.await();
+                                    taskCompletions.offer(1);
+                                    return null;
+                                },
+                                TEST_EXECUTOR_RESOURCE.getExecutor())
+                        .runAfter(
+                                () -> {
+                                    taskCompletions.offer(2);
+                                    return null;
+                                },
+                                TEST_EXECUTOR_RESOURCE.getExecutor());
+
+        blockingLatch.trigger();
+
+        backgroundTask.getTerminationFuture().join();
+
+        assertThat(taskCompletions, Matchers.contains(1, 2));
+    }
+
+    @Test
+    public void testAbortSkipsTasksWhichHaveNotBeenStarted() {
+        final OneShotLatch blockingLatch = new OneShotLatch();
+        final BlockingQueue<Integer> taskCompletions = new ArrayBlockingQueue<>(2);
+        final BackgroundTask<Void> backgroundTask =
+                BackgroundTask.initialBackgroundTask(
+                                () -> {
+                                    blockingLatch.await();
+                                    taskCompletions.offer(1);
+                                    return null;
+                                },
+                                TEST_EXECUTOR_RESOURCE.getExecutor())
+                        .runAfter(
+                                () -> {
+                                    taskCompletions.offer(2);
+                                    return null;
+                                },
+                                TEST_EXECUTOR_RESOURCE.getExecutor());
+
+        final BackgroundTask<Void> finalTask =
+                backgroundTask.runAfter(
+                        () -> {
+                            taskCompletions.offer(3);
+                            return null;
+                        },
+                        TEST_EXECUTOR_RESOURCE.getExecutor());
+
+        backgroundTask.abort();
+
+        blockingLatch.trigger();
+
+        finalTask.getTerminationFuture().join();
+
+        assertThat(taskCompletions, Matchers.contains(1, 3));
+    }
+}

[flink] 01/17: [FLINK-21602] Add CreatingExecutionGraph state

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit bc0f2c698b68960d227d5c7dc8a06a52b7138888
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Sun Mar 14 00:12:38 2021 +0100

    [FLINK-21602] Add CreatingExecutionGraph state
    
    The CreatingExecutionGraph state models the asynchronous ExecutionGraph creation
    after enough resources have been acquired in the WaitingForResources state.
---
 .../scheduler/adaptive/AdaptiveScheduler.java      | 231 +++++++++++----------
 .../scheduler/adaptive/CreatingExecutionGraph.java | 231 +++++++++++++++++++++
 .../scheduler/adaptive/WaitingForResources.java    |  31 +--
 .../scheduler/adaptive/AdaptiveSchedulerTest.java  |   2 +-
 .../adaptive/CreatingExecutionGraphTest.java       | 215 +++++++++++++++++++
 .../adaptive/WaitingForResourcesTest.java          |  62 +-----
 6 files changed, 585 insertions(+), 187 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
index 0998faf..1c5763e 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
@@ -149,6 +149,7 @@ public class AdaptiveScheduler
         implements SchedulerNG,
                 Created.Context,
                 WaitingForResources.Context,
+                CreatingExecutionGraph.Context,
                 Executing.Context,
                 Restarting.Context,
                 Failing.Context,
@@ -599,112 +600,6 @@ public class AdaptiveScheduler
     }
 
     @Override
-    public ExecutionGraph createExecutionGraphWithAvailableResources() throws Exception {
-        final ParallelismAndResourceAssignments parallelismAndResourceAssignments =
-                determineParallelismAndAssignResources(slotAllocator);
-
-        JobGraph adjustedJobGraph = jobInformation.copyJobGraph();
-        for (JobVertex vertex : adjustedJobGraph.getVertices()) {
-            vertex.setParallelism(parallelismAndResourceAssignments.getParallelism(vertex.getID()));
-        }
-
-        final ExecutionGraph executionGraph = createExecutionGraphAndRestoreState(adjustedJobGraph);
-
-        executionGraph.start(componentMainThreadExecutor);
-        executionGraph.transitionToRunning();
-
-        executionGraph.setInternalTaskFailuresListener(
-                new UpdateSchedulerNgOnInternalFailuresListener(this));
-
-        for (ExecutionVertex executionVertex : executionGraph.getAllExecutionVertices()) {
-            final LogicalSlot assignedSlot =
-                    parallelismAndResourceAssignments.getAssignedSlot(executionVertex.getID());
-            executionVertex
-                    .getCurrentExecutionAttempt()
-                    .registerProducedPartitions(assignedSlot.getTaskManagerLocation(), false);
-            executionVertex.tryAssignResource(assignedSlot);
-        }
-        return executionGraph;
-    }
-
-    private ExecutionGraph createExecutionGraphAndRestoreState(JobGraph adjustedJobGraph)
-            throws Exception {
-        ExecutionDeploymentListener executionDeploymentListener =
-                new ExecutionDeploymentTrackerDeploymentListenerAdapter(executionDeploymentTracker);
-        ExecutionStateUpdateListener executionStateUpdateListener =
-                (execution, newState) -> {
-                    if (newState.isTerminal()) {
-                        executionDeploymentTracker.stopTrackingDeploymentOf(execution);
-                    }
-                };
-
-        final ExecutionGraph newExecutionGraph =
-                DefaultExecutionGraphBuilder.buildGraph(
-                        adjustedJobGraph,
-                        configuration,
-                        futureExecutor,
-                        ioExecutor,
-                        userCodeClassLoader,
-                        completedCheckpointStore,
-                        checkpointsCleaner,
-                        checkpointIdCounter,
-                        rpcTimeout,
-                        jobManagerJobMetricGroup,
-                        blobWriter,
-                        LOG,
-                        shuffleMaster,
-                        partitionTracker,
-                        TaskDeploymentDescriptorFactory.PartitionLocationConstraint
-                                .MUST_BE_KNOWN, // AdaptiveScheduler only supports streaming jobs
-                        executionDeploymentListener,
-                        executionStateUpdateListener,
-                        initializationTimestamp,
-                        vertexAttemptNumberStore);
-
-        final CheckpointCoordinator checkpointCoordinator =
-                newExecutionGraph.getCheckpointCoordinator();
-
-        if (checkpointCoordinator != null) {
-            // check whether we find a valid checkpoint
-            if (!checkpointCoordinator.restoreInitialCheckpointIfPresent(
-                    new HashSet<>(newExecutionGraph.getAllVertices().values()))) {
-
-                // check whether we can restore from a savepoint
-                tryRestoreExecutionGraphFromSavepoint(
-                        newExecutionGraph, adjustedJobGraph.getSavepointRestoreSettings());
-            }
-        }
-
-        return newExecutionGraph;
-    }
-
-    /**
-     * Tries to restore the given {@link ExecutionGraph} from the provided {@link
-     * SavepointRestoreSettings}, iff checkpointing is enabled.
-     *
-     * @param executionGraphToRestore {@link ExecutionGraph} which is supposed to be restored
-     * @param savepointRestoreSettings {@link SavepointRestoreSettings} containing information about
-     *     the savepoint to restore from
-     * @throws Exception if the {@link ExecutionGraph} could not be restored
-     */
-    private void tryRestoreExecutionGraphFromSavepoint(
-            ExecutionGraph executionGraphToRestore,
-            SavepointRestoreSettings savepointRestoreSettings)
-            throws Exception {
-        if (savepointRestoreSettings.restoreSavepoint()) {
-            final CheckpointCoordinator checkpointCoordinator =
-                    executionGraphToRestore.getCheckpointCoordinator();
-            if (checkpointCoordinator != null) {
-                checkpointCoordinator.restoreSavepoint(
-                        savepointRestoreSettings.getRestorePath(),
-                        savepointRestoreSettings.allowNonRestoredState(),
-                        executionGraphToRestore.getAllVertices(),
-                        userCodeClassLoader);
-            }
-        }
-    }
-
-    @Override
     public ArchivedExecutionGraph getArchivedExecutionGraph(
             JobStatus jobStatus, @Nullable Throwable cause) {
         return ArchivedExecutionGraph.createFromInitializingJob(
@@ -813,6 +708,125 @@ public class AdaptiveScheduler
     }
 
     @Override
+    public void goToCreatingExecutionGraph() {
+        CompletableFuture<ExecutionGraph> executionGraphFuture;
+
+        try {
+            final ExecutionGraph executionGraph = createExecutionGraphWithAvailableResources();
+            executionGraphFuture = CompletableFuture.completedFuture(executionGraph);
+        } catch (Exception exception) {
+            executionGraphFuture = FutureUtils.completedExceptionally(exception);
+        }
+
+        transitionToState(new CreatingExecutionGraph.Factory(this, executionGraphFuture, LOG));
+    }
+
+    ExecutionGraph createExecutionGraphWithAvailableResources() throws Exception {
+        final ParallelismAndResourceAssignments parallelismAndResourceAssignments =
+                determineParallelismAndAssignResources(slotAllocator);
+
+        JobGraph adjustedJobGraph = jobInformation.copyJobGraph();
+        for (JobVertex vertex : adjustedJobGraph.getVertices()) {
+            vertex.setParallelism(parallelismAndResourceAssignments.getParallelism(vertex.getID()));
+        }
+
+        final ExecutionGraph executionGraph = createExecutionGraphAndRestoreState(adjustedJobGraph);
+
+        executionGraph.start(componentMainThreadExecutor);
+        executionGraph.transitionToRunning();
+
+        executionGraph.setInternalTaskFailuresListener(
+                new UpdateSchedulerNgOnInternalFailuresListener(this));
+
+        for (ExecutionVertex executionVertex : executionGraph.getAllExecutionVertices()) {
+            final LogicalSlot assignedSlot =
+                    parallelismAndResourceAssignments.getAssignedSlot(executionVertex.getID());
+            executionVertex
+                    .getCurrentExecutionAttempt()
+                    .registerProducedPartitions(assignedSlot.getTaskManagerLocation(), false);
+            executionVertex.tryAssignResource(assignedSlot);
+        }
+        return executionGraph;
+    }
+
+    private ExecutionGraph createExecutionGraphAndRestoreState(JobGraph adjustedJobGraph)
+            throws Exception {
+        ExecutionDeploymentListener executionDeploymentListener =
+                new ExecutionDeploymentTrackerDeploymentListenerAdapter(executionDeploymentTracker);
+        ExecutionStateUpdateListener executionStateUpdateListener =
+                (execution, newState) -> {
+                    if (newState.isTerminal()) {
+                        executionDeploymentTracker.stopTrackingDeploymentOf(execution);
+                    }
+                };
+
+        final ExecutionGraph newExecutionGraph =
+                DefaultExecutionGraphBuilder.buildGraph(
+                        adjustedJobGraph,
+                        configuration,
+                        futureExecutor,
+                        ioExecutor,
+                        userCodeClassLoader,
+                        completedCheckpointStore,
+                        checkpointsCleaner,
+                        checkpointIdCounter,
+                        rpcTimeout,
+                        jobManagerJobMetricGroup,
+                        blobWriter,
+                        LOG,
+                        shuffleMaster,
+                        partitionTracker,
+                        TaskDeploymentDescriptorFactory.PartitionLocationConstraint
+                                .MUST_BE_KNOWN, // AdaptiveScheduler only supports streaming jobs
+                        executionDeploymentListener,
+                        executionStateUpdateListener,
+                        initializationTimestamp,
+                        vertexAttemptNumberStore);
+
+        final CheckpointCoordinator checkpointCoordinator =
+                newExecutionGraph.getCheckpointCoordinator();
+
+        if (checkpointCoordinator != null) {
+            // check whether we find a valid checkpoint
+            if (!checkpointCoordinator.restoreInitialCheckpointIfPresent(
+                    new HashSet<>(newExecutionGraph.getAllVertices().values()))) {
+
+                // check whether we can restore from a savepoint
+                tryRestoreExecutionGraphFromSavepoint(
+                        newExecutionGraph, adjustedJobGraph.getSavepointRestoreSettings());
+            }
+        }
+
+        return newExecutionGraph;
+    }
+
+    /**
+     * Tries to restore the given {@link ExecutionGraph} from the provided {@link
+     * SavepointRestoreSettings}, iff checkpointing is enabled.
+     *
+     * @param executionGraphToRestore {@link ExecutionGraph} which is supposed to be restored
+     * @param savepointRestoreSettings {@link SavepointRestoreSettings} containing information about
+     *     the savepoint to restore from
+     * @throws Exception if the {@link ExecutionGraph} could not be restored
+     */
+    private void tryRestoreExecutionGraphFromSavepoint(
+            ExecutionGraph executionGraphToRestore,
+            SavepointRestoreSettings savepointRestoreSettings)
+            throws Exception {
+        if (savepointRestoreSettings.restoreSavepoint()) {
+            final CheckpointCoordinator checkpointCoordinator =
+                    executionGraphToRestore.getCheckpointCoordinator();
+            if (checkpointCoordinator != null) {
+                checkpointCoordinator.restoreSavepoint(
+                        savepointRestoreSettings.getRestorePath(),
+                        savepointRestoreSettings.allowNonRestoredState(),
+                        executionGraphToRestore.getAllVertices(),
+                        userCodeClassLoader);
+            }
+        }
+    }
+
+    @Override
     public boolean canScaleUp(ExecutionGraph executionGraph) {
         int availableSlots = declarativeSlotPool.getFreeSlotsInformation().size();
 
@@ -936,6 +950,11 @@ public class AdaptiveScheduler
                 () -> runIfState(expectedState, action), delay.toMillis(), TimeUnit.MILLISECONDS);
     }
 
+    @Override
+    public CreatingExecutionGraph.AssignmentResult tryToAssignSlots(ExecutionGraph executionGraph) {
+        return CreatingExecutionGraph.AssignmentResult.success(executionGraph);
+    }
+
     // ----------------------------------------------------------------
 
     /** Note: Do not call this method from a State constructor or State#onLeave. */
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraph.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraph.java
new file mode 100644
index 0000000..b6f8df4
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraph.java
@@ -0,0 +1,231 @@
+/*
+ * 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.flink.runtime.scheduler.adaptive;
+
+import org.apache.flink.api.common.JobStatus;
+import org.apache.flink.runtime.concurrent.FutureUtils;
+import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
+import org.apache.flink.runtime.executiongraph.ExecutionGraph;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+import java.util.concurrent.CompletableFuture;
+
+/**
+ * State which waits for the creation of the {@link ExecutionGraph}. If the creation fails, then the
+ * state transitions to {@link Finished}. If the creation succeeds, then the system tries to assign
+ * the required slots. If the set of available slots has changed so that the created {@link
+ * ExecutionGraph} cannot be executed, the state transitions back into {@link WaitingForResources}.
+ * If there are enough slots for the {@link ExecutionGraph} to run, the state transitions to {@link
+ * Executing}.
+ */
+public class CreatingExecutionGraph implements State {
+
+    private final Context context;
+
+    private final Logger log;
+
+    public CreatingExecutionGraph(
+            Context context, CompletableFuture<ExecutionGraph> executionGraphFuture, Logger log) {
+        this.context = context;
+        this.log = log;
+
+        FutureUtils.assertNoException(
+                executionGraphFuture.handle(
+                        (executionGraph, throwable) -> {
+                            context.runIfState(
+                                    this,
+                                    () -> handleExecutionGraphCreation(executionGraph, throwable),
+                                    Duration.ZERO);
+                            return null;
+                        }));
+    }
+
+    private void handleExecutionGraphCreation(
+            @Nullable ExecutionGraph executionGraph, @Nullable Throwable throwable) {
+        if (throwable != null) {
+            log.info(
+                    "Failed to go from {} to {} because the ExecutionGraph creation failed.",
+                    CreatingExecutionGraph.class.getSimpleName(),
+                    Executing.class.getSimpleName(),
+                    throwable);
+            context.goToFinished(context.getArchivedExecutionGraph(JobStatus.FAILED, throwable));
+        } else {
+            final AssignmentResult result = context.tryToAssignSlots(executionGraph);
+
+            if (result.isSuccess()) {
+                context.goToExecuting(result.getExecutionGraph());
+            } else {
+                context.goToWaitingForResources();
+            }
+        }
+    }
+
+    @Override
+    public void cancel() {
+        context.goToFinished(context.getArchivedExecutionGraph(JobStatus.CANCELED, null));
+    }
+
+    @Override
+    public void suspend(Throwable cause) {
+        context.goToFinished(context.getArchivedExecutionGraph(JobStatus.SUSPENDED, cause));
+    }
+
+    @Override
+    public JobStatus getJobStatus() {
+        return JobStatus.INITIALIZING;
+    }
+
+    @Override
+    public ArchivedExecutionGraph getJob() {
+        return context.getArchivedExecutionGraph(getJobStatus(), null);
+    }
+
+    @Override
+    public void handleGlobalFailure(Throwable cause) {
+        context.goToFinished(context.getArchivedExecutionGraph(JobStatus.FAILED, cause));
+    }
+
+    @Override
+    public Logger getLogger() {
+        return log;
+    }
+
+    /** Context for the {@link CreatingExecutionGraph} state. */
+    interface Context {
+
+        /**
+         * Transitions into the {@link Finished} state.
+         *
+         * @param archivedExecutionGraph archivedExecutionGraph representing the final job state
+         */
+        void goToFinished(ArchivedExecutionGraph archivedExecutionGraph);
+
+        /**
+         * Transitions into the {@link Executing} state.
+         *
+         * @param executionGraph executionGraph which is passed to the {@link Executing} state
+         */
+        void goToExecuting(ExecutionGraph executionGraph);
+
+        /** Transitions into the {@link WaitingForResources} state. */
+        void goToWaitingForResources();
+
+        /**
+         * Creates the {@link ArchivedExecutionGraph} for the given job status and cause. Cause can
+         * be null if there is no failure.
+         *
+         * @param jobStatus jobStatus to initialize the {@link ArchivedExecutionGraph} with
+         * @param cause cause describing a failure cause; {@code null} if there is none
+         * @return the created {@link ArchivedExecutionGraph}
+         */
+        ArchivedExecutionGraph getArchivedExecutionGraph(
+                JobStatus jobStatus, @Nullable Throwable cause);
+
+        /**
+         * Runs the given action after a delay if the state at this time equals the expected state.
+         *
+         * @param expectedState expectedState describes the required state at the time of running
+         *     the action
+         * @param action action to run if the expected state equals the actual state
+         * @param delay delay after which to run the action
+         */
+        void runIfState(State expectedState, Runnable action, Duration delay);
+
+        /**
+         * Try to assign slots to the created {@link ExecutionGraph}. If it is possible, then this
+         * method returns a successful {@link AssignmentResult} which contains the assigned {@link
+         * ExecutionGraph}. If not, then the assignment result is a failure.
+         *
+         * @param executionGraph executionGraph to assign slots to
+         * @return {@link AssignmentResult} representing the result of the assignment
+         */
+        AssignmentResult tryToAssignSlots(ExecutionGraph executionGraph);
+    }
+
+    /**
+     * Class representing the assignment result of the slots to the {@link ExecutionGraph}. The
+     * assignment is either successful or not possible. If it is successful, the assignment also
+     * contains the assigned {@link ExecutionGraph}.
+     */
+    static final class AssignmentResult {
+
+        private static final AssignmentResult NOT_POSSIBLE = new AssignmentResult(null);
+
+        @Nullable private final ExecutionGraph executionGraph;
+
+        private AssignmentResult(@Nullable ExecutionGraph executionGraph) {
+            this.executionGraph = executionGraph;
+        }
+
+        boolean isSuccess() {
+            return executionGraph != null;
+        }
+
+        ExecutionGraph getExecutionGraph() {
+            Preconditions.checkState(
+                    isSuccess(), "Can only return the ExecutionGraph if it is a success.");
+            return executionGraph;
+        }
+
+        static AssignmentResult success(ExecutionGraph executionGraph) {
+            return new AssignmentResult(
+                    Preconditions.checkNotNull(
+                            executionGraph,
+                            "AssignmentResult.success expects a non-null ExecutionGraph."));
+        }
+
+        static AssignmentResult notPossible() {
+            return NOT_POSSIBLE;
+        }
+    }
+
+    /** Factory for the {@link CreatingExecutionGraph} state. */
+    static class Factory implements StateFactory<CreatingExecutionGraph> {
+
+        private final Context context;
+
+        private final CompletableFuture<ExecutionGraph> executionGraphFuture;
+
+        private final Logger log;
+
+        Factory(
+                Context context,
+                CompletableFuture<ExecutionGraph> executionGraphFuture,
+                Logger log) {
+            this.context = context;
+            this.executionGraphFuture = executionGraphFuture;
+            this.log = log;
+        }
+
+        @Override
+        public Class<CreatingExecutionGraph> getStateClass() {
+            return CreatingExecutionGraph.class;
+        }
+
+        @Override
+        public CreatingExecutionGraph getState() {
+            return new CreatingExecutionGraph(context, executionGraphFuture, log);
+        }
+    }
+}
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResources.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResources.java
index 6f118c0..848d729 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResources.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResources.java
@@ -20,7 +20,6 @@ package org.apache.flink.runtime.scheduler.adaptive;
 
 import org.apache.flink.api.common.JobStatus;
 import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
-import org.apache.flink.runtime.executiongraph.ExecutionGraph;
 import org.apache.flink.runtime.util.ResourceCounter;
 import org.apache.flink.util.Preconditions;
 
@@ -101,19 +100,7 @@ class WaitingForResources implements State, ResourceConsumer {
     }
 
     private void createExecutionGraphWithAvailableResources() {
-        try {
-            final ExecutionGraph executionGraph =
-                    context.createExecutionGraphWithAvailableResources();
-
-            context.goToExecuting(executionGraph);
-        } catch (Exception exception) {
-            log.info(
-                    "Failed to go from {} to {} because the ExecutionGraph creation failed.",
-                    WaitingForResources.class.getSimpleName(),
-                    Executing.class.getSimpleName(),
-                    exception);
-            context.goToFinished(context.getArchivedExecutionGraph(JobStatus.FAILED, exception));
-        }
+        context.goToCreatingExecutionGraph();
     }
 
     /** Context of the {@link WaitingForResources} state. */
@@ -126,12 +113,8 @@ class WaitingForResources implements State, ResourceConsumer {
          */
         void goToFinished(ArchivedExecutionGraph archivedExecutionGraph);
 
-        /**
-         * Transitions into the {@link Executing} state.
-         *
-         * @param executionGraph executionGraph which is passed to the {@link Executing} state
-         */
-        void goToExecuting(ExecutionGraph executionGraph);
+        /** Transitions into the {@link CreatingExecutionGraph} state. */
+        void goToCreatingExecutionGraph();
 
         /**
          * Creates the {@link ArchivedExecutionGraph} for the given job status and cause. Cause can
@@ -153,14 +136,6 @@ class WaitingForResources implements State, ResourceConsumer {
         boolean hasEnoughResources(ResourceCounter desiredResources);
 
         /**
-         * Creates an {@link ExecutionGraph} with the available resources.
-         *
-         * @return the created {@link ExecutionGraph}
-         * @throws Exception if the creation of the {@link ExecutionGraph} fails
-         */
-        ExecutionGraph createExecutionGraphWithAvailableResources() throws Exception;
-
-        /**
          * Runs the given action after a delay if the state at this time equals the expected state.
          *
          * @param expectedState expectedState describes the required state at the time of running
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
index ec4d4b2..4958a37 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
@@ -479,7 +479,7 @@ public class AdaptiveSchedulerTest extends TestLogger {
                 createSlotOffersForResourceRequirements(
                         ResourceCounter.withResource(ResourceProfile.UNKNOWN, PARALLELISM)));
 
-        assertThat(scheduler.getState(), instanceOf(Executing.class));
+        assertThat(scheduler.getState(), instanceOf(CreatingExecutionGraph.class));
     }
 
     @Test
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraphTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraphTest.java
new file mode 100644
index 0000000..3d467fb
--- /dev/null
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraphTest.java
@@ -0,0 +1,215 @@
+/*
+ * 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.flink.runtime.scheduler.adaptive;
+
+import org.apache.flink.api.common.JobID;
+import org.apache.flink.api.common.JobStatus;
+import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
+import org.apache.flink.runtime.executiongraph.ExecutionGraph;
+import org.apache.flink.util.FlinkException;
+import org.apache.flink.util.TestLogger;
+
+import org.junit.Test;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.sameInstance;
+import static org.junit.Assert.assertThat;
+
+/** Tests for the {@link CreatingExecutionGraph} state. */
+public class CreatingExecutionGraphTest extends TestLogger {
+
+    @Test
+    public void testCancelTransitionsToFinished() throws Exception {
+        try (MockCreatingExecutionGraphContext context = new MockCreatingExecutionGraphContext()) {
+            final CreatingExecutionGraph creatingExecutionGraph =
+                    new CreatingExecutionGraph(context, new CompletableFuture<>(), log);
+
+            context.setExpectFinished(
+                    archivedExecutionGraph ->
+                            assertThat(archivedExecutionGraph.getState(), is(JobStatus.CANCELED)));
+
+            creatingExecutionGraph.cancel();
+        }
+    }
+
+    @Test
+    public void testSuspendTransitionsToFinished() throws Exception {
+        try (MockCreatingExecutionGraphContext context = new MockCreatingExecutionGraphContext()) {
+            final CreatingExecutionGraph creatingExecutionGraph =
+                    new CreatingExecutionGraph(context, new CompletableFuture<>(), log);
+
+            context.setExpectFinished(
+                    archivedExecutionGraph ->
+                            assertThat(archivedExecutionGraph.getState(), is(JobStatus.SUSPENDED)));
+
+            creatingExecutionGraph.suspend(new FlinkException("Job has been suspended."));
+        }
+    }
+
+    @Test
+    public void testGlobalFailureTransitionsToFinished() throws Exception {
+        try (MockCreatingExecutionGraphContext context = new MockCreatingExecutionGraphContext()) {
+            final CreatingExecutionGraph creatingExecutionGraph =
+                    new CreatingExecutionGraph(context, new CompletableFuture<>(), log);
+
+            context.setExpectFinished(
+                    archivedExecutionGraph ->
+                            assertThat(archivedExecutionGraph.getState(), is(JobStatus.FAILED)));
+
+            creatingExecutionGraph.handleGlobalFailure(new FlinkException("Test exception"));
+        }
+    }
+
+    @Test
+    public void testFailedExecutionGraphCreationTransitionsToFinished() throws Exception {
+        try (MockCreatingExecutionGraphContext context = new MockCreatingExecutionGraphContext()) {
+            final CompletableFuture<ExecutionGraph> executionGraphFuture =
+                    new CompletableFuture<>();
+            final CreatingExecutionGraph creatingExecutionGraph =
+                    new CreatingExecutionGraph(context, executionGraphFuture, log);
+
+            context.setExpectFinished(
+                    archivedExecutionGraph ->
+                            assertThat(archivedExecutionGraph.getState(), is(JobStatus.FAILED)));
+
+            executionGraphFuture.completeExceptionally(new FlinkException("Test exception"));
+        }
+    }
+
+    @Test
+    public void testNotPossibleSlotAssignmentTransitionsToWaitingForResources() throws Exception {
+        try (MockCreatingExecutionGraphContext context = new MockCreatingExecutionGraphContext()) {
+            final CompletableFuture<ExecutionGraph> executionGraphFuture =
+                    new CompletableFuture<>();
+            final CreatingExecutionGraph creatingExecutionGraph =
+                    new CreatingExecutionGraph(context, executionGraphFuture, log);
+
+            context.setTryToAssignSlotsFunction(
+                    ignored -> CreatingExecutionGraph.AssignmentResult.notPossible());
+            context.setExpectWaitingForResources();
+
+            executionGraphFuture.complete(new StateTrackingMockExecutionGraph());
+        }
+    }
+
+    @Test
+    public void testSuccessfulSlotAssignmentTransitionsToExecuting() throws Exception {
+        try (MockCreatingExecutionGraphContext context = new MockCreatingExecutionGraphContext()) {
+            final CompletableFuture<ExecutionGraph> executionGraphFuture =
+                    new CompletableFuture<>();
+            final CreatingExecutionGraph creatingExecutionGraph =
+                    new CreatingExecutionGraph(context, executionGraphFuture, log);
+
+            final StateTrackingMockExecutionGraph executionGraph =
+                    new StateTrackingMockExecutionGraph();
+
+            context.setTryToAssignSlotsFunction(CreatingExecutionGraph.AssignmentResult::success);
+            context.setExpectedExecuting(
+                    actualExecutionGraph ->
+                            assertThat(actualExecutionGraph, sameInstance(executionGraph)));
+
+            executionGraphFuture.complete(executionGraph);
+        }
+    }
+
+    static class MockCreatingExecutionGraphContext
+            implements CreatingExecutionGraph.Context, AutoCloseable {
+        private final StateValidator<ArchivedExecutionGraph> finishedStateValidator =
+                new StateValidator<>("Finished");
+        private final StateValidator<Void> waitingForResourcesStateValidator =
+                new StateValidator<>("WaitingForResources");
+        private final StateValidator<ExecutionGraph> executingStateValidator =
+                new StateValidator<>("Executing");
+
+        private Function<ExecutionGraph, CreatingExecutionGraph.AssignmentResult>
+                tryToAssignSlotsFunction = CreatingExecutionGraph.AssignmentResult::success;
+
+        private boolean hadStateTransitionHappened = false;
+
+        public void setExpectFinished(Consumer<ArchivedExecutionGraph> asserter) {
+            finishedStateValidator.expectInput(asserter);
+        }
+
+        public void setExpectWaitingForResources() {
+            waitingForResourcesStateValidator.expectInput((none) -> {});
+        }
+
+        public void setExpectedExecuting(Consumer<ExecutionGraph> asserter) {
+            executingStateValidator.expectInput(asserter);
+        }
+
+        public void setTryToAssignSlotsFunction(
+                Function<ExecutionGraph, CreatingExecutionGraph.AssignmentResult>
+                        tryToAssignSlotsFunction) {
+            this.tryToAssignSlotsFunction = tryToAssignSlotsFunction;
+        }
+
+        @Override
+        public void goToFinished(ArchivedExecutionGraph archivedExecutionGraph) {
+            finishedStateValidator.validateInput(archivedExecutionGraph);
+            hadStateTransitionHappened = true;
+        }
+
+        @Override
+        public void goToExecuting(ExecutionGraph executionGraph) {
+            executingStateValidator.validateInput(executionGraph);
+            hadStateTransitionHappened = true;
+        }
+
+        @Override
+        public ArchivedExecutionGraph getArchivedExecutionGraph(
+                JobStatus jobStatus, @Nullable Throwable cause) {
+            return ArchivedExecutionGraph.createFromInitializingJob(
+                    new JobID(), "testJob", jobStatus, cause, 0L);
+        }
+
+        @Override
+        public void runIfState(State expectedState, Runnable action, Duration delay) {
+            if (!hadStateTransitionHappened) {
+                action.run();
+            }
+        }
+
+        @Override
+        public CreatingExecutionGraph.AssignmentResult tryToAssignSlots(
+                ExecutionGraph executionGraph) {
+            return tryToAssignSlotsFunction.apply(executionGraph);
+        }
+
+        @Override
+        public void goToWaitingForResources() {
+            waitingForResourcesStateValidator.validateInput(null);
+            hadStateTransitionHappened = true;
+        }
+
+        @Override
+        public void close() throws Exception {
+            finishedStateValidator.close();
+            waitingForResourcesStateValidator.close();
+            executingStateValidator.close();
+        }
+    }
+}
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResourcesTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResourcesTest.java
index 05135bb..8586551 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResourcesTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResourcesTest.java
@@ -22,13 +22,9 @@ import org.apache.flink.api.common.JobStatus;
 import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
 import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
 import org.apache.flink.runtime.executiongraph.ErrorInfo;
-import org.apache.flink.runtime.executiongraph.ExecutionGraph;
-import org.apache.flink.runtime.executiongraph.TestingDefaultExecutionGraphBuilder;
 import org.apache.flink.runtime.rest.handler.legacy.utils.ArchivedExecutionGraphBuilder;
 import org.apache.flink.runtime.util.ResourceCounter;
-import org.apache.flink.util.FlinkException;
 import org.apache.flink.util.TestLogger;
-import org.apache.flink.util.function.SupplierWithException;
 
 import org.junit.Test;
 
@@ -53,11 +49,11 @@ public class WaitingForResourcesTest extends TestLogger {
 
     /** WaitingForResources is transitioning to Executing if there are enough resources. */
     @Test
-    public void testTransitionToExecuting() throws Exception {
+    public void testTransitionToCreatingExecutionGraph() throws Exception {
         try (MockContext ctx = new MockContext()) {
             ctx.setHasEnoughResources(() -> true);
 
-            ctx.setExpectExecuting(assertNonNull());
+            ctx.setExpectCreatingExecutionGraph();
 
             new WaitingForResources(ctx, log, RESOURCE_COUNTER, Duration.ZERO);
             // run delayed actions
@@ -71,31 +67,6 @@ public class WaitingForResourcesTest extends TestLogger {
     }
 
     @Test
-    public void testTransitionToFinishedOnExecutionGraphInitializationFailure() throws Exception {
-        try (MockContext ctx = new MockContext()) {
-            ctx.setHasEnoughResources(() -> true);
-            ctx.setCreateExecutionGraphWithAvailableResources(
-                    () -> {
-                        throw new RuntimeException("Test exception");
-                    });
-
-            ctx.setExpectFinished(
-                    (archivedExecutionGraph -> {
-                        assertThat(archivedExecutionGraph.getState(), is(JobStatus.FAILED));
-                    }));
-
-            new WaitingForResources(ctx, log, RESOURCE_COUNTER, Duration.ZERO);
-
-            // run delayed actions
-            for (ScheduledRunnable scheduledRunnable : ctx.getScheduledRunnables()) {
-                if (!ctx.hasStateTransition()) {
-                    scheduledRunnable.runAction();
-                }
-            }
-        }
-    }
-
-    @Test
     public void testNotEnoughResources() throws Exception {
         try (MockContext ctx = new MockContext()) {
             ctx.setHasEnoughResources(() -> false);
@@ -114,7 +85,7 @@ public class WaitingForResourcesTest extends TestLogger {
             WaitingForResources wfr =
                     new WaitingForResources(ctx, log, RESOURCE_COUNTER, Duration.ZERO);
             ctx.setHasEnoughResources(() -> true); // make resources available
-            ctx.setExpectExecuting(assertNonNull());
+            ctx.setExpectCreatingExecutionGraph();
             wfr.notifyNewResourcesAvailable(); // .. and notify
         }
     }
@@ -126,7 +97,7 @@ public class WaitingForResourcesTest extends TestLogger {
             WaitingForResources wfr =
                     new WaitingForResources(ctx, log, RESOURCE_COUNTER, Duration.ZERO);
 
-            ctx.setExpectExecuting(assertNonNull());
+            ctx.setExpectCreatingExecutionGraph();
 
             // immediately execute all scheduled runnables
             assertThat(ctx.getScheduledRunnables().size(), greaterThan(0));
@@ -195,15 +166,12 @@ public class WaitingForResourcesTest extends TestLogger {
 
     private static class MockContext implements WaitingForResources.Context, AutoCloseable {
 
-        private final StateValidator<ExecutionGraph> executingStateValidator =
+        private final StateValidator<Void> creatingExecutionGraphStateValidator =
                 new StateValidator<>("executing");
         private final StateValidator<ArchivedExecutionGraph> finishedStateValidator =
                 new StateValidator<>("finished");
 
         private Supplier<Boolean> hasEnoughResourcesSupplier = () -> false;
-        private SupplierWithException<ExecutionGraph, FlinkException>
-                createExecutionGraphWithAvailableResources =
-                        () -> TestingDefaultExecutionGraphBuilder.newBuilder().build();
         private final List<ScheduledRunnable> scheduledRunnables = new ArrayList<>();
         private boolean hasStateTransition = false;
 
@@ -215,22 +183,17 @@ public class WaitingForResourcesTest extends TestLogger {
             hasEnoughResourcesSupplier = sup;
         }
 
-        public void setCreateExecutionGraphWithAvailableResources(
-                SupplierWithException<ExecutionGraph, FlinkException> sup) {
-            this.createExecutionGraphWithAvailableResources = sup;
-        }
-
         void setExpectFinished(Consumer<ArchivedExecutionGraph> asserter) {
             finishedStateValidator.expectInput(asserter);
         }
 
-        void setExpectExecuting(Consumer<ExecutionGraph> asserter) {
-            executingStateValidator.expectInput(asserter);
+        void setExpectCreatingExecutionGraph() {
+            creatingExecutionGraphStateValidator.expectInput(none -> {});
         }
 
         @Override
         public void close() throws Exception {
-            executingStateValidator.close();
+            creatingExecutionGraphStateValidator.close();
             finishedStateValidator.close();
         }
 
@@ -249,11 +212,6 @@ public class WaitingForResourcesTest extends TestLogger {
         }
 
         @Override
-        public ExecutionGraph createExecutionGraphWithAvailableResources() throws FlinkException {
-            return createExecutionGraphWithAvailableResources.get();
-        }
-
-        @Override
         public void runIfState(State expectedState, Runnable action, Duration delay) {
             scheduledRunnables.add(new ScheduledRunnable(expectedState, action, delay));
         }
@@ -265,8 +223,8 @@ public class WaitingForResourcesTest extends TestLogger {
         }
 
         @Override
-        public void goToExecuting(ExecutionGraph executionGraph) {
-            executingStateValidator.validateInput(executionGraph);
+        public void goToCreatingExecutionGraph() {
+            creatingExecutionGraphStateValidator.validateInput(null);
             hasStateTransition = true;
         }
 

[flink] 09/17: [hotfix] Make TestExecutorResource generic in the ExecutorService

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 848e6d80c08f81cede662951c9c0913539b8c6e9
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Mon Mar 15 18:04:11 2021 +0100

    [hotfix] Make TestExecutorResource generic in the ExecutorService
    
    Making the TestExecutorResource generic in the ExecutorService has the advantage that the resource
    can also manage and return SchedulerExecutorServices.
---
 .../taskexecutor/TaskExecutorPartitionLifecycleTest.java      |  4 ++--
 .../apache/flink/testutils/executor/TestExecutorResource.java | 11 +++++------
 2 files changed, 7 insertions(+), 8 deletions(-)

diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskExecutorPartitionLifecycleTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskExecutorPartitionLifecycleTest.java
index e858f7d..2d76738 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskExecutorPartitionLifecycleTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskExecutorPartitionLifecycleTest.java
@@ -118,8 +118,8 @@ public class TaskExecutorPartitionLifecycleTest extends TestLogger {
     @Rule public final TemporaryFolder tmp = new TemporaryFolder();
 
     @ClassRule
-    public static final TestExecutorResource TEST_EXECUTOR_SERVICE_RESOURCE =
-            new TestExecutorResource(() -> java.util.concurrent.Executors.newFixedThreadPool(1));
+    public static final TestExecutorResource<?> TEST_EXECUTOR_SERVICE_RESOURCE =
+            new TestExecutorResource<>(() -> java.util.concurrent.Executors.newFixedThreadPool(1));
 
     @Before
     public void setup() {
diff --git a/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/testutils/executor/TestExecutorResource.java b/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/testutils/executor/TestExecutorResource.java
index 011afe1..162aef0 100644
--- a/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/testutils/executor/TestExecutorResource.java
+++ b/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/testutils/executor/TestExecutorResource.java
@@ -19,18 +19,17 @@ package org.apache.flink.testutils.executor;
 
 import org.junit.rules.ExternalResource;
 
-import java.util.concurrent.Executor;
 import java.util.concurrent.ExecutorService;
 import java.util.function.Supplier;
 
 /** Resource which starts/stops an {@link ExecutorService} for testing purposes. */
-public class TestExecutorResource extends ExternalResource {
+public class TestExecutorResource<T extends ExecutorService> extends ExternalResource {
 
-    private final Supplier<ExecutorService> serviceFactory;
+    private final Supplier<T> serviceFactory;
 
-    private ExecutorService executorService;
+    private T executorService;
 
-    public TestExecutorResource(Supplier<ExecutorService> serviceFactory) {
+    public TestExecutorResource(Supplier<T> serviceFactory) {
         this.serviceFactory = serviceFactory;
     }
 
@@ -39,7 +38,7 @@ public class TestExecutorResource extends ExternalResource {
         executorService = serviceFactory.get();
     }
 
-    public Executor getExecutor() {
+    public T getExecutor() {
         // only return an Executor since this resource is in charge of the life cycle
         return executorService;
     }

[flink] 11/17: [FLINK-21602] Split ExecutionGraph generation and slot assignments into two steps

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 1f5f9aa5e82e75a104229d551a2d8b443f32885a
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Tue Mar 16 10:59:56 2021 +0100

    [FLINK-21602] Split ExecutionGraph generation and slot assignments into two steps
    
    In order to properly support the asynchronous ExecutionGraph generation, we need to handle
    the case where the set of available slots changed after the ExecutionGraph has been created.
    In this situation, we need to check whether the expected set of resources is still there
    and if not, then go back to WaitingForResources. Moreover, we need to schedule a resource
    check when entering the Executing state in order to not miss newly arrived slots.
---
 .../scheduler/adaptive/AdaptiveScheduler.java      | 125 ++++++----
 .../scheduler/adaptive/CreatingExecutionGraph.java |  65 ++++-
 .../runtime/scheduler/adaptive/Executing.java      |  15 ++
 .../ParallelismAndResourceAssignments.java         |  49 ----
 .../adaptive/allocator/VertexParallelism.java      |   2 +
 .../VertexParallelismWithSlotSharing.java          |   5 +
 .../jobmaster/slotpool/SlotPoolTestUtils.java      |  12 +-
 .../scheduler/adaptive/AdaptiveSchedulerTest.java  | 277 ++++++++++++++-------
 .../adaptive/CreatingExecutionGraphTest.java       |  67 +++--
 .../runtime/scheduler/adaptive/ExecutingTest.java  |  27 +-
 .../adaptive/StateTrackingMockExecutionGraph.java  |  16 +-
 .../adaptive/allocator/TestingSlotAllocator.java   | 120 +++++++++
 12 files changed, 549 insertions(+), 231 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
index 3bac7a0..badad27 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
@@ -577,30 +577,16 @@ public class AdaptiveScheduler
         return outstandingResources.isEmpty();
     }
 
-    private ParallelismAndResourceAssignments determineParallelismAndAssignResources(
-            SlotAllocator slotAllocator) throws JobExecutionException {
-
-        final VertexParallelism vertexParallelism =
-                slotAllocator
-                        .determineParallelism(
-                                jobInformation, declarativeSlotPool.getFreeSlotsInformation())
-                        .orElseThrow(
-                                () ->
-                                        new JobExecutionException(
-                                                jobInformation.getJobID(),
-                                                "Not enough resources available for scheduling."));
-
-        final ReservedSlots reservedSlots =
-                slotAllocator
-                        .tryReserveResources(vertexParallelism)
-                        .orElseThrow(
-                                () ->
-                                        new JobExecutionException(
-                                                jobInformation.getJobID(),
-                                                "Could not reserve all required slots."));
+    private VertexParallelism determineParallelism(SlotAllocator slotAllocator)
+            throws JobExecutionException {
 
-        return new ParallelismAndResourceAssignments(
-                reservedSlots, vertexParallelism.getMaxParallelismForVertices());
+        return slotAllocator
+                .determineParallelism(jobInformation, declarativeSlotPool.getFreeSlotsInformation())
+                .orElseThrow(
+                        () ->
+                                new JobExecutionException(
+                                        jobInformation.getJobID(),
+                                        "Not enough resources available for scheduling."));
     }
 
     @Override
@@ -713,29 +699,44 @@ public class AdaptiveScheduler
 
     @Override
     public void goToCreatingExecutionGraph() {
-        CompletableFuture<ExecutionGraph> executionGraphFuture;
+        final CompletableFuture<CreatingExecutionGraph.ExecutionGraphWithVertexParallelism>
+                executionGraphWithAvailableResourcesFuture =
+                        createExecutionGraphWithAvailableResourcesAsync();
+
+        transitionToState(
+                new CreatingExecutionGraph.Factory(
+                        this, executionGraphWithAvailableResourcesFuture, LOG));
+    }
+
+    private CompletableFuture<CreatingExecutionGraph.ExecutionGraphWithVertexParallelism>
+            createExecutionGraphWithAvailableResourcesAsync() {
+        final JobGraph adjustedJobGraph;
+        final VertexParallelism vertexParallelism;
 
         try {
-            final ExecutionGraph executionGraph = createExecutionGraphWithAvailableResources();
-            executionGraphFuture = CompletableFuture.completedFuture(executionGraph);
+            vertexParallelism = determineParallelism(slotAllocator);
+
+            adjustedJobGraph = jobInformation.copyJobGraph();
+            for (JobVertex vertex : adjustedJobGraph.getVertices()) {
+                vertex.setParallelism(vertexParallelism.getParallelism(vertex.getID()));
+            }
         } catch (Exception exception) {
-            executionGraphFuture = FutureUtils.completedExceptionally(exception);
+            return FutureUtils.completedExceptionally(exception);
         }
 
-        transitionToState(new CreatingExecutionGraph.Factory(this, executionGraphFuture, LOG));
+        return createExecutionGraphAndRestoreStateAsync(adjustedJobGraph)
+                .thenApply(
+                        executionGraph ->
+                                CreatingExecutionGraph.ExecutionGraphWithVertexParallelism.create(
+                                        executionGraph, vertexParallelism));
     }
 
-    ExecutionGraph createExecutionGraphWithAvailableResources() throws Exception {
-        final ParallelismAndResourceAssignments parallelismAndResourceAssignments =
-                determineParallelismAndAssignResources(slotAllocator);
-
-        JobGraph adjustedJobGraph = jobInformation.copyJobGraph();
-        for (JobVertex vertex : adjustedJobGraph.getVertices()) {
-            vertex.setParallelism(parallelismAndResourceAssignments.getParallelism(vertex.getID()));
-        }
-
+    @Override
+    public CreatingExecutionGraph.AssignmentResult tryToAssignSlots(
+            CreatingExecutionGraph.ExecutionGraphWithVertexParallelism
+                    executionGraphWithVertexParallelism) {
         final ExecutionGraph executionGraph =
-                createExecutionGraphAndRestoreStateAsync(adjustedJobGraph).join();
+                executionGraphWithVertexParallelism.getExecutionGraph();
 
         executionGraph.start(componentMainThreadExecutor);
         executionGraph.transitionToRunning();
@@ -743,28 +744,51 @@ public class AdaptiveScheduler
         executionGraph.setInternalTaskFailuresListener(
                 new UpdateSchedulerNgOnInternalFailuresListener(this));
 
+        final VertexParallelism vertexParallelism =
+                executionGraphWithVertexParallelism.getVertexParallelism();
+        return slotAllocator
+                .tryReserveResources(vertexParallelism)
+                .map(
+                        reservedSlots ->
+                                CreatingExecutionGraph.AssignmentResult.success(
+                                        assignSlotsToExecutionGraph(executionGraph, reservedSlots)))
+                .orElseGet(CreatingExecutionGraph.AssignmentResult::notPossible);
+    }
+
+    @Nonnull
+    private ExecutionGraph assignSlotsToExecutionGraph(
+            ExecutionGraph executionGraph, ReservedSlots reservedSlots) {
         for (ExecutionVertex executionVertex : executionGraph.getAllExecutionVertices()) {
-            final LogicalSlot assignedSlot =
-                    parallelismAndResourceAssignments.getAssignedSlot(executionVertex.getID());
+            final LogicalSlot assignedSlot = reservedSlots.getSlotFor(executionVertex.getID());
             executionVertex
                     .getCurrentExecutionAttempt()
                     .registerProducedPartitions(assignedSlot.getTaskManagerLocation(), false);
             executionVertex.tryAssignResource(assignedSlot);
         }
+
         return executionGraph;
     }
 
     private CompletableFuture<ExecutionGraph> createExecutionGraphAndRestoreStateAsync(
             JobGraph adjustedJobGraph) {
         return CompletableFuture.supplyAsync(
-                () -> {
-                    try {
-                        return createExecutionGraphAndRestoreState(adjustedJobGraph);
-                    } catch (Exception exception) {
-                        throw new CompletionException(exception);
-                    }
-                },
-                ioExecutor);
+                        () -> {
+                            try {
+                                return createExecutionGraphAndRestoreState(adjustedJobGraph);
+                            } catch (Exception exception) {
+                                throw new CompletionException(exception);
+                            }
+                        },
+                        ioExecutor)
+                .handleAsync(
+                        (executionGraph, throwable) -> {
+                            if (throwable != null) {
+                                throw new CompletionException(throwable);
+                            } else {
+                                return executionGraph;
+                            }
+                        },
+                        getMainThreadExecutor());
     }
 
     @Nonnull
@@ -969,11 +993,6 @@ public class AdaptiveScheduler
                 () -> runIfState(expectedState, action), delay.toMillis(), TimeUnit.MILLISECONDS);
     }
 
-    @Override
-    public CreatingExecutionGraph.AssignmentResult tryToAssignSlots(ExecutionGraph executionGraph) {
-        return CreatingExecutionGraph.AssignmentResult.success(executionGraph);
-    }
-
     // ----------------------------------------------------------------
 
     /** Note: Do not call this method from a State constructor or State#onLeave. */
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraph.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraph.java
index 5e21ba6..79a265d 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraph.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraph.java
@@ -22,6 +22,7 @@ import org.apache.flink.api.common.JobStatus;
 import org.apache.flink.runtime.concurrent.FutureUtils;
 import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
 import org.apache.flink.runtime.executiongraph.ExecutionGraph;
+import org.apache.flink.runtime.scheduler.adaptive.allocator.VertexParallelism;
 import org.apache.flink.util.Preconditions;
 
 import org.slf4j.Logger;
@@ -47,23 +48,29 @@ public class CreatingExecutionGraph implements State {
     private final Logger log;
 
     public CreatingExecutionGraph(
-            Context context, CompletableFuture<ExecutionGraph> executionGraphFuture, Logger log) {
+            Context context,
+            CompletableFuture<ExecutionGraphWithVertexParallelism>
+                    executionGraphWithParallelismFuture,
+            Logger log) {
         this.context = context;
         this.log = log;
 
         FutureUtils.assertNoException(
-                executionGraphFuture.handle(
-                        (executionGraph, throwable) -> {
+                executionGraphWithParallelismFuture.handle(
+                        (executionGraphWithVertexParallelism, throwable) -> {
                             context.runIfState(
                                     this,
-                                    () -> handleExecutionGraphCreation(executionGraph, throwable),
+                                    () ->
+                                            handleExecutionGraphCreation(
+                                                    executionGraphWithVertexParallelism, throwable),
                                     Duration.ZERO);
                             return null;
                         }));
     }
 
     private void handleExecutionGraphCreation(
-            @Nullable ExecutionGraph executionGraph, @Nullable Throwable throwable) {
+            @Nullable ExecutionGraphWithVertexParallelism executionGraphWithVertexParallelism,
+            @Nullable Throwable throwable) {
         if (throwable != null) {
             log.info(
                     "Failed to go from {} to {} because the ExecutionGraph creation failed.",
@@ -72,11 +79,16 @@ public class CreatingExecutionGraph implements State {
                     throwable);
             context.goToFinished(context.getArchivedExecutionGraph(JobStatus.FAILED, throwable));
         } else {
-            final AssignmentResult result = context.tryToAssignSlots(executionGraph);
+            final AssignmentResult result =
+                    context.tryToAssignSlots(executionGraphWithVertexParallelism);
 
             if (result.isSuccess()) {
+                log.debug(
+                        "Successfully reserved and assigned the required slots for the ExecutionGraph.");
                 context.goToExecuting(result.getExecutionGraph());
             } else {
+                log.debug(
+                        "Failed to reserve and assign the required slots. Waiting for new resources.");
                 context.goToWaitingForResources();
             }
         }
@@ -159,10 +171,12 @@ public class CreatingExecutionGraph implements State {
          * method returns a successful {@link AssignmentResult} which contains the assigned {@link
          * ExecutionGraph}. If not, then the assignment result is a failure.
          *
-         * @param executionGraph executionGraph to assign slots to
+         * @param executionGraphWithVertexParallelism executionGraphWithVertexParallelism to assign
+         *     slots to resources
          * @return {@link AssignmentResult} representing the result of the assignment
          */
-        AssignmentResult tryToAssignSlots(ExecutionGraph executionGraph);
+        AssignmentResult tryToAssignSlots(
+                ExecutionGraphWithVertexParallelism executionGraphWithVertexParallelism);
     }
 
     /**
@@ -207,16 +221,18 @@ public class CreatingExecutionGraph implements State {
 
         private final Context context;
 
-        private final CompletableFuture<ExecutionGraph> executionGraphFuture;
+        private final CompletableFuture<ExecutionGraphWithVertexParallelism>
+                executionGraphWithParallelismFuture;
 
         private final Logger log;
 
         Factory(
                 Context context,
-                CompletableFuture<ExecutionGraph> executionGraphFuture,
+                CompletableFuture<ExecutionGraphWithVertexParallelism>
+                        executionGraphWithParallelismFuture,
                 Logger log) {
             this.context = context;
-            this.executionGraphFuture = executionGraphFuture;
+            this.executionGraphWithParallelismFuture = executionGraphWithParallelismFuture;
             this.log = log;
         }
 
@@ -227,7 +243,32 @@ public class CreatingExecutionGraph implements State {
 
         @Override
         public CreatingExecutionGraph getState() {
-            return new CreatingExecutionGraph(context, executionGraphFuture, log);
+            return new CreatingExecutionGraph(context, executionGraphWithParallelismFuture, log);
+        }
+    }
+
+    static class ExecutionGraphWithVertexParallelism {
+        private final ExecutionGraph executionGraph;
+
+        private final VertexParallelism vertexParallelism;
+
+        private ExecutionGraphWithVertexParallelism(
+                ExecutionGraph executionGraph, VertexParallelism vertexParallelism) {
+            this.executionGraph = executionGraph;
+            this.vertexParallelism = vertexParallelism;
+        }
+
+        public static ExecutionGraphWithVertexParallelism create(
+                ExecutionGraph executionGraph, VertexParallelism vertexParallelism) {
+            return new ExecutionGraphWithVertexParallelism(executionGraph, vertexParallelism);
+        }
+
+        public ExecutionGraph getExecutionGraph() {
+            return executionGraph;
+        }
+
+        public VertexParallelism getVertexParallelism() {
+            return vertexParallelism;
         }
     }
 }
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Executing.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Executing.java
index 9ab0456..74d4afc 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Executing.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Executing.java
@@ -35,6 +35,7 @@ import org.slf4j.Logger;
 import javax.annotation.Nullable;
 
 import java.time.Duration;
+import java.util.concurrent.ScheduledFuture;
 
 /** State which represents a running job with an {@link ExecutionGraph} and assigned slots. */
 class Executing extends StateWithExecutionGraph implements ResourceConsumer {
@@ -55,6 +56,9 @@ class Executing extends StateWithExecutionGraph implements ResourceConsumer {
         this.userCodeClassLoader = userCodeClassLoader;
 
         deploy();
+
+        // check if new resources have come available in the meantime
+        context.runIfState(this, this::notifyNewResourcesAvailable, Duration.ZERO);
     }
 
     @Override
@@ -206,6 +210,17 @@ class Executing extends StateWithExecutionGraph implements ResourceConsumer {
                 ExecutionGraphHandler executionGraphHandler,
                 OperatorCoordinatorHandler operatorCoordinatorHandler,
                 Throwable failureCause);
+
+        /**
+         * Runs the given action after a delay if the state at this time equals the expected state.
+         *
+         * @param expectedState expectedState describes the required state at the time of running
+         *     the action
+         * @param action action to run if the expected state equals the actual state
+         * @param delay delay after which to run the action
+         * @return a ScheduledFuture representing pending completion of the task
+         */
+        ScheduledFuture<?> runIfState(State expectedState, Runnable action, Duration delay);
     }
 
     /**
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/ParallelismAndResourceAssignments.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/ParallelismAndResourceAssignments.java
deleted file mode 100644
index febf3aa..0000000
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/ParallelismAndResourceAssignments.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.flink.runtime.scheduler.adaptive;
-
-import org.apache.flink.runtime.jobgraph.JobVertexID;
-import org.apache.flink.runtime.jobmaster.LogicalSlot;
-import org.apache.flink.runtime.scheduler.adaptive.allocator.ReservedSlots;
-import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
-import org.apache.flink.util.Preconditions;
-
-import java.util.Map;
-
-/** Assignment of slots to execution vertices. */
-public final class ParallelismAndResourceAssignments {
-    private final ReservedSlots reservedSlots;
-
-    private final Map<JobVertexID, Integer> parallelismPerJobVertex;
-
-    public ParallelismAndResourceAssignments(
-            ReservedSlots reservedSlots, Map<JobVertexID, Integer> parallelismPerJobVertex) {
-        this.reservedSlots = reservedSlots;
-        this.parallelismPerJobVertex = parallelismPerJobVertex;
-    }
-
-    public int getParallelism(JobVertexID jobVertexId) {
-        Preconditions.checkState(parallelismPerJobVertex.containsKey(jobVertexId));
-        return parallelismPerJobVertex.get(jobVertexId);
-    }
-
-    public LogicalSlot getAssignedSlot(ExecutionVertexID executionVertexId) {
-        return reservedSlots.getSlotFor(executionVertexId);
-    }
-}
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/VertexParallelism.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/VertexParallelism.java
index d4be287..0a19a32 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/VertexParallelism.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/VertexParallelism.java
@@ -31,4 +31,6 @@ import java.util.Map;
  */
 public interface VertexParallelism {
     Map<JobVertexID, Integer> getMaxParallelismForVertices();
+
+    int getParallelism(JobVertexID jobVertexId);
 }
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/VertexParallelismWithSlotSharing.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/VertexParallelismWithSlotSharing.java
index 8ed9ace..05bcadf 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/VertexParallelismWithSlotSharing.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/VertexParallelismWithSlotSharing.java
@@ -44,4 +44,9 @@ public class VertexParallelismWithSlotSharing implements VertexParallelism {
     public Map<JobVertexID, Integer> getMaxParallelismForVertices() {
         return vertexParallelism;
     }
+
+    @Override
+    public int getParallelism(JobVertexID jobVertexId) {
+        return vertexParallelism.get(jobVertexId);
+    }
 }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/SlotPoolTestUtils.java b/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/SlotPoolTestUtils.java
index 8bf8c6a..f83e7cd 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/SlotPoolTestUtils.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/SlotPoolTestUtils.java
@@ -38,7 +38,7 @@ public final class SlotPoolTestUtils {
         throw new UnsupportedOperationException("This class should never be instantiated.");
     }
 
-    static TaskManagerGateway createTaskManagerGateway(
+    public static TaskManagerGateway createTaskManagerGateway(
             @Nullable TaskExecutorGateway taskExecutorGateway) {
         return new RpcTaskManagerGateway(
                 taskExecutorGateway == null
@@ -50,7 +50,15 @@ public final class SlotPoolTestUtils {
     @Nonnull
     public static Collection<SlotOffer> offerSlots(
             DeclarativeSlotPool slotPool, Collection<? extends SlotOffer> slotOffers) {
+        return offerSlots(slotPool, slotOffers, createTaskManagerGateway(null));
+    }
+
+    @Nonnull
+    public static Collection<SlotOffer> offerSlots(
+            DeclarativeSlotPool slotPool,
+            Collection<? extends SlotOffer> slotOffers,
+            TaskManagerGateway taskManagerGateway) {
         return slotPool.offerSlots(
-                slotOffers, new LocalTaskManagerLocation(), createTaskManagerGateway(null), 0);
+                slotOffers, new LocalTaskManagerLocation(), taskManagerGateway, 0);
     }
 }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
index 8a433a4..c4ba684 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
@@ -23,6 +23,7 @@ import org.apache.flink.api.common.time.Time;
 import org.apache.flink.configuration.Configuration;
 import org.apache.flink.configuration.JobManagerOptions;
 import org.apache.flink.core.testutils.FlinkMatchers;
+import org.apache.flink.core.testutils.OneShotLatch;
 import org.apache.flink.metrics.Gauge;
 import org.apache.flink.runtime.checkpoint.CheckpointException;
 import org.apache.flink.runtime.checkpoint.CheckpointIDCounter;
@@ -34,6 +35,7 @@ import org.apache.flink.runtime.checkpoint.StandaloneCompletedCheckpointStore;
 import org.apache.flink.runtime.checkpoint.TestingCheckpointIDCounter;
 import org.apache.flink.runtime.checkpoint.TestingCheckpointRecoveryFactory;
 import org.apache.flink.runtime.checkpoint.TestingCompletedCheckpointStore;
+import org.apache.flink.runtime.clusterframework.types.AllocationID;
 import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
 import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutor;
 import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutorServiceAdapter;
@@ -42,7 +44,6 @@ import org.apache.flink.runtime.execution.ExecutionState;
 import org.apache.flink.runtime.execution.SuppressRestartsException;
 import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
 import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
-import org.apache.flink.runtime.executiongraph.ExecutionGraph;
 import org.apache.flink.runtime.executiongraph.TaskExecutionStateTransition;
 import org.apache.flink.runtime.executiongraph.failover.flip1.NoRestartBackoffTimeStrategy;
 import org.apache.flink.runtime.executiongraph.failover.flip1.TestRestartBackoffTimeStrategy;
@@ -58,9 +59,12 @@ import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
 import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration;
 import org.apache.flink.runtime.jobgraph.tasks.JobCheckpointingSettings;
 import org.apache.flink.runtime.jobmanager.PartitionProducerDisposedException;
+import org.apache.flink.runtime.jobmanager.slots.TaskManagerGateway;
 import org.apache.flink.runtime.jobmaster.TestUtils;
 import org.apache.flink.runtime.jobmaster.slotpool.DefaultAllocatedSlotPool;
 import org.apache.flink.runtime.jobmaster.slotpool.DefaultDeclarativeSlotPool;
+import org.apache.flink.runtime.jobmaster.slotpool.SlotPoolTestUtils;
+import org.apache.flink.runtime.messages.Acknowledge;
 import org.apache.flink.runtime.metrics.MetricNames;
 import org.apache.flink.runtime.metrics.MetricRegistry;
 import org.apache.flink.runtime.metrics.groups.JobManagerJobMetricGroup;
@@ -70,15 +74,18 @@ import org.apache.flink.runtime.operators.coordination.TaskNotRunningException;
 import org.apache.flink.runtime.operators.coordination.TestOperatorEvent;
 import org.apache.flink.runtime.rest.handler.legacy.utils.ArchivedExecutionGraphBuilder;
 import org.apache.flink.runtime.scheduler.GloballyTerminalJobStatusListener;
+import org.apache.flink.runtime.scheduler.adaptive.allocator.TestingSlotAllocator;
 import org.apache.flink.runtime.slots.ResourceRequirement;
+import org.apache.flink.runtime.taskexecutor.TestingTaskExecutorGatewayBuilder;
 import org.apache.flink.runtime.taskmanager.LocalTaskManagerLocation;
 import org.apache.flink.runtime.taskmanager.TaskExecutionState;
 import org.apache.flink.runtime.testtasks.NoOpInvokable;
 import org.apache.flink.runtime.util.ResourceCounter;
 import org.apache.flink.runtime.util.TestingFatalErrorHandler;
-import org.apache.flink.util.ExecutorUtils;
+import org.apache.flink.testutils.executor.TestExecutorResource;
 import org.apache.flink.util.FlinkException;
 import org.apache.flink.util.TestLogger;
+import org.apache.flink.util.function.FunctionUtils;
 
 import org.hamcrest.MatcherAssert;
 import org.hamcrest.Matchers;
@@ -93,6 +100,9 @@ import javax.annotation.Nullable;
 import java.io.File;
 import java.io.IOException;
 import java.time.Duration;
+import java.util.Optional;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
@@ -109,6 +119,7 @@ import static org.hamcrest.Matchers.contains;
 import static org.hamcrest.Matchers.instanceOf;
 import static org.hamcrest.Matchers.notNullValue;
 import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertThat;
 
 /** Tests for the {@link AdaptiveScheduler}. */
@@ -119,6 +130,10 @@ public class AdaptiveSchedulerTest extends TestLogger {
 
     @ClassRule public static final TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder();
 
+    @ClassRule
+    public static final TestExecutorResource<ScheduledExecutorService> TEST_EXECUTOR_RESOURCE =
+            new TestExecutorResource<>(Executors::newSingleThreadScheduledExecutor);
+
     static {
         JOB_VERTEX = new JobVertex("v1");
         JOB_VERTEX.setParallelism(PARALLELISM);
@@ -128,6 +143,10 @@ public class AdaptiveSchedulerTest extends TestLogger {
     private final ManuallyTriggeredComponentMainThreadExecutor mainThreadExecutor =
             new ManuallyTriggeredComponentMainThreadExecutor(Thread.currentThread());
 
+    private final ComponentMainThreadExecutor singleThreadMainThreadExecutor =
+            ComponentMainThreadExecutorServiceAdapter.forSingleThreadExecutor(
+                    TEST_EXECUTOR_RESOURCE.getExecutor());
+
     @Test
     public void testInitialState() throws Exception {
         final AdaptiveScheduler scheduler =
@@ -236,22 +255,39 @@ public class AdaptiveSchedulerTest extends TestLogger {
         final DefaultDeclarativeSlotPool declarativeSlotPool =
                 createDeclarativeSlotPool(jobGraph.getJobID());
 
+        final Configuration configuration = new Configuration();
+        configuration.set(JobManagerOptions.RESOURCE_WAIT_TIMEOUT, Duration.ofMillis(1L));
+
         final AdaptiveScheduler scheduler =
-                new AdaptiveSchedulerBuilder(jobGraph, mainThreadExecutor)
+                new AdaptiveSchedulerBuilder(jobGraph, singleThreadMainThreadExecutor)
                         .setDeclarativeSlotPool(declarativeSlotPool)
+                        .setJobMasterConfiguration(configuration)
                         .build();
 
-        scheduler.startScheduling();
-
         final int numAvailableSlots = 1;
 
-        offerSlots(
-                declarativeSlotPool,
-                createSlotOffersForResourceRequirements(
-                        ResourceCounter.withResource(ResourceProfile.UNKNOWN, numAvailableSlots)));
+        final OneShotLatch submitTaskLatch = new OneShotLatch();
+        final TaskManagerGateway taskManagerGateway =
+                createWaitingForTaskSubmissionTaskManagerGateway(submitTaskLatch);
+
+        singleThreadMainThreadExecutor.execute(
+                () -> {
+                    scheduler.startScheduling();
+                    offerSlots(
+                            declarativeSlotPool,
+                            createSlotOffersForResourceRequirements(
+                                    ResourceCounter.withResource(
+                                            ResourceProfile.UNKNOWN, numAvailableSlots)),
+                            taskManagerGateway);
+                });
 
-        final ExecutionGraph executionGraph =
-                scheduler.createExecutionGraphWithAvailableResources();
+        submitTaskLatch.await();
+
+        final ArchivedExecutionGraph executionGraph =
+                CompletableFuture.supplyAsync(
+                                () -> scheduler.requestJob().getArchivedExecutionGraph(),
+                                singleThreadMainThreadExecutor)
+                        .join();
 
         assertThat(
                 executionGraph.getJobVertex(JOB_VERTEX.getID()).getParallelism(),
@@ -267,20 +303,33 @@ public class AdaptiveSchedulerTest extends TestLogger {
                 createDeclarativeSlotPool(jobGraph.getJobID());
 
         final AdaptiveScheduler adaptiveScheduler =
-                new AdaptiveSchedulerBuilder(jobGraph, mainThreadExecutor)
+                new AdaptiveSchedulerBuilder(jobGraph, singleThreadMainThreadExecutor)
                         .setInitializationTimestamp(initializationTimestamp)
                         .setDeclarativeSlotPool(declarativeSlotPool)
                         .build();
 
-        adaptiveScheduler.startScheduling();
+        final OneShotLatch submitTaskLatch = new OneShotLatch();
+        final TaskManagerGateway taskManagerGateway =
+                createWaitingForTaskSubmissionTaskManagerGateway(submitTaskLatch);
 
-        offerSlots(
-                declarativeSlotPool,
-                createSlotOffersForResourceRequirements(
-                        ResourceCounter.withResource(ResourceProfile.UNKNOWN, 1)));
+        singleThreadMainThreadExecutor.execute(
+                () -> {
+                    adaptiveScheduler.startScheduling();
+                    offerSlots(
+                            declarativeSlotPool,
+                            createSlotOffersForResourceRequirements(
+                                    ResourceCounter.withResource(
+                                            ResourceProfile.UNKNOWN, PARALLELISM)),
+                            taskManagerGateway);
+                });
 
-        final ExecutionGraph executionGraph =
-                adaptiveScheduler.createExecutionGraphWithAvailableResources();
+        submitTaskLatch.await();
+
+        final ArchivedExecutionGraph executionGraph =
+                CompletableFuture.supplyAsync(
+                                () -> adaptiveScheduler.requestJob().getArchivedExecutionGraph(),
+                                singleThreadMainThreadExecutor)
+                        .join();
 
         assertThat(
                 executionGraph.getStatusTimestamp(JobStatus.INITIALIZING),
@@ -380,9 +429,10 @@ public class AdaptiveSchedulerTest extends TestLogger {
 
         final Configuration configuration = new Configuration();
         configuration.set(JobManagerOptions.MIN_PARALLELISM_INCREASE, 1);
+        configuration.set(JobManagerOptions.RESOURCE_WAIT_TIMEOUT, Duration.ofMillis(1L));
 
         final AdaptiveScheduler scheduler =
-                new AdaptiveSchedulerBuilder(jobGraph, mainThreadExecutor)
+                new AdaptiveSchedulerBuilder(jobGraph, singleThreadMainThreadExecutor)
                         .setJobMasterConfiguration(configuration)
                         .setJobManagerJobMetricGroup(
                                 new JobManagerJobMetricGroup(
@@ -395,39 +445,52 @@ public class AdaptiveSchedulerTest extends TestLogger {
 
         final Gauge<Integer> numRestartsMetric = numRestartsMetricFuture.get();
 
-        scheduler.startScheduling();
-
         final SimpleAckingTaskManagerGateway taskManagerGateway =
                 new SimpleAckingTaskManagerGateway();
+        final BlockingQueue<AllocationID> submittedTasks = new ArrayBlockingQueue<>(5);
+        taskManagerGateway.setSubmitConsumer(
+                taskDeploymentDescriptor ->
+                        submittedTasks.offer(taskDeploymentDescriptor.getAllocationId()));
+
         taskManagerGateway.setCancelConsumer(
                 executionAttemptId ->
-                        mainThreadExecutor.execute(
+                        singleThreadMainThreadExecutor.execute(
                                 () ->
                                         scheduler.updateTaskExecutionState(
                                                 new TaskExecutionState(
                                                         executionAttemptId,
                                                         ExecutionState.CANCELED))));
 
-        declarativeSlotPool.offerSlots(
-                createSlotOffersForResourceRequirements(
-                        ResourceCounter.withResource(ResourceProfile.UNKNOWN, 1)),
-                new LocalTaskManagerLocation(),
-                taskManagerGateway,
-                System.currentTimeMillis());
+        singleThreadMainThreadExecutor.execute(
+                () -> {
+                    scheduler.startScheduling();
+
+                    declarativeSlotPool.offerSlots(
+                            createSlotOffersForResourceRequirements(
+                                    ResourceCounter.withResource(ResourceProfile.UNKNOWN, 1)),
+                            new LocalTaskManagerLocation(),
+                            taskManagerGateway,
+                            System.currentTimeMillis());
+                });
 
-        // trigger resource timeout and the deployment of the job
-        mainThreadExecutor.triggerAllNonPeriodicTasks();
+        // wait for the first task submission
+        submittedTasks.take();
 
         assertThat(numRestartsMetric.getValue(), is(0));
 
-        // offer more slots, which will cause a restart in order to scale up
-        offerSlots(
-                declarativeSlotPool,
-                createSlotOffersForResourceRequirements(
-                        ResourceCounter.withResource(ResourceProfile.UNKNOWN, PARALLELISM)));
+        singleThreadMainThreadExecutor.execute(
+                () -> {
+                    // offer more slots, which will cause a restart in order to scale up
+                    offerSlots(
+                            declarativeSlotPool,
+                            createSlotOffersForResourceRequirements(
+                                    ResourceCounter.withResource(
+                                            ResourceProfile.UNKNOWN, PARALLELISM)),
+                            taskManagerGateway);
+                });
 
-        // trigger cancellation of tasks and the restart
-        mainThreadExecutor.triggerAllNonPeriodicTasks();
+        // wait for the second task submission
+        submittedTasks.take();
 
         assertThat(numRestartsMetric.getValue(), is(1));
     }
@@ -731,47 +794,34 @@ public class AdaptiveSchedulerTest extends TestLogger {
         final GloballyTerminalJobStatusListener jobStatusListener =
                 new GloballyTerminalJobStatusListener();
 
-        final ScheduledExecutorService singleThreadExecutor =
-                Executors.newSingleThreadScheduledExecutor();
-
-        try {
-            final ComponentMainThreadExecutor singleMainThreadExecutor =
-                    ComponentMainThreadExecutorServiceAdapter.forSingleThreadExecutor(
-                            singleThreadExecutor);
-            final AdaptiveScheduler adaptiveScheduler =
-                    new AdaptiveSchedulerBuilder(jobGraphWithNewOperator, singleMainThreadExecutor)
-                            .setDeclarativeSlotPool(declarativeSlotPool)
-                            .setJobStatusListener(jobStatusListener)
-                            .build();
-
-            adaptiveScheduler.startScheduling();
-
-            singleMainThreadExecutor.execute(
-                    () ->
-                            offerSlots(
-                                    declarativeSlotPool,
-                                    createSlotOffersForResourceRequirements(
-                                            ResourceCounter.withResource(
-                                                    ResourceProfile.UNKNOWN, 1))));
-
-            assertThat(jobStatusListener.getTerminationFuture().join(), is(JobStatus.FAILED));
-
-            final ArchivedExecutionGraph archivedExecutionGraph =
-                    CompletableFuture.supplyAsync(
-                                    () ->
-                                            adaptiveScheduler
-                                                    .requestJob()
-                                                    .getArchivedExecutionGraph(),
-                                    singleMainThreadExecutor)
-                            .join();
-
-            assertThat(archivedExecutionGraph.getState(), is(JobStatus.FAILED));
-            assertThat(
-                    archivedExecutionGraph.getFailureInfo().getException(),
-                    FlinkMatchers.containsMessage("Failed to rollback to checkpoint/savepoint"));
-        } finally {
-            ExecutorUtils.gracefulShutdown(10L, TimeUnit.SECONDS, singleThreadExecutor);
-        }
+        final AdaptiveScheduler adaptiveScheduler =
+                new AdaptiveSchedulerBuilder(
+                                jobGraphWithNewOperator, singleThreadMainThreadExecutor)
+                        .setDeclarativeSlotPool(declarativeSlotPool)
+                        .setJobStatusListener(jobStatusListener)
+                        .build();
+
+        singleThreadMainThreadExecutor.execute(
+                () -> {
+                    adaptiveScheduler.startScheduling();
+                    offerSlots(
+                            declarativeSlotPool,
+                            createSlotOffersForResourceRequirements(
+                                    ResourceCounter.withResource(ResourceProfile.UNKNOWN, 1)));
+                });
+
+        assertThat(jobStatusListener.getTerminationFuture().join(), is(JobStatus.FAILED));
+
+        final ArchivedExecutionGraph archivedExecutionGraph =
+                CompletableFuture.supplyAsync(
+                                () -> adaptiveScheduler.requestJob().getArchivedExecutionGraph(),
+                                singleThreadMainThreadExecutor)
+                        .join();
+
+        assertThat(archivedExecutionGraph.getState(), is(JobStatus.FAILED));
+        assertThat(
+                archivedExecutionGraph.getFailureInfo().getException(),
+                FlinkMatchers.containsMessage("Failed to rollback to checkpoint/savepoint"));
     }
 
     @Test
@@ -807,26 +857,81 @@ public class AdaptiveSchedulerTest extends TestLogger {
                 createDeclarativeSlotPool(jobGraphWithNewOperator.getJobID());
 
         AdaptiveScheduler adaptiveScheduler =
-                new AdaptiveSchedulerBuilder(jobGraphWithNewOperator, mainThreadExecutor)
+                new AdaptiveSchedulerBuilder(
+                                jobGraphWithNewOperator, singleThreadMainThreadExecutor)
                         .setCheckpointRecoveryFactory(testingCheckpointRecoveryFactory)
                         .setDeclarativeSlotPool(declarativeSlotPool)
                         .build();
 
-        adaptiveScheduler.startScheduling();
+        final OneShotLatch submitTaskLatch = new OneShotLatch();
+        final TaskManagerGateway taskManagerGateway =
+                createWaitingForTaskSubmissionTaskManagerGateway(submitTaskLatch);
 
-        offerSlots(
-                declarativeSlotPool,
-                createSlotOffersForResourceRequirements(
-                        ResourceCounter.withResource(ResourceProfile.UNKNOWN, 1)));
+        singleThreadMainThreadExecutor.execute(
+                () -> {
+                    adaptiveScheduler.startScheduling();
+
+                    offerSlots(
+                            declarativeSlotPool,
+                            createSlotOffersForResourceRequirements(
+                                    ResourceCounter.withResource(ResourceProfile.UNKNOWN, 1)),
+                            taskManagerGateway);
+                });
+
+        submitTaskLatch.await();
 
         // starting and offering the required slots should trigger the ExecutionGraph creation
-        final CompletedCheckpoint savepoint = completedCheckpointStore.getLatestCheckpoint(false);
+        final CompletedCheckpoint savepoint =
+                CompletableFuture.supplyAsync(
+                                FunctionUtils.uncheckedSupplier(
+                                        () -> completedCheckpointStore.getLatestCheckpoint(false)),
+                                singleThreadMainThreadExecutor)
+                        .join();
 
         MatcherAssert.assertThat(savepoint, notNullValue());
 
         MatcherAssert.assertThat(savepoint.getCheckpointID(), Matchers.is(savepointId));
     }
 
+    @Nonnull
+    private TaskManagerGateway createWaitingForTaskSubmissionTaskManagerGateway(
+            OneShotLatch submitTaskLatch) {
+        final TaskManagerGateway taskManagerGateway =
+                SlotPoolTestUtils.createTaskManagerGateway(
+                        new TestingTaskExecutorGatewayBuilder()
+                                .setSubmitTaskConsumer(
+                                        (taskDeploymentDescriptor, jobMasterId) -> {
+                                            submitTaskLatch.trigger();
+                                            return CompletableFuture.completedFuture(
+                                                    Acknowledge.get());
+                                        })
+                                .createTestingTaskExecutorGateway());
+        return taskManagerGateway;
+    }
+
+    @Test
+    public void testTryToAssignSlotsReturnsNotPossibleIfExpectedResourcesAreNotAvailable()
+            throws Exception {
+
+        final TestingSlotAllocator slotAllocator =
+                TestingSlotAllocator.newBuilder()
+                        .setTryReserveResourcesFunction(ignored -> Optional.empty())
+                        .build();
+
+        final AdaptiveScheduler adaptiveScheduler =
+                new AdaptiveSchedulerBuilder(createJobGraph(), mainThreadExecutor)
+                        .setSlotAllocator(slotAllocator)
+                        .build();
+
+        final CreatingExecutionGraph.AssignmentResult assignmentResult =
+                adaptiveScheduler.tryToAssignSlots(
+                        CreatingExecutionGraph.ExecutionGraphWithVertexParallelism.create(
+                                new StateTrackingMockExecutionGraph(),
+                                new CreatingExecutionGraphTest.TestingVertexParallelism()));
+
+        assertFalse(assignmentResult.isSuccess());
+    }
+
     // ---------------------------------------------------------------------------------------------
     // Utils
     // ---------------------------------------------------------------------------------------------
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraphTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraphTest.java
index a352734..12d56da 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraphTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/CreatingExecutionGraphTest.java
@@ -23,6 +23,8 @@ import org.apache.flink.api.common.JobStatus;
 import org.apache.flink.core.testutils.CompletedScheduledFuture;
 import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
 import org.apache.flink.runtime.executiongraph.ExecutionGraph;
+import org.apache.flink.runtime.jobgraph.JobVertexID;
+import org.apache.flink.runtime.scheduler.adaptive.allocator.VertexParallelism;
 import org.apache.flink.util.FlinkException;
 import org.apache.flink.util.TestLogger;
 
@@ -31,6 +33,7 @@ import org.junit.Test;
 import javax.annotation.Nullable;
 
 import java.time.Duration;
+import java.util.Map;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ScheduledFuture;
 import java.util.function.Consumer;
@@ -88,52 +91,61 @@ public class CreatingExecutionGraphTest extends TestLogger {
     @Test
     public void testFailedExecutionGraphCreationTransitionsToFinished() throws Exception {
         try (MockCreatingExecutionGraphContext context = new MockCreatingExecutionGraphContext()) {
-            final CompletableFuture<ExecutionGraph> executionGraphFuture =
-                    new CompletableFuture<>();
+            final CompletableFuture<CreatingExecutionGraph.ExecutionGraphWithVertexParallelism>
+                    executionGraphWithVertexParallelismFuture = new CompletableFuture<>();
             final CreatingExecutionGraph creatingExecutionGraph =
-                    new CreatingExecutionGraph(context, executionGraphFuture, log);
+                    new CreatingExecutionGraph(
+                            context, executionGraphWithVertexParallelismFuture, log);
 
             context.setExpectFinished(
                     archivedExecutionGraph ->
                             assertThat(archivedExecutionGraph.getState(), is(JobStatus.FAILED)));
 
-            executionGraphFuture.completeExceptionally(new FlinkException("Test exception"));
+            executionGraphWithVertexParallelismFuture.completeExceptionally(
+                    new FlinkException("Test exception"));
         }
     }
 
     @Test
     public void testNotPossibleSlotAssignmentTransitionsToWaitingForResources() throws Exception {
         try (MockCreatingExecutionGraphContext context = new MockCreatingExecutionGraphContext()) {
-            final CompletableFuture<ExecutionGraph> executionGraphFuture =
-                    new CompletableFuture<>();
+            final CompletableFuture<CreatingExecutionGraph.ExecutionGraphWithVertexParallelism>
+                    executionGraphWithVertexParallelismFuture = new CompletableFuture<>();
             final CreatingExecutionGraph creatingExecutionGraph =
-                    new CreatingExecutionGraph(context, executionGraphFuture, log);
+                    new CreatingExecutionGraph(
+                            context, executionGraphWithVertexParallelismFuture, log);
 
             context.setTryToAssignSlotsFunction(
                     ignored -> CreatingExecutionGraph.AssignmentResult.notPossible());
             context.setExpectWaitingForResources();
 
-            executionGraphFuture.complete(new StateTrackingMockExecutionGraph());
+            executionGraphWithVertexParallelismFuture.complete(
+                    CreatingExecutionGraph.ExecutionGraphWithVertexParallelism.create(
+                            new StateTrackingMockExecutionGraph(), new TestingVertexParallelism()));
         }
     }
 
     @Test
     public void testSuccessfulSlotAssignmentTransitionsToExecuting() throws Exception {
         try (MockCreatingExecutionGraphContext context = new MockCreatingExecutionGraphContext()) {
-            final CompletableFuture<ExecutionGraph> executionGraphFuture =
-                    new CompletableFuture<>();
+            final CompletableFuture<CreatingExecutionGraph.ExecutionGraphWithVertexParallelism>
+                    executionGraphWithvertexParallelismFuture = new CompletableFuture<>();
             final CreatingExecutionGraph creatingExecutionGraph =
-                    new CreatingExecutionGraph(context, executionGraphFuture, log);
+                    new CreatingExecutionGraph(
+                            context, executionGraphWithvertexParallelismFuture, log);
 
             final StateTrackingMockExecutionGraph executionGraph =
                     new StateTrackingMockExecutionGraph();
 
-            context.setTryToAssignSlotsFunction(CreatingExecutionGraph.AssignmentResult::success);
+            context.setTryToAssignSlotsFunction(
+                    e -> CreatingExecutionGraph.AssignmentResult.success(e.getExecutionGraph()));
             context.setExpectedExecuting(
                     actualExecutionGraph ->
                             assertThat(actualExecutionGraph, sameInstance(executionGraph)));
 
-            executionGraphFuture.complete(executionGraph);
+            executionGraphWithvertexParallelismFuture.complete(
+                    CreatingExecutionGraph.ExecutionGraphWithVertexParallelism.create(
+                            executionGraph, new TestingVertexParallelism()));
         }
     }
 
@@ -146,8 +158,11 @@ public class CreatingExecutionGraphTest extends TestLogger {
         private final StateValidator<ExecutionGraph> executingStateValidator =
                 new StateValidator<>("Executing");
 
-        private Function<ExecutionGraph, CreatingExecutionGraph.AssignmentResult>
-                tryToAssignSlotsFunction = CreatingExecutionGraph.AssignmentResult::success;
+        private Function<
+                        CreatingExecutionGraph.ExecutionGraphWithVertexParallelism,
+                        CreatingExecutionGraph.AssignmentResult>
+                tryToAssignSlotsFunction =
+                        e -> CreatingExecutionGraph.AssignmentResult.success(e.getExecutionGraph());
 
         private boolean hadStateTransitionHappened = false;
 
@@ -164,7 +179,9 @@ public class CreatingExecutionGraphTest extends TestLogger {
         }
 
         public void setTryToAssignSlotsFunction(
-                Function<ExecutionGraph, CreatingExecutionGraph.AssignmentResult>
+                Function<
+                                CreatingExecutionGraph.ExecutionGraphWithVertexParallelism,
+                                CreatingExecutionGraph.AssignmentResult>
                         tryToAssignSlotsFunction) {
             this.tryToAssignSlotsFunction = tryToAssignSlotsFunction;
         }
@@ -199,8 +216,9 @@ public class CreatingExecutionGraphTest extends TestLogger {
 
         @Override
         public CreatingExecutionGraph.AssignmentResult tryToAssignSlots(
-                ExecutionGraph executionGraph) {
-            return tryToAssignSlotsFunction.apply(executionGraph);
+                CreatingExecutionGraph.ExecutionGraphWithVertexParallelism
+                        executionGraphWithVertexParallelism) {
+            return tryToAssignSlotsFunction.apply(executionGraphWithVertexParallelism);
         }
 
         @Override
@@ -216,4 +234,17 @@ public class CreatingExecutionGraphTest extends TestLogger {
             executingStateValidator.close();
         }
     }
+
+    static final class TestingVertexParallelism implements VertexParallelism {
+
+        @Override
+        public Map<JobVertexID, Integer> getMaxParallelismForVertices() {
+            throw new UnsupportedOperationException("Is not supported");
+        }
+
+        @Override
+        public int getParallelism(JobVertexID jobVertexId) {
+            throw new UnsupportedOperationException("Is not supported");
+        }
+    }
 }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/ExecutingTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/ExecutingTest.java
index 76f04f0..f8a1876 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/ExecutingTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/ExecutingTest.java
@@ -21,6 +21,7 @@ package org.apache.flink.runtime.scheduler.adaptive;
 import org.apache.flink.api.common.JobID;
 import org.apache.flink.api.common.JobStatus;
 import org.apache.flink.api.common.time.Time;
+import org.apache.flink.core.testutils.CompletedScheduledFuture;
 import org.apache.flink.runtime.JobException;
 import org.apache.flink.runtime.blob.BlobWriter;
 import org.apache.flink.runtime.blob.PermanentBlobKey;
@@ -65,6 +66,7 @@ import java.time.Duration;
 import java.util.Collections;
 import java.util.concurrent.Executor;
 import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.ScheduledFuture;
 import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.function.Supplier;
@@ -289,6 +291,20 @@ public class ExecutingTest extends TestLogger {
         }
     }
 
+    @Test
+    public void testExecutingChecksForNewResourcesWhenBeingCreated() throws Exception {
+        try (MockExecutingContext context = new MockExecutingContext()) {
+            context.setCanScaleUp(() -> true);
+            context.setExpectRestarting(
+                    restartingArguments -> {
+                        // expect immediate restart on scale up
+                        assertThat(restartingArguments.getBackoffTime(), is(Duration.ZERO));
+                    });
+
+            final Executing executing = new ExecutingStateBuilder().build(context);
+        }
+    }
+
     private final class ExecutingStateBuilder {
         private ExecutionGraph executionGraph =
                 TestingDefaultExecutionGraphBuilder.newBuilder().build();
@@ -344,7 +360,7 @@ public class ExecutingTest extends TestLogger {
                 new StateValidator<>("cancelling");
 
         private Function<Throwable, Executing.FailureResult> howToHandleFailure;
-        private Supplier<Boolean> canScaleUp;
+        private Supplier<Boolean> canScaleUp = () -> false;
 
         public void setExpectFailing(Consumer<FailingArguments> asserter) {
             failingStateValidator.expectInput(asserter);
@@ -420,6 +436,15 @@ public class ExecutingTest extends TestLogger {
         }
 
         @Override
+        public ScheduledFuture<?> runIfState(State expectedState, Runnable action, Duration delay) {
+            if (!hadStateTransition) {
+                action.run();
+            }
+
+            return CompletedScheduledFuture.create(null);
+        }
+
+        @Override
         public void close() throws Exception {
             super.close();
             failingStateValidator.close();
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/StateTrackingMockExecutionGraph.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/StateTrackingMockExecutionGraph.java
index fa7eaa3..ca28a16 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/StateTrackingMockExecutionGraph.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/StateTrackingMockExecutionGraph.java
@@ -226,12 +226,14 @@ class StateTrackingMockExecutionGraph implements ExecutionGraph {
         return new StringifiedAccumulatorResult[0];
     }
 
-    // -- remaining interface implementations: all unsupported
+    @Override
+    public void start(@Nonnull ComponentMainThreadExecutor jobMasterMainThreadExecutor) {}
 
     @Override
-    public void start(@Nonnull ComponentMainThreadExecutor jobMasterMainThreadExecutor) {
-        throw new UnsupportedOperationException();
-    }
+    public void setInternalTaskFailuresListener(
+            InternalFailuresListener internalTaskFailuresListener) {}
+
+    // -- remaining interface implementations: all unsupported
 
     @Override
     public SchedulingTopology getSchedulingTopology() {
@@ -303,12 +305,6 @@ class StateTrackingMockExecutionGraph implements ExecutionGraph {
     }
 
     @Override
-    public void setInternalTaskFailuresListener(
-            InternalFailuresListener internalTaskFailuresListener) {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
     public void attachJobGraph(List<JobVertex> topologiallySorted) throws JobException {
         throw new UnsupportedOperationException();
     }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/TestingSlotAllocator.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/TestingSlotAllocator.java
new file mode 100644
index 0000000..aa6fd7b
--- /dev/null
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/TestingSlotAllocator.java
@@ -0,0 +1,120 @@
+/*
+ * 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.flink.runtime.scheduler.adaptive.allocator;
+
+import org.apache.flink.runtime.jobmaster.SlotInfo;
+import org.apache.flink.runtime.util.ResourceCounter;
+
+import java.util.Collection;
+import java.util.Optional;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+
+/** Testing implementation of {@link SlotAllocator}. */
+public class TestingSlotAllocator implements SlotAllocator {
+
+    private final Function<Iterable<JobInformation.VertexInformation>, ResourceCounter>
+            calculateRequiredSlotsFunction;
+
+    private final BiFunction<
+                    JobInformation,
+                    Collection<? extends SlotInfo>,
+                    Optional<? extends VertexParallelism>>
+            determineParallelismFunction;
+
+    private final Function<VertexParallelism, Optional<ReservedSlots>> tryReserveResourcesFunction;
+
+    private TestingSlotAllocator(
+            Function<Iterable<JobInformation.VertexInformation>, ResourceCounter>
+                    calculateRequiredSlotsFunction,
+            BiFunction<
+                            JobInformation,
+                            Collection<? extends SlotInfo>,
+                            Optional<? extends VertexParallelism>>
+                    determineParallelismFunction,
+            Function<VertexParallelism, Optional<ReservedSlots>> tryReserveResourcesFunction) {
+        this.calculateRequiredSlotsFunction = calculateRequiredSlotsFunction;
+        this.determineParallelismFunction = determineParallelismFunction;
+        this.tryReserveResourcesFunction = tryReserveResourcesFunction;
+    }
+
+    @Override
+    public ResourceCounter calculateRequiredSlots(
+            Iterable<JobInformation.VertexInformation> vertices) {
+        return calculateRequiredSlotsFunction.apply(vertices);
+    }
+
+    @Override
+    public Optional<? extends VertexParallelism> determineParallelism(
+            JobInformation jobInformation, Collection<? extends SlotInfo> slots) {
+        return determineParallelismFunction.apply(jobInformation, slots);
+    }
+
+    @Override
+    public Optional<ReservedSlots> tryReserveResources(VertexParallelism vertexParallelism) {
+        return tryReserveResourcesFunction.apply(vertexParallelism);
+    }
+
+    public static Builder newBuilder() {
+        return new Builder();
+    }
+
+    /** Builder for the {@link TestingSlotAllocator}. */
+    public static final class Builder {
+        private Function<Iterable<JobInformation.VertexInformation>, ResourceCounter>
+                calculateRequiredSlotsFunction = ignored -> ResourceCounter.empty();
+        private BiFunction<
+                        JobInformation,
+                        Collection<? extends SlotInfo>,
+                        Optional<? extends VertexParallelism>>
+                determineParallelismFunction = (ignoredA, ignoredB) -> Optional.empty();
+        private Function<VertexParallelism, Optional<ReservedSlots>> tryReserveResourcesFunction =
+                ignored -> Optional.empty();
+
+        public Builder setCalculateRequiredSlotsFunction(
+                Function<Iterable<JobInformation.VertexInformation>, ResourceCounter>
+                        calculateRequiredSlotsFunction) {
+            this.calculateRequiredSlotsFunction = calculateRequiredSlotsFunction;
+            return this;
+        }
+
+        public Builder setDetermineParallelismFunction(
+                BiFunction<
+                                JobInformation,
+                                Collection<? extends SlotInfo>,
+                                Optional<? extends VertexParallelism>>
+                        determineParallelismFunction) {
+            this.determineParallelismFunction = determineParallelismFunction;
+            return this;
+        }
+
+        public Builder setTryReserveResourcesFunction(
+                Function<VertexParallelism, Optional<ReservedSlots>> tryReserveResourcesFunction) {
+            this.tryReserveResourcesFunction = tryReserveResourcesFunction;
+            return this;
+        }
+
+        public TestingSlotAllocator build() {
+            return new TestingSlotAllocator(
+                    calculateRequiredSlotsFunction,
+                    determineParallelismFunction,
+                    tryReserveResourcesFunction);
+        }
+    }
+}

[flink] 12/17: [hotfix] Factor ExecutionGraph creation out into ExecutionGraphFactory

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit fb94512ae02df71cf6ef9255e96852b3220f5c9a
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Tue Mar 16 11:57:11 2021 +0100

    [hotfix] Factor ExecutionGraph creation out into ExecutionGraphFactory
    
    Using the ExecutionGraphFactory for creating and restoring an ExecutionGraph allows
    to share the functionality between the DefaultScheduler and the AdaptiveScheduler.
---
 .../scheduler/DefaultExecutionGraphFactory.java    | 169 +++++++++++++++++++++
 .../flink/runtime/scheduler/DefaultScheduler.java  |  24 +--
 .../runtime/scheduler/DefaultSchedulerFactory.java |  22 ++-
 .../runtime/scheduler/ExecutionGraphFactory.java   |  59 +++++++
 .../flink/runtime/scheduler/SchedulerBase.java     | 149 ++----------------
 .../scheduler/adaptive/AdaptiveScheduler.java      | 123 ++-------------
 .../adaptive/AdaptiveSchedulerFactory.java         |  24 ++-
 .../DefaultExecutionGraphFactoryTest.java          | 156 +++++++++++++++++++
 .../runtime/scheduler/DefaultSchedulerTest.java    |  88 -----------
 .../runtime/scheduler/SchedulerTestingUtils.java   |  22 ++-
 .../adaptive/AdaptiveSchedulerBuilder.java         |  24 ++-
 .../scheduler/adaptive/AdaptiveSchedulerTest.java  | 144 ------------------
 12 files changed, 481 insertions(+), 523 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultExecutionGraphFactory.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultExecutionGraphFactory.java
new file mode 100644
index 0000000..3dbb80d
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultExecutionGraphFactory.java
@@ -0,0 +1,169 @@
+/*
+ * 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.flink.runtime.scheduler;
+
+import org.apache.flink.api.common.time.Time;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.blob.BlobWriter;
+import org.apache.flink.runtime.checkpoint.CheckpointCoordinator;
+import org.apache.flink.runtime.checkpoint.CheckpointIDCounter;
+import org.apache.flink.runtime.checkpoint.CheckpointsCleaner;
+import org.apache.flink.runtime.checkpoint.CompletedCheckpointStore;
+import org.apache.flink.runtime.deployment.TaskDeploymentDescriptorFactory;
+import org.apache.flink.runtime.executiongraph.DefaultExecutionGraphBuilder;
+import org.apache.flink.runtime.executiongraph.ExecutionDeploymentListener;
+import org.apache.flink.runtime.executiongraph.ExecutionGraph;
+import org.apache.flink.runtime.executiongraph.ExecutionStateUpdateListener;
+import org.apache.flink.runtime.executiongraph.VertexAttemptNumberStore;
+import org.apache.flink.runtime.io.network.partition.JobMasterPartitionTracker;
+import org.apache.flink.runtime.jobgraph.JobGraph;
+import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
+import org.apache.flink.runtime.jobmaster.ExecutionDeploymentTracker;
+import org.apache.flink.runtime.jobmaster.ExecutionDeploymentTrackerDeploymentListenerAdapter;
+import org.apache.flink.runtime.metrics.groups.JobManagerJobMetricGroup;
+import org.apache.flink.runtime.shuffle.ShuffleMaster;
+
+import org.slf4j.Logger;
+
+import java.util.HashSet;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledExecutorService;
+
+/** Default {@link ExecutionGraphFactory} implementation. */
+public class DefaultExecutionGraphFactory implements ExecutionGraphFactory {
+
+    private final Configuration configuration;
+    private final ClassLoader userCodeClassLoader;
+    private final ExecutionDeploymentTracker executionDeploymentTracker;
+    private final ScheduledExecutorService futureExecutor;
+    private final Executor ioExecutor;
+    private final Time rpcTimeout;
+    private final JobManagerJobMetricGroup jobManagerJobMetricGroup;
+    private final BlobWriter blobWriter;
+    private final ShuffleMaster<?> shuffleMaster;
+    private final JobMasterPartitionTracker jobMasterPartitionTracker;
+
+    public DefaultExecutionGraphFactory(
+            Configuration configuration,
+            ClassLoader userCodeClassLoader,
+            ExecutionDeploymentTracker executionDeploymentTracker,
+            ScheduledExecutorService futureExecutor,
+            Executor ioExecutor,
+            Time rpcTimeout,
+            JobManagerJobMetricGroup jobManagerJobMetricGroup,
+            BlobWriter blobWriter,
+            ShuffleMaster<?> shuffleMaster,
+            JobMasterPartitionTracker jobMasterPartitionTracker) {
+        this.configuration = configuration;
+        this.userCodeClassLoader = userCodeClassLoader;
+        this.executionDeploymentTracker = executionDeploymentTracker;
+        this.futureExecutor = futureExecutor;
+        this.ioExecutor = ioExecutor;
+        this.rpcTimeout = rpcTimeout;
+        this.jobManagerJobMetricGroup = jobManagerJobMetricGroup;
+        this.blobWriter = blobWriter;
+        this.shuffleMaster = shuffleMaster;
+        this.jobMasterPartitionTracker = jobMasterPartitionTracker;
+    }
+
+    @Override
+    public ExecutionGraph createAndRestoreExecutionGraph(
+            JobGraph jobGraph,
+            CompletedCheckpointStore completedCheckpointStore,
+            CheckpointsCleaner checkpointsCleaner,
+            CheckpointIDCounter checkpointIdCounter,
+            TaskDeploymentDescriptorFactory.PartitionLocationConstraint partitionLocationConstraint,
+            long initializationTimestamp,
+            VertexAttemptNumberStore vertexAttemptNumberStore,
+            Logger log)
+            throws Exception {
+        ExecutionDeploymentListener executionDeploymentListener =
+                new ExecutionDeploymentTrackerDeploymentListenerAdapter(executionDeploymentTracker);
+        ExecutionStateUpdateListener executionStateUpdateListener =
+                (execution, newState) -> {
+                    if (newState.isTerminal()) {
+                        executionDeploymentTracker.stopTrackingDeploymentOf(execution);
+                    }
+                };
+
+        final ExecutionGraph newExecutionGraph =
+                DefaultExecutionGraphBuilder.buildGraph(
+                        jobGraph,
+                        configuration,
+                        futureExecutor,
+                        ioExecutor,
+                        userCodeClassLoader,
+                        completedCheckpointStore,
+                        checkpointsCleaner,
+                        checkpointIdCounter,
+                        rpcTimeout,
+                        jobManagerJobMetricGroup,
+                        blobWriter,
+                        log,
+                        shuffleMaster,
+                        jobMasterPartitionTracker,
+                        partitionLocationConstraint,
+                        executionDeploymentListener,
+                        executionStateUpdateListener,
+                        initializationTimestamp,
+                        vertexAttemptNumberStore);
+
+        final CheckpointCoordinator checkpointCoordinator =
+                newExecutionGraph.getCheckpointCoordinator();
+
+        if (checkpointCoordinator != null) {
+            // check whether we find a valid checkpoint
+            if (!checkpointCoordinator.restoreInitialCheckpointIfPresent(
+                    new HashSet<>(newExecutionGraph.getAllVertices().values()))) {
+
+                // check whether we can restore from a savepoint
+                tryRestoreExecutionGraphFromSavepoint(
+                        newExecutionGraph, jobGraph.getSavepointRestoreSettings());
+            }
+        }
+
+        return newExecutionGraph;
+    }
+
+    /**
+     * Tries to restore the given {@link ExecutionGraph} from the provided {@link
+     * SavepointRestoreSettings}, iff checkpointing is enabled.
+     *
+     * @param executionGraphToRestore {@link ExecutionGraph} which is supposed to be restored
+     * @param savepointRestoreSettings {@link SavepointRestoreSettings} containing information about
+     *     the savepoint to restore from
+     * @throws Exception if the {@link ExecutionGraph} could not be restored
+     */
+    private void tryRestoreExecutionGraphFromSavepoint(
+            ExecutionGraph executionGraphToRestore,
+            SavepointRestoreSettings savepointRestoreSettings)
+            throws Exception {
+        if (savepointRestoreSettings.restoreSavepoint()) {
+            final CheckpointCoordinator checkpointCoordinator =
+                    executionGraphToRestore.getCheckpointCoordinator();
+            if (checkpointCoordinator != null) {
+                checkpointCoordinator.restoreSavepoint(
+                        savepointRestoreSettings.getRestorePath(),
+                        savepointRestoreSettings.allowNonRestoredState(),
+                        executionGraphToRestore.getAllVertices(),
+                        userCodeClassLoader);
+            }
+        }
+    }
+}
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultScheduler.java
index 394d1cf..be29192 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultScheduler.java
@@ -20,9 +20,7 @@
 package org.apache.flink.runtime.scheduler;
 
 import org.apache.flink.api.common.JobStatus;
-import org.apache.flink.api.common.time.Time;
 import org.apache.flink.configuration.Configuration;
-import org.apache.flink.runtime.blob.BlobWriter;
 import org.apache.flink.runtime.checkpoint.CheckpointRecoveryFactory;
 import org.apache.flink.runtime.clusterframework.types.AllocationID;
 import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
@@ -38,13 +36,11 @@ import org.apache.flink.runtime.executiongraph.failover.flip1.ExecutionFailureHa
 import org.apache.flink.runtime.executiongraph.failover.flip1.FailoverStrategy;
 import org.apache.flink.runtime.executiongraph.failover.flip1.FailureHandlingResult;
 import org.apache.flink.runtime.executiongraph.failover.flip1.RestartBackoffTimeStrategy;
-import org.apache.flink.runtime.io.network.partition.JobMasterPartitionTracker;
 import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID;
 import org.apache.flink.runtime.jobgraph.JobGraph;
 import org.apache.flink.runtime.jobmanager.scheduler.CoLocationGroup;
 import org.apache.flink.runtime.jobmanager.scheduler.NoResourceAvailableException;
 import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup;
-import org.apache.flink.runtime.jobmaster.ExecutionDeploymentTracker;
 import org.apache.flink.runtime.jobmaster.LogicalSlot;
 import org.apache.flink.runtime.metrics.groups.JobManagerJobMetricGroup;
 import org.apache.flink.runtime.operators.coordination.OperatorCoordinator;
@@ -52,7 +48,6 @@ import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
 import org.apache.flink.runtime.scheduler.strategy.SchedulingStrategy;
 import org.apache.flink.runtime.scheduler.strategy.SchedulingStrategyFactory;
 import org.apache.flink.runtime.scheduler.strategy.SchedulingTopology;
-import org.apache.flink.runtime.shuffle.ShuffleMaster;
 import org.apache.flink.runtime.taskmanager.TaskManagerLocation;
 import org.apache.flink.util.ExceptionUtils;
 
@@ -70,7 +65,6 @@ import java.util.Set;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.CompletionException;
 import java.util.concurrent.Executor;
-import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.function.BiFunction;
@@ -106,25 +100,20 @@ public class DefaultScheduler extends SchedulerBase implements SchedulerOperatio
             final Executor ioExecutor,
             final Configuration jobMasterConfiguration,
             final Consumer<ComponentMainThreadExecutor> startUpAction,
-            final ScheduledExecutorService futureExecutor,
             final ScheduledExecutor delayExecutor,
             final ClassLoader userCodeLoader,
             final CheckpointRecoveryFactory checkpointRecoveryFactory,
-            final Time rpcTimeout,
-            final BlobWriter blobWriter,
             final JobManagerJobMetricGroup jobManagerJobMetricGroup,
-            final ShuffleMaster<?> shuffleMaster,
-            final JobMasterPartitionTracker partitionTracker,
             final SchedulingStrategyFactory schedulingStrategyFactory,
             final FailoverStrategy.Factory failoverStrategyFactory,
             final RestartBackoffTimeStrategy restartBackoffTimeStrategy,
             final ExecutionVertexOperations executionVertexOperations,
             final ExecutionVertexVersioner executionVertexVersioner,
             final ExecutionSlotAllocatorFactory executionSlotAllocatorFactory,
-            final ExecutionDeploymentTracker executionDeploymentTracker,
             long initializationTimestamp,
             final ComponentMainThreadExecutor mainThreadExecutor,
-            final JobStatusListener jobStatusListener)
+            final JobStatusListener jobStatusListener,
+            final ExecutionGraphFactory executionGraphFactory)
             throws Exception {
 
         super(
@@ -132,19 +121,14 @@ public class DefaultScheduler extends SchedulerBase implements SchedulerOperatio
                 jobGraph,
                 ioExecutor,
                 jobMasterConfiguration,
-                futureExecutor,
                 userCodeLoader,
                 checkpointRecoveryFactory,
-                rpcTimeout,
-                blobWriter,
                 jobManagerJobMetricGroup,
-                shuffleMaster,
-                partitionTracker,
                 executionVertexVersioner,
-                executionDeploymentTracker,
                 initializationTimestamp,
                 mainThreadExecutor,
-                jobStatusListener);
+                jobStatusListener,
+                executionGraphFactory);
 
         this.log = log;
 
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultSchedulerFactory.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultSchedulerFactory.java
index 217008f..cf00887 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultSchedulerFactory.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultSchedulerFactory.java
@@ -101,31 +101,39 @@ public class DefaultSchedulerFactory implements SchedulerNGFactory {
                 jobGraph.getName(),
                 jobGraph.getJobID());
 
+        final ExecutionGraphFactory executionGraphFactory =
+                new DefaultExecutionGraphFactory(
+                        jobMasterConfiguration,
+                        userCodeLoader,
+                        executionDeploymentTracker,
+                        futureExecutor,
+                        ioExecutor,
+                        rpcTimeout,
+                        jobManagerJobMetricGroup,
+                        blobWriter,
+                        shuffleMaster,
+                        partitionTracker);
+
         return new DefaultScheduler(
                 log,
                 jobGraph,
                 ioExecutor,
                 jobMasterConfiguration,
                 schedulerComponents.getStartUpAction(),
-                futureExecutor,
                 new ScheduledExecutorServiceAdapter(futureExecutor),
                 userCodeLoader,
                 checkpointRecoveryFactory,
-                rpcTimeout,
-                blobWriter,
                 jobManagerJobMetricGroup,
-                shuffleMaster,
-                partitionTracker,
                 schedulerComponents.getSchedulingStrategyFactory(),
                 FailoverStrategyFactoryLoader.loadFailoverStrategyFactory(jobMasterConfiguration),
                 restartBackoffTimeStrategy,
                 new DefaultExecutionVertexOperations(),
                 new ExecutionVertexVersioner(),
                 schedulerComponents.getAllocatorFactory(),
-                executionDeploymentTracker,
                 initializationTimestamp,
                 mainThreadExecutor,
-                jobStatusListener);
+                jobStatusListener,
+                executionGraphFactory);
     }
 
     @Override
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/ExecutionGraphFactory.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/ExecutionGraphFactory.java
new file mode 100644
index 0000000..f7fed50
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/ExecutionGraphFactory.java
@@ -0,0 +1,59 @@
+/*
+ * 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.flink.runtime.scheduler;
+
+import org.apache.flink.runtime.checkpoint.CheckpointIDCounter;
+import org.apache.flink.runtime.checkpoint.CheckpointsCleaner;
+import org.apache.flink.runtime.checkpoint.CompletedCheckpointStore;
+import org.apache.flink.runtime.deployment.TaskDeploymentDescriptorFactory;
+import org.apache.flink.runtime.executiongraph.ExecutionGraph;
+import org.apache.flink.runtime.executiongraph.VertexAttemptNumberStore;
+import org.apache.flink.runtime.jobgraph.JobGraph;
+
+import org.slf4j.Logger;
+
+/** Factory for creating an {@link ExecutionGraph}. */
+public interface ExecutionGraphFactory {
+
+    /**
+     * Create and restore {@link ExecutionGraph} from the given {@link JobGraph} and services.
+     *
+     * @param jobGraph jobGraph to initialize the ExecutionGraph with
+     * @param completedCheckpointStore completedCheckpointStore to pass to the CheckpointCoordinator
+     * @param checkpointsCleaner checkpointsCleaner to pass to the CheckpointCoordinator
+     * @param checkpointIdCounter checkpointIdCounter to pass to the CheckpointCoordinator
+     * @param partitionLocationConstraint partitionLocationConstraint for this job
+     * @param initializationTimestamp initializationTimestamp when the ExecutionGraph was created
+     * @param vertexAttemptNumberStore vertexAttemptNumberStore keeping information about the vertex
+     *     attempts of previous runs
+     * @param log log to use for logging
+     * @return restored {@link ExecutionGraph}
+     * @throws Exception if the {@link ExecutionGraph} could not be created and restored
+     */
+    ExecutionGraph createAndRestoreExecutionGraph(
+            JobGraph jobGraph,
+            CompletedCheckpointStore completedCheckpointStore,
+            CheckpointsCleaner checkpointsCleaner,
+            CheckpointIDCounter checkpointIdCounter,
+            TaskDeploymentDescriptorFactory.PartitionLocationConstraint partitionLocationConstraint,
+            long initializationTimestamp,
+            VertexAttemptNumberStore vertexAttemptNumberStore,
+            Logger log)
+            throws Exception;
+}
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java
index 87a1354..3ddb55f 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java
@@ -22,13 +22,10 @@ package org.apache.flink.runtime.scheduler;
 import org.apache.flink.annotation.VisibleForTesting;
 import org.apache.flink.api.common.JobID;
 import org.apache.flink.api.common.JobStatus;
-import org.apache.flink.api.common.time.Time;
 import org.apache.flink.configuration.CheckpointingOptions;
 import org.apache.flink.configuration.Configuration;
 import org.apache.flink.queryablestate.KvStateID;
-import org.apache.flink.runtime.JobException;
 import org.apache.flink.runtime.accumulators.AccumulatorSnapshot;
-import org.apache.flink.runtime.blob.BlobWriter;
 import org.apache.flink.runtime.checkpoint.CheckpointCoordinator;
 import org.apache.flink.runtime.checkpoint.CheckpointException;
 import org.apache.flink.runtime.checkpoint.CheckpointFailureReason;
@@ -40,37 +37,29 @@ import org.apache.flink.runtime.checkpoint.CheckpointsCleaner;
 import org.apache.flink.runtime.checkpoint.CompletedCheckpoint;
 import org.apache.flink.runtime.checkpoint.CompletedCheckpointStore;
 import org.apache.flink.runtime.checkpoint.TaskStateSnapshot;
-import org.apache.flink.runtime.client.JobExecutionException;
 import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutor;
 import org.apache.flink.runtime.concurrent.FutureUtils;
 import org.apache.flink.runtime.deployment.TaskDeploymentDescriptorFactory;
 import org.apache.flink.runtime.execution.ExecutionState;
 import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
-import org.apache.flink.runtime.executiongraph.DefaultExecutionGraphBuilder;
 import org.apache.flink.runtime.executiongraph.DefaultVertexAttemptNumberStore;
 import org.apache.flink.runtime.executiongraph.ErrorInfo;
 import org.apache.flink.runtime.executiongraph.Execution;
 import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
-import org.apache.flink.runtime.executiongraph.ExecutionDeploymentListener;
 import org.apache.flink.runtime.executiongraph.ExecutionGraph;
 import org.apache.flink.runtime.executiongraph.ExecutionJobVertex;
-import org.apache.flink.runtime.executiongraph.ExecutionStateUpdateListener;
 import org.apache.flink.runtime.executiongraph.ExecutionVertex;
 import org.apache.flink.runtime.executiongraph.JobStatusListener;
 import org.apache.flink.runtime.executiongraph.TaskExecutionStateTransition;
 import org.apache.flink.runtime.executiongraph.failover.flip1.FailureHandlingResult;
 import org.apache.flink.runtime.executiongraph.failover.flip1.ResultPartitionAvailabilityChecker;
-import org.apache.flink.runtime.io.network.partition.JobMasterPartitionTracker;
 import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
 import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
 import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID;
 import org.apache.flink.runtime.jobgraph.JobGraph;
 import org.apache.flink.runtime.jobgraph.JobVertexID;
 import org.apache.flink.runtime.jobgraph.OperatorID;
-import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
 import org.apache.flink.runtime.jobmanager.PartitionProducerDisposedException;
-import org.apache.flink.runtime.jobmaster.ExecutionDeploymentTracker;
-import org.apache.flink.runtime.jobmaster.ExecutionDeploymentTrackerDeploymentListenerAdapter;
 import org.apache.flink.runtime.jobmaster.SerializedInputSplit;
 import org.apache.flink.runtime.messages.FlinkJobNotFoundException;
 import org.apache.flink.runtime.messages.checkpoint.DeclineCheckpoint;
@@ -89,7 +78,6 @@ import org.apache.flink.runtime.scheduler.stopwithsavepoint.StopWithSavepointTer
 import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
 import org.apache.flink.runtime.scheduler.strategy.SchedulingExecutionVertex;
 import org.apache.flink.runtime.scheduler.strategy.SchedulingTopology;
-import org.apache.flink.runtime.shuffle.ShuffleMaster;
 import org.apache.flink.runtime.state.KeyGroupRange;
 import org.apache.flink.runtime.util.IntArrayList;
 import org.apache.flink.util.ExceptionUtils;
@@ -115,7 +103,6 @@ import java.util.Set;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.CompletionException;
 import java.util.concurrent.Executor;
-import java.util.concurrent.ScheduledExecutorService;
 import java.util.stream.Collectors;
 import java.util.stream.StreamSupport;
 
@@ -137,24 +124,12 @@ public abstract class SchedulerBase implements SchedulerNG, CheckpointScheduling
 
     protected final InputsLocationsRetriever inputsLocationsRetriever;
 
-    private final Executor ioExecutor;
-
-    private final Configuration jobMasterConfiguration;
-
-    private final ScheduledExecutorService futureExecutor;
-
-    private final ClassLoader userCodeLoader;
-
     private final CompletedCheckpointStore completedCheckpointStore;
 
     private final CheckpointsCleaner checkpointsCleaner;
 
     private final CheckpointIDCounter checkpointIdCounter;
 
-    private final Time rpcTimeout;
-
-    private final BlobWriter blobWriter;
-
     private final JobManagerJobMetricGroup jobManagerJobMetricGroup;
 
     protected final ExecutionVertexVersioner executionVertexVersioner;
@@ -169,35 +144,27 @@ public abstract class SchedulerBase implements SchedulerNG, CheckpointScheduling
 
     private final List<ErrorInfo> taskFailureHistory = new ArrayList<>();
 
+    private final ExecutionGraphFactory executionGraphFactory;
+
     public SchedulerBase(
             final Logger log,
             final JobGraph jobGraph,
             final Executor ioExecutor,
             final Configuration jobMasterConfiguration,
-            final ScheduledExecutorService futureExecutor,
             final ClassLoader userCodeLoader,
             final CheckpointRecoveryFactory checkpointRecoveryFactory,
-            final Time rpcTimeout,
-            final BlobWriter blobWriter,
             final JobManagerJobMetricGroup jobManagerJobMetricGroup,
-            final ShuffleMaster<?> shuffleMaster,
-            final JobMasterPartitionTracker partitionTracker,
             final ExecutionVertexVersioner executionVertexVersioner,
-            final ExecutionDeploymentTracker executionDeploymentTracker,
             long initializationTimestamp,
             final ComponentMainThreadExecutor mainThreadExecutor,
-            final JobStatusListener jobStatusListener)
+            final JobStatusListener jobStatusListener,
+            final ExecutionGraphFactory executionGraphFactory)
             throws Exception {
 
         this.log = checkNotNull(log);
         this.jobGraph = checkNotNull(jobGraph);
-        this.ioExecutor = checkNotNull(ioExecutor);
-        this.jobMasterConfiguration = checkNotNull(jobMasterConfiguration);
-        this.futureExecutor = checkNotNull(futureExecutor);
-        this.userCodeLoader = checkNotNull(userCodeLoader);
-        this.rpcTimeout = checkNotNull(rpcTimeout);
+        this.executionGraphFactory = executionGraphFactory;
 
-        this.blobWriter = checkNotNull(blobWriter);
         this.jobManagerJobMetricGroup = checkNotNull(jobManagerJobMetricGroup);
         this.executionVertexVersioner = checkNotNull(executionVertexVersioner);
         this.mainThreadExecutor = mainThreadExecutor;
@@ -216,13 +183,9 @@ public abstract class SchedulerBase implements SchedulerNG, CheckpointScheduling
 
         this.executionGraph =
                 createAndRestoreExecutionGraph(
-                        jobManagerJobMetricGroup,
                         completedCheckpointStore,
                         checkpointsCleaner,
                         checkpointIdCounter,
-                        checkNotNull(shuffleMaster),
-                        checkNotNull(partitionTracker),
-                        checkNotNull(executionDeploymentTracker),
                         initializationTimestamp,
                         mainThreadExecutor,
                         jobStatusListener);
@@ -273,42 +236,25 @@ public abstract class SchedulerBase implements SchedulerNG, CheckpointScheduling
     }
 
     private ExecutionGraph createAndRestoreExecutionGraph(
-            JobManagerJobMetricGroup currentJobManagerJobMetricGroup,
             CompletedCheckpointStore completedCheckpointStore,
             CheckpointsCleaner checkpointsCleaner,
             CheckpointIDCounter checkpointIdCounter,
-            ShuffleMaster<?> shuffleMaster,
-            JobMasterPartitionTracker partitionTracker,
-            ExecutionDeploymentTracker executionDeploymentTracker,
             long initializationTimestamp,
             ComponentMainThreadExecutor mainThreadExecutor,
             JobStatusListener jobStatusListener)
             throws Exception {
 
-        ExecutionGraph newExecutionGraph =
-                createExecutionGraph(
-                        currentJobManagerJobMetricGroup,
+        final ExecutionGraph newExecutionGraph =
+                executionGraphFactory.createAndRestoreExecutionGraph(
+                        jobGraph,
                         completedCheckpointStore,
                         checkpointsCleaner,
                         checkpointIdCounter,
-                        shuffleMaster,
-                        partitionTracker,
-                        executionDeploymentTracker,
-                        initializationTimestamp);
-
-        final CheckpointCoordinator checkpointCoordinator =
-                newExecutionGraph.getCheckpointCoordinator();
-
-        if (checkpointCoordinator != null) {
-            // check whether we find a valid checkpoint
-            if (!checkpointCoordinator.restoreInitialCheckpointIfPresent(
-                    new HashSet<>(newExecutionGraph.getAllVertices().values()))) {
-
-                // check whether we can restore from a savepoint
-                tryRestoreExecutionGraphFromSavepoint(
-                        newExecutionGraph, jobGraph.getSavepointRestoreSettings());
-            }
-        }
+                        TaskDeploymentDescriptorFactory.PartitionLocationConstraint.fromJobType(
+                                jobGraph.getJobType()),
+                        initializationTimestamp,
+                        new DefaultVertexAttemptNumberStore(),
+                        log);
 
         newExecutionGraph.setInternalTaskFailuresListener(
                 new UpdateSchedulerNgOnInternalFailuresListener(this));
@@ -318,75 +264,6 @@ public abstract class SchedulerBase implements SchedulerNG, CheckpointScheduling
         return newExecutionGraph;
     }
 
-    private ExecutionGraph createExecutionGraph(
-            JobManagerJobMetricGroup currentJobManagerJobMetricGroup,
-            CompletedCheckpointStore completedCheckpointStore,
-            CheckpointsCleaner checkpointsCleaner,
-            CheckpointIDCounter checkpointIdCounter,
-            ShuffleMaster<?> shuffleMaster,
-            final JobMasterPartitionTracker partitionTracker,
-            ExecutionDeploymentTracker executionDeploymentTracker,
-            long initializationTimestamp)
-            throws JobExecutionException, JobException {
-
-        ExecutionDeploymentListener executionDeploymentListener =
-                new ExecutionDeploymentTrackerDeploymentListenerAdapter(executionDeploymentTracker);
-        ExecutionStateUpdateListener executionStateUpdateListener =
-                (execution, newState) -> {
-                    if (newState.isTerminal()) {
-                        executionDeploymentTracker.stopTrackingDeploymentOf(execution);
-                    }
-                };
-
-        return DefaultExecutionGraphBuilder.buildGraph(
-                jobGraph,
-                jobMasterConfiguration,
-                futureExecutor,
-                ioExecutor,
-                userCodeLoader,
-                completedCheckpointStore,
-                checkpointsCleaner,
-                checkpointIdCounter,
-                rpcTimeout,
-                currentJobManagerJobMetricGroup,
-                blobWriter,
-                log,
-                shuffleMaster,
-                partitionTracker,
-                TaskDeploymentDescriptorFactory.PartitionLocationConstraint.fromJobType(
-                        jobGraph.getJobType()),
-                executionDeploymentListener,
-                executionStateUpdateListener,
-                initializationTimestamp,
-                new DefaultVertexAttemptNumberStore());
-    }
-
-    /**
-     * Tries to restore the given {@link ExecutionGraph} from the provided {@link
-     * SavepointRestoreSettings}.
-     *
-     * @param executionGraphToRestore {@link ExecutionGraph} which is supposed to be restored
-     * @param savepointRestoreSettings {@link SavepointRestoreSettings} containing information about
-     *     the savepoint to restore from
-     * @throws Exception if the {@link ExecutionGraph} could not be restored
-     */
-    private void tryRestoreExecutionGraphFromSavepoint(
-            ExecutionGraph executionGraphToRestore,
-            SavepointRestoreSettings savepointRestoreSettings)
-            throws Exception {
-        if (savepointRestoreSettings.restoreSavepoint()) {
-            final CheckpointCoordinator checkpointCoordinator =
-                    executionGraphToRestore.getCheckpointCoordinator();
-            if (checkpointCoordinator != null) {
-                checkpointCoordinator.restoreSavepoint(
-                        savepointRestoreSettings.getRestorePath(),
-                        savepointRestoreSettings.allowNonRestoredState(),
-                        executionGraphToRestore.getAllVertices(),
-                        userCodeLoader);
-            }
-        }
-    }
-
     protected void resetForNewExecutions(final Collection<ExecutionVertexID> vertices) {
         vertices.stream()
                 .map(this::getExecutionVertex)
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
index badad27..a7783db 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
@@ -21,15 +21,12 @@ package org.apache.flink.runtime.scheduler.adaptive;
 import org.apache.flink.annotation.VisibleForTesting;
 import org.apache.flink.api.common.JobID;
 import org.apache.flink.api.common.JobStatus;
-import org.apache.flink.api.common.time.Time;
 import org.apache.flink.configuration.Configuration;
 import org.apache.flink.configuration.JobManagerOptions;
 import org.apache.flink.metrics.Gauge;
 import org.apache.flink.queryablestate.KvStateID;
 import org.apache.flink.runtime.JobException;
 import org.apache.flink.runtime.accumulators.AccumulatorSnapshot;
-import org.apache.flink.runtime.blob.BlobWriter;
-import org.apache.flink.runtime.checkpoint.CheckpointCoordinator;
 import org.apache.flink.runtime.checkpoint.CheckpointException;
 import org.apache.flink.runtime.checkpoint.CheckpointFailureReason;
 import org.apache.flink.runtime.checkpoint.CheckpointIDCounter;
@@ -45,20 +42,16 @@ import org.apache.flink.runtime.concurrent.FutureUtils;
 import org.apache.flink.runtime.deployment.TaskDeploymentDescriptorFactory;
 import org.apache.flink.runtime.execution.ExecutionState;
 import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
-import org.apache.flink.runtime.executiongraph.DefaultExecutionGraphBuilder;
 import org.apache.flink.runtime.executiongraph.DefaultVertexAttemptNumberStore;
 import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
-import org.apache.flink.runtime.executiongraph.ExecutionDeploymentListener;
 import org.apache.flink.runtime.executiongraph.ExecutionGraph;
 import org.apache.flink.runtime.executiongraph.ExecutionJobVertex;
-import org.apache.flink.runtime.executiongraph.ExecutionStateUpdateListener;
 import org.apache.flink.runtime.executiongraph.ExecutionVertex;
 import org.apache.flink.runtime.executiongraph.JobStatusListener;
 import org.apache.flink.runtime.executiongraph.MutableVertexAttemptNumberStore;
 import org.apache.flink.runtime.executiongraph.TaskExecutionStateTransition;
 import org.apache.flink.runtime.executiongraph.failover.flip1.ExecutionFailureHandler;
 import org.apache.flink.runtime.executiongraph.failover.flip1.RestartBackoffTimeStrategy;
-import org.apache.flink.runtime.io.network.partition.JobMasterPartitionTracker;
 import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
 import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
 import org.apache.flink.runtime.jobgraph.JobEdge;
@@ -67,10 +60,7 @@ import org.apache.flink.runtime.jobgraph.JobType;
 import org.apache.flink.runtime.jobgraph.JobVertex;
 import org.apache.flink.runtime.jobgraph.JobVertexID;
 import org.apache.flink.runtime.jobgraph.OperatorID;
-import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
 import org.apache.flink.runtime.jobmanager.PartitionProducerDisposedException;
-import org.apache.flink.runtime.jobmaster.ExecutionDeploymentTracker;
-import org.apache.flink.runtime.jobmaster.ExecutionDeploymentTrackerDeploymentListenerAdapter;
 import org.apache.flink.runtime.jobmaster.LogicalSlot;
 import org.apache.flink.runtime.jobmaster.SerializedInputSplit;
 import org.apache.flink.runtime.jobmaster.SlotInfo;
@@ -88,6 +78,7 @@ import org.apache.flink.runtime.operators.coordination.TaskNotRunningException;
 import org.apache.flink.runtime.query.KvStateLocation;
 import org.apache.flink.runtime.query.UnknownKvStateLocation;
 import org.apache.flink.runtime.rpc.FatalErrorHandler;
+import org.apache.flink.runtime.scheduler.ExecutionGraphFactory;
 import org.apache.flink.runtime.scheduler.ExecutionGraphHandler;
 import org.apache.flink.runtime.scheduler.ExecutionGraphInfo;
 import org.apache.flink.runtime.scheduler.OperatorCoordinatorHandler;
@@ -99,7 +90,6 @@ import org.apache.flink.runtime.scheduler.adaptive.allocator.SlotAllocator;
 import org.apache.flink.runtime.scheduler.adaptive.allocator.VertexParallelism;
 import org.apache.flink.runtime.scheduler.adaptive.scalingpolicy.ReactiveScaleUpController;
 import org.apache.flink.runtime.scheduler.adaptive.scalingpolicy.ScaleUpController;
-import org.apache.flink.runtime.shuffle.ShuffleMaster;
 import org.apache.flink.runtime.state.KeyGroupRange;
 import org.apache.flink.runtime.util.ResourceCounter;
 import org.apache.flink.util.ExceptionUtils;
@@ -118,13 +108,11 @@ import java.io.IOException;
 import java.net.InetSocketAddress;
 import java.time.Duration;
 import java.util.Collection;
-import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Optional;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.CompletionException;
 import java.util.concurrent.Executor;
-import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 
@@ -164,15 +152,8 @@ public class AdaptiveScheduler
 
     private final long initializationTimestamp;
 
-    private final Configuration configuration;
-    private final ScheduledExecutorService futureExecutor;
     private final Executor ioExecutor;
     private final ClassLoader userCodeClassLoader;
-    private final Time rpcTimeout;
-    private final BlobWriter blobWriter;
-    private final ShuffleMaster<?> shuffleMaster;
-    private final JobMasterPartitionTracker partitionTracker;
-    private final ExecutionDeploymentTracker executionDeploymentTracker;
     private final JobManagerJobMetricGroup jobManagerJobMetricGroup;
 
     private final CompletedCheckpointStore completedCheckpointStore;
@@ -194,6 +175,8 @@ public class AdaptiveScheduler
 
     private final Duration resourceTimeout;
 
+    private final ExecutionGraphFactory executionGraphFactory;
+
     private State state = new Created(this, LOG);
 
     private boolean isTransitioningState = false;
@@ -208,21 +191,16 @@ public class AdaptiveScheduler
             Configuration configuration,
             DeclarativeSlotPool declarativeSlotPool,
             SlotAllocator slotAllocator,
-            ScheduledExecutorService futureExecutor,
             Executor ioExecutor,
             ClassLoader userCodeClassLoader,
             CheckpointRecoveryFactory checkpointRecoveryFactory,
-            Time rpcTimeout,
-            BlobWriter blobWriter,
             JobManagerJobMetricGroup jobManagerJobMetricGroup,
-            ShuffleMaster<?> shuffleMaster,
-            JobMasterPartitionTracker partitionTracker,
             RestartBackoffTimeStrategy restartBackoffTimeStrategy,
-            ExecutionDeploymentTracker executionDeploymentTracker,
             long initializationTimestamp,
             ComponentMainThreadExecutor mainThreadExecutor,
             FatalErrorHandler fatalErrorHandler,
-            JobStatusListener jobStatusListener)
+            JobStatusListener jobStatusListener,
+            ExecutionGraphFactory executionGraphFactory)
             throws JobExecutionException {
 
         ensureFullyPipelinedStreamingJob(jobGraph);
@@ -230,16 +208,9 @@ public class AdaptiveScheduler
         this.jobInformation = new JobGraphJobInformation(jobGraph);
         this.declarativeSlotPool = declarativeSlotPool;
         this.initializationTimestamp = initializationTimestamp;
-        this.configuration = configuration;
-        this.futureExecutor = futureExecutor;
         this.ioExecutor = ioExecutor;
         this.userCodeClassLoader = userCodeClassLoader;
-        this.rpcTimeout = rpcTimeout;
-        this.blobWriter = blobWriter;
-        this.shuffleMaster = shuffleMaster;
-        this.partitionTracker = partitionTracker;
         this.restartBackoffTimeStrategy = restartBackoffTimeStrategy;
-        this.executionDeploymentTracker = executionDeploymentTracker;
         this.jobManagerJobMetricGroup = jobManagerJobMetricGroup;
         this.fatalErrorHandler = fatalErrorHandler;
         this.completedCheckpointStore =
@@ -265,6 +236,8 @@ public class AdaptiveScheduler
 
         this.resourceTimeout = configuration.get(JobManagerOptions.RESOURCE_WAIT_TIMEOUT);
 
+        this.executionGraphFactory = executionGraphFactory;
+
         registerMetrics();
     }
 
@@ -794,79 +767,15 @@ public class AdaptiveScheduler
     @Nonnull
     private ExecutionGraph createExecutionGraphAndRestoreState(JobGraph adjustedJobGraph)
             throws Exception {
-        ExecutionDeploymentListener executionDeploymentListener =
-                new ExecutionDeploymentTrackerDeploymentListenerAdapter(executionDeploymentTracker);
-        ExecutionStateUpdateListener executionStateUpdateListener =
-                (execution, newState) -> {
-                    if (newState.isTerminal()) {
-                        executionDeploymentTracker.stopTrackingDeploymentOf(execution);
-                    }
-                };
-
-        final ExecutionGraph newExecutionGraph =
-                DefaultExecutionGraphBuilder.buildGraph(
-                        adjustedJobGraph,
-                        configuration,
-                        futureExecutor,
-                        ioExecutor,
-                        userCodeClassLoader,
-                        completedCheckpointStore,
-                        checkpointsCleaner,
-                        checkpointIdCounter,
-                        rpcTimeout,
-                        jobManagerJobMetricGroup,
-                        blobWriter,
-                        LOG,
-                        shuffleMaster,
-                        partitionTracker,
-                        TaskDeploymentDescriptorFactory.PartitionLocationConstraint
-                                .MUST_BE_KNOWN, // AdaptiveScheduler only supports streaming jobs
-                        executionDeploymentListener,
-                        executionStateUpdateListener,
-                        initializationTimestamp,
-                        vertexAttemptNumberStore);
-
-        final CheckpointCoordinator checkpointCoordinator =
-                newExecutionGraph.getCheckpointCoordinator();
-
-        if (checkpointCoordinator != null) {
-            // check whether we find a valid checkpoint
-            if (!checkpointCoordinator.restoreInitialCheckpointIfPresent(
-                    new HashSet<>(newExecutionGraph.getAllVertices().values()))) {
-
-                // check whether we can restore from a savepoint
-                tryRestoreExecutionGraphFromSavepoint(
-                        newExecutionGraph, adjustedJobGraph.getSavepointRestoreSettings());
-            }
-        }
-
-        return newExecutionGraph;
-    }
-
-    /**
-     * Tries to restore the given {@link ExecutionGraph} from the provided {@link
-     * SavepointRestoreSettings}, iff checkpointing is enabled.
-     *
-     * @param executionGraphToRestore {@link ExecutionGraph} which is supposed to be restored
-     * @param savepointRestoreSettings {@link SavepointRestoreSettings} containing information about
-     *     the savepoint to restore from
-     * @throws Exception if the {@link ExecutionGraph} could not be restored
-     */
-    private void tryRestoreExecutionGraphFromSavepoint(
-            ExecutionGraph executionGraphToRestore,
-            SavepointRestoreSettings savepointRestoreSettings)
-            throws Exception {
-        if (savepointRestoreSettings.restoreSavepoint()) {
-            final CheckpointCoordinator checkpointCoordinator =
-                    executionGraphToRestore.getCheckpointCoordinator();
-            if (checkpointCoordinator != null) {
-                checkpointCoordinator.restoreSavepoint(
-                        savepointRestoreSettings.getRestorePath(),
-                        savepointRestoreSettings.allowNonRestoredState(),
-                        executionGraphToRestore.getAllVertices(),
-                        userCodeClassLoader);
-            }
-        }
+        return executionGraphFactory.createAndRestoreExecutionGraph(
+                adjustedJobGraph,
+                completedCheckpointStore,
+                checkpointsCleaner,
+                checkpointIdCounter,
+                TaskDeploymentDescriptorFactory.PartitionLocationConstraint.MUST_BE_KNOWN,
+                initializationTimestamp,
+                vertexAttemptNumberStore,
+                LOG);
     }
 
     @Override
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerFactory.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerFactory.java
index 278baa0..4c790cc 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerFactory.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerFactory.java
@@ -34,6 +34,8 @@ import org.apache.flink.runtime.jobmaster.slotpool.DeclarativeSlotPool;
 import org.apache.flink.runtime.jobmaster.slotpool.SlotPoolService;
 import org.apache.flink.runtime.metrics.groups.JobManagerJobMetricGroup;
 import org.apache.flink.runtime.rpc.FatalErrorHandler;
+import org.apache.flink.runtime.scheduler.DefaultExecutionGraphFactory;
+import org.apache.flink.runtime.scheduler.ExecutionGraphFactory;
 import org.apache.flink.runtime.scheduler.SchedulerNG;
 import org.apache.flink.runtime.scheduler.SchedulerNGFactory;
 import org.apache.flink.runtime.scheduler.adaptive.allocator.SlotSharingSlotAllocator;
@@ -92,26 +94,34 @@ public class AdaptiveSchedulerFactory implements SchedulerNGFactory {
         final SlotSharingSlotAllocator slotAllocator =
                 createSlotSharingSlotAllocator(declarativeSlotPool);
 
+        final ExecutionGraphFactory executionGraphFactory =
+                new DefaultExecutionGraphFactory(
+                        jobMasterConfiguration,
+                        userCodeLoader,
+                        executionDeploymentTracker,
+                        futureExecutor,
+                        ioExecutor,
+                        rpcTimeout,
+                        jobManagerJobMetricGroup,
+                        blobWriter,
+                        shuffleMaster,
+                        partitionTracker);
+
         return new AdaptiveScheduler(
                 jobGraph,
                 jobMasterConfiguration,
                 declarativeSlotPool,
                 slotAllocator,
-                futureExecutor,
                 ioExecutor,
                 userCodeLoader,
                 checkpointRecoveryFactory,
-                rpcTimeout,
-                blobWriter,
                 jobManagerJobMetricGroup,
-                shuffleMaster,
-                partitionTracker,
                 restartBackoffTimeStrategy,
-                executionDeploymentTracker,
                 initializationTimestamp,
                 mainThreadExecutor,
                 fatalErrorHandler,
-                jobStatusListener);
+                jobStatusListener,
+                executionGraphFactory);
     }
 
     @Override
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultExecutionGraphFactoryTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultExecutionGraphFactoryTest.java
new file mode 100644
index 0000000..2a57d04
--- /dev/null
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultExecutionGraphFactoryTest.java
@@ -0,0 +1,156 @@
+/*
+ * 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.flink.runtime.scheduler;
+
+import org.apache.flink.api.common.time.Time;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.testutils.FlinkMatchers;
+import org.apache.flink.runtime.blob.VoidBlobWriter;
+import org.apache.flink.runtime.checkpoint.CheckpointsCleaner;
+import org.apache.flink.runtime.checkpoint.CompletedCheckpoint;
+import org.apache.flink.runtime.checkpoint.StandaloneCheckpointIDCounter;
+import org.apache.flink.runtime.checkpoint.StandaloneCompletedCheckpointStore;
+import org.apache.flink.runtime.deployment.TaskDeploymentDescriptorFactory;
+import org.apache.flink.runtime.executiongraph.DefaultVertexAttemptNumberStore;
+import org.apache.flink.runtime.io.network.partition.NoOpJobMasterPartitionTracker;
+import org.apache.flink.runtime.jobgraph.JobGraph;
+import org.apache.flink.runtime.jobgraph.JobVertex;
+import org.apache.flink.runtime.jobgraph.OperatorID;
+import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
+import org.apache.flink.runtime.jobmaster.DefaultExecutionDeploymentTracker;
+import org.apache.flink.runtime.jobmaster.TestUtils;
+import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
+import org.apache.flink.runtime.shuffle.NettyShuffleMaster;
+import org.apache.flink.runtime.testingUtils.TestingUtils;
+import org.apache.flink.runtime.testtasks.NoOpInvokable;
+import org.apache.flink.util.TestLogger;
+
+import org.hamcrest.MatcherAssert;
+import org.hamcrest.Matchers;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import javax.annotation.Nonnull;
+
+import java.io.File;
+import java.io.IOException;
+
+import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+
+/** Tests for the {@link DefaultExecutionGraphFactory}. */
+public class DefaultExecutionGraphFactoryTest extends TestLogger {
+
+    @ClassRule public static final TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder();
+
+    @Test
+    public void testRestoringModifiedJobFromSavepointFails() throws Exception {
+        final JobGraph jobGraphWithNewOperator = createJobGraphWithSavepoint(false, 42L);
+
+        final ExecutionGraphFactory executionGraphFactory = createExecutionGraphFactory();
+
+        try {
+            executionGraphFactory.createAndRestoreExecutionGraph(
+                    jobGraphWithNewOperator,
+                    new StandaloneCompletedCheckpointStore(1),
+                    new CheckpointsCleaner(),
+                    new StandaloneCheckpointIDCounter(),
+                    TaskDeploymentDescriptorFactory.PartitionLocationConstraint.CAN_BE_UNKNOWN,
+                    0L,
+                    new DefaultVertexAttemptNumberStore(),
+                    log);
+            fail("Expected ExecutionGraph creation to fail because of non restored state.");
+        } catch (Exception e) {
+            assertThat(
+                    e, FlinkMatchers.containsMessage("Failed to rollback to checkpoint/savepoint"));
+        }
+    }
+
+    @Test
+    public void testRestoringModifiedJobFromSavepointWithAllowNonRestoredStateSucceeds()
+            throws Exception {
+        // create savepoint data
+        final long savepointId = 42L;
+        final JobGraph jobGraphWithNewOperator = createJobGraphWithSavepoint(true, savepointId);
+
+        final ExecutionGraphFactory executionGraphFactory = createExecutionGraphFactory();
+
+        final StandaloneCompletedCheckpointStore completedCheckpointStore =
+                new StandaloneCompletedCheckpointStore(1);
+        executionGraphFactory.createAndRestoreExecutionGraph(
+                jobGraphWithNewOperator,
+                completedCheckpointStore,
+                new CheckpointsCleaner(),
+                new StandaloneCheckpointIDCounter(),
+                TaskDeploymentDescriptorFactory.PartitionLocationConstraint.CAN_BE_UNKNOWN,
+                0L,
+                new DefaultVertexAttemptNumberStore(),
+                log);
+
+        final CompletedCheckpoint savepoint = completedCheckpointStore.getLatestCheckpoint(false);
+
+        MatcherAssert.assertThat(savepoint, notNullValue());
+
+        MatcherAssert.assertThat(savepoint.getCheckpointID(), Matchers.is(savepointId));
+    }
+
+    @Nonnull
+    private ExecutionGraphFactory createExecutionGraphFactory() {
+        final ExecutionGraphFactory executionGraphFactory =
+                new DefaultExecutionGraphFactory(
+                        new Configuration(),
+                        ClassLoader.getSystemClassLoader(),
+                        new DefaultExecutionDeploymentTracker(),
+                        TestingUtils.defaultExecutor(),
+                        TestingUtils.defaultExecutor(),
+                        Time.milliseconds(0L),
+                        UnregisteredMetricGroups.createUnregisteredJobManagerJobMetricGroup(),
+                        VoidBlobWriter.getInstance(),
+                        NettyShuffleMaster.INSTANCE,
+                        NoOpJobMasterPartitionTracker.INSTANCE);
+        return executionGraphFactory;
+    }
+
+    @Nonnull
+    private JobGraph createJobGraphWithSavepoint(boolean allowNonRestoredState, long savepointId)
+            throws IOException {
+        // create savepoint data
+        final OperatorID operatorID = new OperatorID();
+        final File savepointFile =
+                TestUtils.createSavepointWithOperatorState(
+                        TEMPORARY_FOLDER.newFile(), savepointId, operatorID);
+
+        // set savepoint settings which don't allow non restored state
+        final SavepointRestoreSettings savepointRestoreSettings =
+                SavepointRestoreSettings.forPath(
+                        savepointFile.getAbsolutePath(), allowNonRestoredState);
+
+        // create a new operator
+        final JobVertex jobVertex = new JobVertex("New operator");
+        jobVertex.setInvokableClass(NoOpInvokable.class);
+        jobVertex.setParallelism(1);
+
+        // this test will fail in the end due to the previously created Savepoint having a state for
+        // a given OperatorID that does not match any operator of the newly created JobGraph
+        return TestUtils.createJobGraphFromJobVerticesWithCheckpointing(
+                savepointRestoreSettings, jobVertex);
+    }
+}
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java
index 3be6b25..e924538 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java
@@ -24,10 +24,6 @@ import org.apache.flink.configuration.Configuration;
 import org.apache.flink.core.testutils.FlinkMatchers;
 import org.apache.flink.runtime.JobException;
 import org.apache.flink.runtime.checkpoint.CheckpointCoordinator;
-import org.apache.flink.runtime.checkpoint.CheckpointRecoveryFactory;
-import org.apache.flink.runtime.checkpoint.CompletedCheckpoint;
-import org.apache.flink.runtime.checkpoint.StandaloneCheckpointIDCounter;
-import org.apache.flink.runtime.checkpoint.StandaloneCompletedCheckpointStore;
 import org.apache.flink.runtime.checkpoint.hooks.TestMasterHook;
 import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutor;
 import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutorServiceAdapter;
@@ -49,12 +45,9 @@ import org.apache.flink.runtime.jobgraph.JobGraph;
 import org.apache.flink.runtime.jobgraph.JobGraphTestUtils;
 import org.apache.flink.runtime.jobgraph.JobVertex;
 import org.apache.flink.runtime.jobgraph.JobVertexID;
-import org.apache.flink.runtime.jobgraph.OperatorID;
-import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
 import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
 import org.apache.flink.runtime.jobmanager.scheduler.NoResourceAvailableException;
 import org.apache.flink.runtime.jobmaster.LogicalSlot;
-import org.apache.flink.runtime.jobmaster.TestUtils;
 import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
 import org.apache.flink.runtime.scheduler.strategy.PipelinedRegionSchedulingStrategy;
 import org.apache.flink.runtime.scheduler.strategy.SchedulingExecutionVertex;
@@ -72,7 +65,6 @@ import org.apache.flink.util.TestLogger;
 import org.apache.flink.shaded.guava18.com.google.common.collect.Iterables;
 import org.apache.flink.shaded.guava18.com.google.common.collect.Range;
 
-import org.hamcrest.MatcherAssert;
 import org.hamcrest.core.Is;
 import org.junit.After;
 import org.junit.Before;
@@ -80,7 +72,6 @@ import org.junit.ClassRule;
 import org.junit.Test;
 import org.junit.rules.TemporaryFolder;
 
-import java.io.File;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Iterator;
@@ -94,7 +85,6 @@ import java.util.function.Consumer;
 import java.util.stream.Collectors;
 import java.util.stream.StreamSupport;
 
-import static org.apache.flink.runtime.checkpoint.PerJobCheckpointRecoveryFactory.useSameServicesForAllJobs;
 import static org.apache.flink.runtime.scheduler.SchedulerTestingUtils.acknowledgePendingCheckpoint;
 import static org.apache.flink.runtime.scheduler.SchedulerTestingUtils.enableCheckpointing;
 import static org.apache.flink.runtime.scheduler.SchedulerTestingUtils.getCheckpointCoordinator;
@@ -1141,84 +1131,6 @@ public class DefaultSchedulerTest extends TestLogger {
                 lessThanOrEqualTo(updateStateTriggeringJobFailureTimeframe.upperEndpoint()));
     }
 
-    @Test
-    public void testRestoringModifiedJobFromSavepointFails() throws Exception {
-        // create savepoint data
-        final long savepointId = 42L;
-        final OperatorID operatorID = new OperatorID();
-        final File savepointFile =
-                TestUtils.createSavepointWithOperatorState(
-                        TEMPORARY_FOLDER.newFile(), savepointId, operatorID);
-
-        // set savepoint settings which don't allow non restored state
-        final SavepointRestoreSettings savepointRestoreSettings =
-                SavepointRestoreSettings.forPath(savepointFile.getAbsolutePath(), false);
-
-        // create a new operator
-        final JobVertex jobVertex = new JobVertex("New operator");
-        jobVertex.setInvokableClass(NoOpInvokable.class);
-
-        // this test will fail in the end due to the previously created Savepoint having a state for
-        // a given OperatorID that does not match any operator of the newly created JobGraph
-        final JobGraph jobGraphWithNewOperator =
-                TestUtils.createJobGraphFromJobVerticesWithCheckpointing(
-                        savepointRestoreSettings, jobVertex);
-
-        try {
-            // creating the DefaultScheduler should try to restore the ExecutionGraph
-            SchedulerTestingUtils.newSchedulerBuilder(
-                            jobGraphWithNewOperator,
-                            ComponentMainThreadExecutorServiceAdapter.forMainThread())
-                    .build();
-            fail("Expected JobMaster creation to fail because of restore failure.");
-        } catch (IllegalStateException ise) {
-            assertThat(
-                    ise,
-                    FlinkMatchers.containsMessage("Failed to rollback to checkpoint/savepoint"));
-        }
-    }
-
-    @Test
-    public void testRestoringModifiedJobFromSavepointWithAllowNonRestoredStateSucceeds()
-            throws Exception {
-        // create savepoint data
-        final long savepointId = 42L;
-        final OperatorID operatorID = new OperatorID();
-        final File savepointFile =
-                TestUtils.createSavepointWithOperatorState(
-                        TEMPORARY_FOLDER.newFile(), savepointId, operatorID);
-
-        // allow for non restored state
-        final SavepointRestoreSettings savepointRestoreSettings =
-                SavepointRestoreSettings.forPath(savepointFile.getAbsolutePath(), true);
-
-        // create a new operator
-        final JobVertex jobVertex = new JobVertex("New operator");
-        jobVertex.setInvokableClass(NoOpInvokable.class);
-        final JobGraph jobGraphWithNewOperator =
-                TestUtils.createJobGraphFromJobVerticesWithCheckpointing(
-                        savepointRestoreSettings, jobVertex);
-
-        final StandaloneCompletedCheckpointStore completedCheckpointStore =
-                new StandaloneCompletedCheckpointStore(1);
-        final CheckpointRecoveryFactory testingCheckpointRecoveryFactory =
-                useSameServicesForAllJobs(
-                        completedCheckpointStore, new StandaloneCheckpointIDCounter());
-
-        SchedulerTestingUtils.newSchedulerBuilder(
-                        jobGraphWithNewOperator,
-                        ComponentMainThreadExecutorServiceAdapter.forMainThread())
-                .setCheckpointRecoveryFactory(testingCheckpointRecoveryFactory)
-                .build();
-
-        // creating the DefaultScheduler should have read the savepoint
-        final CompletedCheckpoint savepoint = completedCheckpointStore.getLatestCheckpoint(false);
-
-        MatcherAssert.assertThat(savepoint, notNullValue());
-
-        MatcherAssert.assertThat(savepoint.getCheckpointID(), is(savepointId));
-    }
-
     private static TaskExecutionState createFailedTaskExecutionState(
             ExecutionAttemptID executionAttemptID) {
         return new TaskExecutionState(
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/SchedulerTestingUtils.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/SchedulerTestingUtils.java
index 1901953..9f7d993 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/SchedulerTestingUtils.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/SchedulerTestingUtils.java
@@ -523,31 +523,39 @@ public class SchedulerTestingUtils {
         }
 
         public DefaultScheduler build() throws Exception {
+            final ExecutionGraphFactory executionGraphFactory =
+                    new DefaultExecutionGraphFactory(
+                            jobMasterConfiguration,
+                            userCodeLoader,
+                            new DefaultExecutionDeploymentTracker(),
+                            futureExecutor,
+                            ioExecutor,
+                            rpcTimeout,
+                            jobManagerJobMetricGroup,
+                            blobWriter,
+                            shuffleMaster,
+                            partitionTracker);
+
             return new DefaultScheduler(
                     log,
                     jobGraph,
                     ioExecutor,
                     jobMasterConfiguration,
                     componentMainThreadExecutor -> {},
-                    futureExecutor,
                     delayExecutor,
                     userCodeLoader,
                     checkpointRecoveryFactory,
-                    rpcTimeout,
-                    blobWriter,
                     jobManagerJobMetricGroup,
-                    shuffleMaster,
-                    partitionTracker,
                     schedulingStrategyFactory,
                     failoverStrategyFactory,
                     restartBackoffTimeStrategy,
                     executionVertexOperations,
                     executionVertexVersioner,
                     executionSlotAllocatorFactory,
-                    new DefaultExecutionDeploymentTracker(),
                     System.currentTimeMillis(),
                     mainThreadExecutor,
-                    jobStatusListener);
+                    jobStatusListener,
+                    executionGraphFactory);
         }
     }
 }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerBuilder.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerBuilder.java
index e005170..9435ccd 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerBuilder.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerBuilder.java
@@ -37,6 +37,8 @@ import org.apache.flink.runtime.jobmaster.slotpool.DefaultDeclarativeSlotPool;
 import org.apache.flink.runtime.metrics.groups.JobManagerJobMetricGroup;
 import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
 import org.apache.flink.runtime.rpc.FatalErrorHandler;
+import org.apache.flink.runtime.scheduler.DefaultExecutionGraphFactory;
+import org.apache.flink.runtime.scheduler.ExecutionGraphFactory;
 import org.apache.flink.runtime.scheduler.adaptive.allocator.SlotAllocator;
 import org.apache.flink.runtime.shuffle.NettyShuffleMaster;
 import org.apache.flink.runtime.shuffle.ShuffleMaster;
@@ -182,6 +184,19 @@ public class AdaptiveSchedulerBuilder {
     }
 
     public AdaptiveScheduler build() throws Exception {
+        final ExecutionGraphFactory executionGraphFactory =
+                new DefaultExecutionGraphFactory(
+                        jobMasterConfiguration,
+                        userCodeLoader,
+                        new DefaultExecutionDeploymentTracker(),
+                        futureExecutor,
+                        ioExecutor,
+                        rpcTimeout,
+                        jobManagerJobMetricGroup,
+                        blobWriter,
+                        shuffleMaster,
+                        partitionTracker);
+
         return new AdaptiveScheduler(
                 jobGraph,
                 jobMasterConfiguration,
@@ -190,20 +205,15 @@ public class AdaptiveSchedulerBuilder {
                         ? AdaptiveSchedulerFactory.createSlotSharingSlotAllocator(
                                 declarativeSlotPool)
                         : slotAllocator,
-                futureExecutor,
                 ioExecutor,
                 userCodeLoader,
                 checkpointRecoveryFactory,
-                rpcTimeout,
-                blobWriter,
                 jobManagerJobMetricGroup,
-                shuffleMaster,
-                partitionTracker,
                 restartBackoffTimeStrategy,
-                new DefaultExecutionDeploymentTracker(),
                 initializationTimestamp,
                 mainThreadExecutor,
                 fatalErrorHandler,
-                jobStatusListener);
+                jobStatusListener,
+                executionGraphFactory);
     }
 }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
index c4ba684..9bbf7a5 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
@@ -22,16 +22,11 @@ import org.apache.flink.api.common.JobStatus;
 import org.apache.flink.api.common.time.Time;
 import org.apache.flink.configuration.Configuration;
 import org.apache.flink.configuration.JobManagerOptions;
-import org.apache.flink.core.testutils.FlinkMatchers;
 import org.apache.flink.core.testutils.OneShotLatch;
 import org.apache.flink.metrics.Gauge;
 import org.apache.flink.runtime.checkpoint.CheckpointException;
 import org.apache.flink.runtime.checkpoint.CheckpointIDCounter;
-import org.apache.flink.runtime.checkpoint.CheckpointRecoveryFactory;
-import org.apache.flink.runtime.checkpoint.CompletedCheckpoint;
 import org.apache.flink.runtime.checkpoint.CompletedCheckpointStore;
-import org.apache.flink.runtime.checkpoint.StandaloneCheckpointIDCounter;
-import org.apache.flink.runtime.checkpoint.StandaloneCompletedCheckpointStore;
 import org.apache.flink.runtime.checkpoint.TestingCheckpointIDCounter;
 import org.apache.flink.runtime.checkpoint.TestingCheckpointRecoveryFactory;
 import org.apache.flink.runtime.checkpoint.TestingCompletedCheckpointStore;
@@ -54,13 +49,11 @@ import org.apache.flink.runtime.jobgraph.JobGraph;
 import org.apache.flink.runtime.jobgraph.JobGraphTestUtils;
 import org.apache.flink.runtime.jobgraph.JobVertex;
 import org.apache.flink.runtime.jobgraph.OperatorID;
-import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
 import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
 import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration;
 import org.apache.flink.runtime.jobgraph.tasks.JobCheckpointingSettings;
 import org.apache.flink.runtime.jobmanager.PartitionProducerDisposedException;
 import org.apache.flink.runtime.jobmanager.slots.TaskManagerGateway;
-import org.apache.flink.runtime.jobmaster.TestUtils;
 import org.apache.flink.runtime.jobmaster.slotpool.DefaultAllocatedSlotPool;
 import org.apache.flink.runtime.jobmaster.slotpool.DefaultDeclarativeSlotPool;
 import org.apache.flink.runtime.jobmaster.slotpool.SlotPoolTestUtils;
@@ -73,22 +66,17 @@ import org.apache.flink.runtime.operators.coordination.CoordinationRequest;
 import org.apache.flink.runtime.operators.coordination.TaskNotRunningException;
 import org.apache.flink.runtime.operators.coordination.TestOperatorEvent;
 import org.apache.flink.runtime.rest.handler.legacy.utils.ArchivedExecutionGraphBuilder;
-import org.apache.flink.runtime.scheduler.GloballyTerminalJobStatusListener;
 import org.apache.flink.runtime.scheduler.adaptive.allocator.TestingSlotAllocator;
 import org.apache.flink.runtime.slots.ResourceRequirement;
 import org.apache.flink.runtime.taskexecutor.TestingTaskExecutorGatewayBuilder;
 import org.apache.flink.runtime.taskmanager.LocalTaskManagerLocation;
 import org.apache.flink.runtime.taskmanager.TaskExecutionState;
-import org.apache.flink.runtime.testtasks.NoOpInvokable;
 import org.apache.flink.runtime.util.ResourceCounter;
 import org.apache.flink.runtime.util.TestingFatalErrorHandler;
 import org.apache.flink.testutils.executor.TestExecutorResource;
 import org.apache.flink.util.FlinkException;
 import org.apache.flink.util.TestLogger;
-import org.apache.flink.util.function.FunctionUtils;
 
-import org.hamcrest.MatcherAssert;
-import org.hamcrest.Matchers;
 import org.junit.ClassRule;
 import org.junit.Test;
 import org.junit.rules.TemporaryFolder;
@@ -97,7 +85,6 @@ import org.slf4j.Logger;
 import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
 
-import java.io.File;
 import java.io.IOException;
 import java.time.Duration;
 import java.util.Optional;
@@ -111,13 +98,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
 
 import static org.apache.flink.core.testutils.FlinkMatchers.futureFailedWith;
-import static org.apache.flink.runtime.checkpoint.PerJobCheckpointRecoveryFactory.useSameServicesForAllJobs;
 import static org.apache.flink.runtime.jobmaster.slotpool.DefaultDeclarativeSlotPoolTest.createSlotOffersForResourceRequirements;
 import static org.apache.flink.runtime.jobmaster.slotpool.SlotPoolTestUtils.offerSlots;
 import static org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups.createUnregisteredJobManagerMetricGroup;
 import static org.hamcrest.Matchers.contains;
 import static org.hamcrest.Matchers.instanceOf;
-import static org.hamcrest.Matchers.notNullValue;
 import static org.hamcrest.core.Is.is;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertThat;
@@ -764,135 +749,6 @@ public class AdaptiveSchedulerTest extends TestLogger {
         scheduler.requestPartitionState(new IntermediateDataSetID(), new ResultPartitionID());
     }
 
-    @Test
-    public void testRestoringModifiedJobFromSavepointFails() throws Exception {
-        // create savepoint data
-        final long savepointId = 42L;
-        final OperatorID operatorID = new OperatorID();
-        final File savepointFile =
-                TestUtils.createSavepointWithOperatorState(
-                        TEMPORARY_FOLDER.newFile(), savepointId, operatorID);
-
-        // set savepoint settings which don't allow non restored state
-        final SavepointRestoreSettings savepointRestoreSettings =
-                SavepointRestoreSettings.forPath(savepointFile.getAbsolutePath(), false);
-
-        // create a new operator
-        final JobVertex jobVertex = new JobVertex("New operator");
-        jobVertex.setInvokableClass(NoOpInvokable.class);
-        jobVertex.setParallelism(1);
-
-        // this test will fail in the end due to the previously created Savepoint having a state for
-        // a given OperatorID that does not match any operator of the newly created JobGraph
-        final JobGraph jobGraphWithNewOperator =
-                TestUtils.createJobGraphFromJobVerticesWithCheckpointing(
-                        savepointRestoreSettings, jobVertex);
-
-        final DefaultDeclarativeSlotPool declarativeSlotPool =
-                createDeclarativeSlotPool(jobGraphWithNewOperator.getJobID());
-
-        final GloballyTerminalJobStatusListener jobStatusListener =
-                new GloballyTerminalJobStatusListener();
-
-        final AdaptiveScheduler adaptiveScheduler =
-                new AdaptiveSchedulerBuilder(
-                                jobGraphWithNewOperator, singleThreadMainThreadExecutor)
-                        .setDeclarativeSlotPool(declarativeSlotPool)
-                        .setJobStatusListener(jobStatusListener)
-                        .build();
-
-        singleThreadMainThreadExecutor.execute(
-                () -> {
-                    adaptiveScheduler.startScheduling();
-                    offerSlots(
-                            declarativeSlotPool,
-                            createSlotOffersForResourceRequirements(
-                                    ResourceCounter.withResource(ResourceProfile.UNKNOWN, 1)));
-                });
-
-        assertThat(jobStatusListener.getTerminationFuture().join(), is(JobStatus.FAILED));
-
-        final ArchivedExecutionGraph archivedExecutionGraph =
-                CompletableFuture.supplyAsync(
-                                () -> adaptiveScheduler.requestJob().getArchivedExecutionGraph(),
-                                singleThreadMainThreadExecutor)
-                        .join();
-
-        assertThat(archivedExecutionGraph.getState(), is(JobStatus.FAILED));
-        assertThat(
-                archivedExecutionGraph.getFailureInfo().getException(),
-                FlinkMatchers.containsMessage("Failed to rollback to checkpoint/savepoint"));
-    }
-
-    @Test
-    public void testRestoringModifiedJobFromSavepointWithAllowNonRestoredStateSucceeds()
-            throws Exception {
-        // create savepoint data
-        final long savepointId = 42L;
-        final OperatorID operatorID = new OperatorID();
-        final File savepointFile =
-                TestUtils.createSavepointWithOperatorState(
-                        TEMPORARY_FOLDER.newFile(), savepointId, operatorID);
-
-        // allow for non restored state
-        final SavepointRestoreSettings savepointRestoreSettings =
-                SavepointRestoreSettings.forPath(savepointFile.getAbsolutePath(), true);
-
-        // create a new operator
-        final JobVertex jobVertex = new JobVertex("New operator");
-        jobVertex.setInvokableClass(NoOpInvokable.class);
-        jobVertex.setParallelism(1);
-
-        final JobGraph jobGraphWithNewOperator =
-                TestUtils.createJobGraphFromJobVerticesWithCheckpointing(
-                        savepointRestoreSettings, jobVertex);
-
-        final StandaloneCompletedCheckpointStore completedCheckpointStore =
-                new StandaloneCompletedCheckpointStore(1);
-        final CheckpointRecoveryFactory testingCheckpointRecoveryFactory =
-                useSameServicesForAllJobs(
-                        completedCheckpointStore, new StandaloneCheckpointIDCounter());
-
-        final DefaultDeclarativeSlotPool declarativeSlotPool =
-                createDeclarativeSlotPool(jobGraphWithNewOperator.getJobID());
-
-        AdaptiveScheduler adaptiveScheduler =
-                new AdaptiveSchedulerBuilder(
-                                jobGraphWithNewOperator, singleThreadMainThreadExecutor)
-                        .setCheckpointRecoveryFactory(testingCheckpointRecoveryFactory)
-                        .setDeclarativeSlotPool(declarativeSlotPool)
-                        .build();
-
-        final OneShotLatch submitTaskLatch = new OneShotLatch();
-        final TaskManagerGateway taskManagerGateway =
-                createWaitingForTaskSubmissionTaskManagerGateway(submitTaskLatch);
-
-        singleThreadMainThreadExecutor.execute(
-                () -> {
-                    adaptiveScheduler.startScheduling();
-
-                    offerSlots(
-                            declarativeSlotPool,
-                            createSlotOffersForResourceRequirements(
-                                    ResourceCounter.withResource(ResourceProfile.UNKNOWN, 1)),
-                            taskManagerGateway);
-                });
-
-        submitTaskLatch.await();
-
-        // starting and offering the required slots should trigger the ExecutionGraph creation
-        final CompletedCheckpoint savepoint =
-                CompletableFuture.supplyAsync(
-                                FunctionUtils.uncheckedSupplier(
-                                        () -> completedCheckpointStore.getLatestCheckpoint(false)),
-                                singleThreadMainThreadExecutor)
-                        .join();
-
-        MatcherAssert.assertThat(savepoint, notNullValue());
-
-        MatcherAssert.assertThat(savepoint.getCheckpointID(), Matchers.is(savepointId));
-    }
-
     @Nonnull
     private TaskManagerGateway createWaitingForTaskSubmissionTaskManagerGateway(
             OneShotLatch submitTaskLatch) {

[flink] 15/17: [FLINK-21602] Allow SchedulerNG to terminate asynchronously

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit a1798ec3ee09c42435524fb890ba1b339392399e
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Wed Mar 17 09:37:25 2021 +0100

    [FLINK-21602] Allow SchedulerNG to terminate asynchronously
    
    This commit let the SchedulerNG extend the AutoCloseableAync interface in order to support
    asynchronous termination behaviours. Moreover, this commit let the JobMaster wait on the
    scheduler's termination before terminating itself.
---
 .../apache/flink/runtime/jobmaster/JobMaster.java  | 50 ++++++++++------------
 .../flink/runtime/scheduler/SchedulerBase.java     |  6 ++-
 .../flink/runtime/scheduler/SchedulerNG.java       |  5 +--
 .../scheduler/adaptive/AdaptiveScheduler.java      |  6 ++-
 .../executiongraph/ExecutionGraphSuspendTest.java  | 22 ++++------
 .../flink/runtime/jobmaster/JobMasterTest.java     | 31 ++++++++++++++
 .../OperatorCoordinatorSchedulerTest.java          |  4 +-
 .../runtime/scheduler/DefaultSchedulerTest.java    |  4 +-
 .../runtime/scheduler/TestingSchedulerNG.java      | 21 +++++----
 9 files changed, 90 insertions(+), 59 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobMaster.java b/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobMaster.java
index 3e115ff..8130b8e 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobMaster.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobMaster.java
@@ -105,6 +105,7 @@ import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
 import java.util.concurrent.Executor;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeoutException;
@@ -394,18 +395,17 @@ public class JobMaster extends PermanentlyFencedRpcEndpoint<JobMasterId>
         log.info("Stopping the JobMaster for job {}({}).", jobGraph.getName(), jobGraph.getJobID());
 
         // make sure there is a graceful exit
-        try {
-            stopJobExecution(
-                    new FlinkException(
-                            String.format(
-                                    "Stopping JobMaster for job %s(%s).",
-                                    jobGraph.getName(), jobGraph.getJobID())));
-        } catch (Exception e) {
-            return FutureUtils.completedExceptionally(
-                    new JobMasterException("Could not properly stop the JobMaster.", e));
-        }
-
-        return CompletableFuture.completedFuture(null);
+        return stopJobExecution(
+                        new FlinkException(
+                                String.format(
+                                        "Stopping JobMaster for job %s(%s).",
+                                        jobGraph.getName(), jobGraph.getJobID())))
+                .exceptionally(
+                        exception -> {
+                            throw new CompletionException(
+                                    new JobMasterException(
+                                            "Could not properly stop the JobMaster.", exception));
+                        });
     }
 
     // ----------------------------------------------------------------------------------------------
@@ -920,22 +920,17 @@ public class JobMaster extends PermanentlyFencedRpcEndpoint<JobMasterId>
         ExceptionUtils.tryRethrowException(resultingException);
     }
 
-    private void stopJobExecution(final Exception cause) throws Exception {
+    private CompletableFuture<Void> stopJobExecution(final Exception cause) {
         validateRunsInMainThread();
 
-        stopScheduling(cause);
-
-        disconnectTaskManagerResourceManagerConnections(cause);
-
-        Exception resultingException = null;
+        final CompletableFuture<Void> terminationFuture = stopScheduling();
 
-        try {
-            stopJobMasterServices();
-        } catch (Exception e) {
-            resultingException = e;
-        }
-
-        ExceptionUtils.tryRethrowException(resultingException);
+        return FutureUtils.runAfterwards(
+                terminationFuture,
+                () -> {
+                    disconnectTaskManagerResourceManagerConnections(cause);
+                    stopJobMasterServices();
+                });
     }
 
     private void disconnectTaskManagerResourceManagerConnections(Exception cause) {
@@ -960,10 +955,11 @@ public class JobMaster extends PermanentlyFencedRpcEndpoint<JobMasterId>
         schedulerNG.startScheduling();
     }
 
-    private void stopScheduling(Exception cause) {
-        schedulerNG.suspend(cause);
+    private CompletableFuture<Void> stopScheduling() {
         jobManagerJobMetricGroup.close();
         jobStatusListener.stop();
+
+        return schedulerNG.closeAsync();
     }
 
     // ----------------------------------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java
index 56c06ae..aacea94 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java
@@ -505,12 +505,16 @@ public abstract class SchedulerBase implements SchedulerNG, CheckpointScheduling
     protected abstract void startSchedulingInternal();
 
     @Override
-    public void suspend(Throwable cause) {
+    public CompletableFuture<Void> closeAsync() {
         mainThreadExecutor.assertRunningInMainThread();
 
+        final FlinkException cause = new FlinkException("Scheduler is being stopped.");
+
         incrementVersionsOfAllVertices();
         executionGraph.suspend(cause);
         operatorCoordinatorHandler.disposeAllOperatorCoordinators();
+
+        return CompletableFuture.completedFuture(null);
     }
 
     @Override
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerNG.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerNG.java
index 505714d..4e306d9 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerNG.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerNG.java
@@ -47,6 +47,7 @@ import org.apache.flink.runtime.query.KvStateLocation;
 import org.apache.flink.runtime.query.UnknownKvStateLocation;
 import org.apache.flink.runtime.state.KeyGroupRange;
 import org.apache.flink.runtime.taskmanager.TaskExecutionState;
+import org.apache.flink.util.AutoCloseableAsync;
 import org.apache.flink.util.FlinkException;
 
 import javax.annotation.Nullable;
@@ -64,12 +65,10 @@ import java.util.concurrent.CompletableFuture;
  * <p>Implementations can expect that methods will not be invoked concurrently. In fact, all
  * invocations will originate from a thread in the {@link ComponentMainThreadExecutor}.
  */
-public interface SchedulerNG {
+public interface SchedulerNG extends AutoCloseableAsync {
 
     void startScheduling();
 
-    void suspend(Throwable cause);
-
     void cancel();
 
     CompletableFuture<JobStatus> getJobTerminationFuture();
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
index db88e05..4615175 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
@@ -282,8 +282,10 @@ public class AdaptiveScheduler
     }
 
     @Override
-    public void suspend(Throwable cause) {
-        state.suspend(cause);
+    public CompletableFuture<Void> closeAsync() {
+        state.suspend(new FlinkException("AdaptiveScheduler is being stopped."));
+
+        return FutureUtils.completedVoidFuture();
     }
 
     @Override
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/executiongraph/ExecutionGraphSuspendTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/executiongraph/ExecutionGraphSuspendTest.java
index af09723..c196a32 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/executiongraph/ExecutionGraphSuspendTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/executiongraph/ExecutionGraphSuspendTest.java
@@ -57,7 +57,7 @@ public class ExecutionGraphSuspendTest extends TestLogger {
 
         // suspend
 
-        scheduler.suspend(new Exception("suspend"));
+        scheduler.closeAsync();
 
         assertEquals(JobStatus.SUSPENDED, eg.getState());
         validateAllVerticesInState(eg, ExecutionState.CANCELED);
@@ -83,7 +83,7 @@ public class ExecutionGraphSuspendTest extends TestLogger {
         validateAllVerticesInState(eg, ExecutionState.DEPLOYING);
 
         // suspend
-        scheduler.suspend(new Exception("suspend"));
+        scheduler.closeAsync();
 
         assertEquals(JobStatus.SUSPENDED, eg.getState());
         validateCancelRpcCalls(gateway, parallelism);
@@ -109,7 +109,7 @@ public class ExecutionGraphSuspendTest extends TestLogger {
         validateAllVerticesInState(eg, ExecutionState.RUNNING);
 
         // suspend
-        scheduler.suspend(new Exception("suspend"));
+        scheduler.closeAsync();
 
         assertEquals(JobStatus.SUSPENDED, eg.getState());
         validateCancelRpcCalls(gateway, parallelism);
@@ -135,7 +135,7 @@ public class ExecutionGraphSuspendTest extends TestLogger {
         validateCancelRpcCalls(gateway, parallelism);
 
         // suspend
-        scheduler.suspend(new Exception("suspend"));
+        scheduler.closeAsync();
 
         assertEquals(JobStatus.SUSPENDED, eg.getState());
         ensureCannotLeaveSuspendedState(scheduler, gateway);
@@ -162,7 +162,7 @@ public class ExecutionGraphSuspendTest extends TestLogger {
         assertEquals(JobStatus.FAILED, eg.getState());
 
         // suspend
-        scheduler.suspend(new Exception("suspend"));
+        scheduler.closeAsync();
 
         // still in failed state
         assertEquals(JobStatus.FAILED, eg.getState());
@@ -187,7 +187,7 @@ public class ExecutionGraphSuspendTest extends TestLogger {
         validateCancelRpcCalls(gateway, parallelism);
 
         // suspend
-        scheduler.suspend(new Exception("suspend"));
+        scheduler.closeAsync();
 
         assertEquals(JobStatus.SUSPENDED, eg.getState());
 
@@ -215,7 +215,7 @@ public class ExecutionGraphSuspendTest extends TestLogger {
         assertEquals(JobStatus.CANCELED, eg.getTerminationFuture().get());
 
         // suspend
-        scheduler.suspend(new Exception("suspend"));
+        scheduler.closeAsync();
 
         // still in failed state
         assertEquals(JobStatus.CANCELED, eg.getState());
@@ -249,14 +249,10 @@ public class ExecutionGraphSuspendTest extends TestLogger {
         ExecutionGraphTestUtils.completeCancellingForAllVertices(eg);
         assertEquals(JobStatus.RESTARTING, eg.getState());
 
-        final Exception exception = new Exception("Suspended");
-
-        scheduler.suspend(exception);
+        scheduler.closeAsync();
 
         assertEquals(JobStatus.SUSPENDED, eg.getState());
 
-        assertEquals(exception, eg.getFailureCause());
-
         taskRestartExecutor.triggerScheduledTasks();
         assertEquals(JobStatus.SUSPENDED, eg.getState());
     }
@@ -281,7 +277,7 @@ public class ExecutionGraphSuspendTest extends TestLogger {
         assertEquals(JobStatus.SUSPENDED, eg.getState());
         validateNoInteractions(gateway);
 
-        scheduler.suspend(new Exception("suspend again"));
+        scheduler.closeAsync();
         assertEquals(JobStatus.SUSPENDED, eg.getState());
         validateNoInteractions(gateway);
 
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/JobMasterTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/JobMasterTest.java
index 5b7c1e9..f66d82a 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/JobMasterTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/JobMasterTest.java
@@ -1628,6 +1628,37 @@ public class JobMasterTest extends TestLogger {
         }
     }
 
+    @Test
+    public void testJobMasterOnlyTerminatesAfterTheSchedulerHasClosed() throws Exception {
+        final CompletableFuture<Void> schedulerTerminationFuture = new CompletableFuture<>();
+        final TestingSchedulerNG testingSchedulerNG =
+                TestingSchedulerNG.newBuilder()
+                        .setCloseAsyncSupplier(() -> schedulerTerminationFuture)
+                        .build();
+
+        final JobMaster jobMaster =
+                new JobMasterBuilder(jobGraph, rpcService)
+                        .withSlotPoolServiceSchedulerFactory(
+                                DefaultSlotPoolServiceSchedulerFactory.create(
+                                        TestingSlotPoolServiceBuilder.newBuilder(),
+                                        new TestingSchedulerNGFactory(testingSchedulerNG)))
+                        .createJobMaster();
+
+        jobMaster.start();
+
+        final CompletableFuture<Void> jobMasterTerminationFuture = jobMaster.closeAsync();
+
+        try {
+            jobMasterTerminationFuture.get(10L, TimeUnit.MILLISECONDS);
+            fail("Expected TimeoutException because the JobMaster should not terminate.");
+        } catch (TimeoutException expected) {
+        }
+
+        schedulerTerminationFuture.complete(null);
+
+        jobMasterTerminationFuture.get();
+    }
+
     private void runJobFailureWhenTaskExecutorTerminatesTest(
             HeartbeatServices heartbeatServices,
             BiConsumer<LocalUnresolvedTaskManagerLocation, JobMasterGateway> jobReachedRunningState,
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorSchedulerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorSchedulerTest.java
index 6a94253..02d1018 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorSchedulerTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorSchedulerTest.java
@@ -118,7 +118,7 @@ public class OperatorCoordinatorSchedulerTest extends TestLogger {
     @After
     public void shutdownScheduler() throws Exception {
         if (createdScheduler != null) {
-            createdScheduler.suspend(new Exception("shutdown"));
+            createdScheduler.close();
         }
     }
 
@@ -139,7 +139,7 @@ public class OperatorCoordinatorSchedulerTest extends TestLogger {
         final DefaultScheduler scheduler = createAndStartScheduler();
         final TestingOperatorCoordinator coordinator = getCoordinator(scheduler);
 
-        scheduler.suspend(new Exception("test suspend"));
+        scheduler.close();
 
         assertTrue(coordinator.isClosed());
     }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java
index dc2a1ee..cd2c06f 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java
@@ -875,7 +875,7 @@ public class DefaultSchedulerTest extends TestLogger {
     }
 
     @Test
-    public void suspendJobWillIncrementVertexVersions() {
+    public void suspendJobWillIncrementVertexVersions() throws Exception {
         final JobGraph jobGraph = singleNonParallelJobVertexJobGraph();
         final JobVertex onlyJobVertex = getOnlyJobVertex(jobGraph);
         final ExecutionVertexID onlyExecutionVertexId =
@@ -885,7 +885,7 @@ public class DefaultSchedulerTest extends TestLogger {
         final ExecutionVertexVersion executionVertexVersion =
                 executionVertexVersioner.getExecutionVertexVersion(onlyExecutionVertexId);
 
-        scheduler.suspend(new Exception("forced suspend"));
+        scheduler.close();
 
         assertTrue(executionVertexVersioner.isModified(executionVertexVersion));
     }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/TestingSchedulerNG.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/TestingSchedulerNG.java
index c87ac20..ad0682e 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/TestingSchedulerNG.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/TestingSchedulerNG.java
@@ -24,6 +24,7 @@ import org.apache.flink.queryablestate.KvStateID;
 import org.apache.flink.runtime.accumulators.AccumulatorSnapshot;
 import org.apache.flink.runtime.checkpoint.CheckpointMetrics;
 import org.apache.flink.runtime.checkpoint.TaskStateSnapshot;
+import org.apache.flink.runtime.concurrent.FutureUtils;
 import org.apache.flink.runtime.execution.ExecutionState;
 import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
 import org.apache.flink.runtime.executiongraph.TaskExecutionStateTransition;
@@ -48,24 +49,25 @@ import java.net.InetSocketAddress;
 import java.util.concurrent.CompletableFuture;
 import java.util.function.BiFunction;
 import java.util.function.Consumer;
+import java.util.function.Supplier;
 
 /** Testing implementation of the {@link SchedulerNG}. */
 public class TestingSchedulerNG implements SchedulerNG {
     private final CompletableFuture<JobStatus> jobTerminationFuture;
     private final Runnable startSchedulingRunnable;
-    private final Consumer<Throwable> suspendConsumer;
+    private final Supplier<CompletableFuture<Void>> closeAsyncSupplier;
     private final BiFunction<String, Boolean, CompletableFuture<String>> triggerSavepointFunction;
     private final Consumer<Throwable> handleGlobalFailureConsumer;
 
     private TestingSchedulerNG(
             CompletableFuture<JobStatus> jobTerminationFuture,
             Runnable startSchedulingRunnable,
-            Consumer<Throwable> suspendConsumer,
+            Supplier<CompletableFuture<Void>> closeAsyncSupplier,
             BiFunction<String, Boolean, CompletableFuture<String>> triggerSavepointFunction,
             Consumer<Throwable> handleGlobalFailureConsumer) {
         this.jobTerminationFuture = jobTerminationFuture;
         this.startSchedulingRunnable = startSchedulingRunnable;
-        this.suspendConsumer = suspendConsumer;
+        this.closeAsyncSupplier = closeAsyncSupplier;
         this.triggerSavepointFunction = triggerSavepointFunction;
         this.handleGlobalFailureConsumer = handleGlobalFailureConsumer;
     }
@@ -80,8 +82,8 @@ public class TestingSchedulerNG implements SchedulerNG {
     }
 
     @Override
-    public void suspend(Throwable cause) {
-        suspendConsumer.accept(cause);
+    public CompletableFuture<Void> closeAsync() {
+        return closeAsyncSupplier.get();
     }
 
     @Override
@@ -226,7 +228,8 @@ public class TestingSchedulerNG implements SchedulerNG {
     public static final class Builder {
         private CompletableFuture<JobStatus> jobTerminationFuture = new CompletableFuture<>();
         private Runnable startSchedulingRunnable = () -> {};
-        private Consumer<Throwable> suspendConsumer = ignored -> {};
+        private Supplier<CompletableFuture<Void>> closeAsyncSupplier =
+                FutureUtils::completedVoidFuture;
         private BiFunction<String, Boolean, CompletableFuture<String>> triggerSavepointFunction =
                 (ignoredA, ignoredB) -> new CompletableFuture<>();
         private Consumer<Throwable> handleGlobalFailureConsumer = (ignored) -> {};
@@ -241,8 +244,8 @@ public class TestingSchedulerNG implements SchedulerNG {
             return this;
         }
 
-        public Builder setSuspendConsumer(Consumer<Throwable> suspendConsumer) {
-            this.suspendConsumer = suspendConsumer;
+        public Builder setCloseAsyncSupplier(Supplier<CompletableFuture<Void>> closeAsyncSupplier) {
+            this.closeAsyncSupplier = closeAsyncSupplier;
             return this;
         }
 
@@ -262,7 +265,7 @@ public class TestingSchedulerNG implements SchedulerNG {
             return new TestingSchedulerNG(
                     jobTerminationFuture,
                     startSchedulingRunnable,
-                    suspendConsumer,
+                    closeAsyncSupplier,
                     triggerSavepointFunction,
                     handleGlobalFailureConsumer);
         }

[flink] 04/17: [hotfix] Let Restarting and WaitingForResources cancel scheduled tasks onLeave

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit ca968d305a99b63162136589e1d9f6ba4c9cdd2b
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Sun Mar 14 13:42:49 2021 +0100

    [hotfix] Let Restarting and WaitingForResources cancel scheduled tasks onLeave
    
    By canceling incompleted scheduled tasks when leaving, the states Restarting and WaitingForResources
    leave a cleaner state behind.
---
 .../flink/runtime/scheduler/adaptive/Restarting.java     | 16 +++++++++++++++-
 .../runtime/scheduler/adaptive/WaitingForResources.java  | 12 ++++++++++--
 .../scheduler/adaptive/AdaptiveSchedulerTest.java        |  3 ++-
 3 files changed, 27 insertions(+), 4 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Restarting.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Restarting.java
index 307dfa02..ffd7eb6 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Restarting.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Restarting.java
@@ -27,6 +27,8 @@ import org.apache.flink.util.Preconditions;
 
 import org.slf4j.Logger;
 
+import javax.annotation.Nullable;
+
 import java.time.Duration;
 import java.util.concurrent.ScheduledFuture;
 
@@ -37,6 +39,8 @@ class Restarting extends StateWithExecutionGraph {
 
     private final Duration backoffTime;
 
+    @Nullable private ScheduledFuture<?> goToWaitingForResourcesFuture;
+
     Restarting(
             Context context,
             ExecutionGraph executionGraph,
@@ -52,6 +56,15 @@ class Restarting extends StateWithExecutionGraph {
     }
 
     @Override
+    public void onLeave(Class<? extends State> newState) {
+        if (goToWaitingForResourcesFuture != null) {
+            goToWaitingForResourcesFuture.cancel(false);
+        }
+
+        super.onLeave(newState);
+    }
+
+    @Override
     public JobStatus getJobStatus() {
         return JobStatus.RESTARTING;
     }
@@ -75,7 +88,8 @@ class Restarting extends StateWithExecutionGraph {
     @Override
     void onGloballyTerminalState(JobStatus globallyTerminalState) {
         Preconditions.checkArgument(globallyTerminalState == JobStatus.CANCELED);
-        context.runIfState(this, context::goToWaitingForResources, backoffTime);
+        goToWaitingForResourcesFuture =
+                context.runIfState(this, context::goToWaitingForResources, backoffTime);
     }
 
     /** Context of the {@link Restarting} state. */
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResources.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResources.java
index 9489ddd..3b2daff 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResources.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/WaitingForResources.java
@@ -41,6 +41,8 @@ class WaitingForResources implements State, ResourceConsumer {
 
     private final ResourceCounter desiredResources;
 
+    private final ScheduledFuture<?> resourceTimeoutFuture;
+
     WaitingForResources(
             Context context,
             Logger log,
@@ -53,12 +55,18 @@ class WaitingForResources implements State, ResourceConsumer {
                 !desiredResources.isEmpty(), "Desired resources must not be empty");
 
         // since state transitions are not allowed in state constructors, schedule calls for later.
-        context.runIfState(
-                this, this::resourceTimeout, Preconditions.checkNotNull(resourceTimeout));
+        resourceTimeoutFuture =
+                context.runIfState(
+                        this, this::resourceTimeout, Preconditions.checkNotNull(resourceTimeout));
         context.runIfState(this, this::notifyNewResourcesAvailable, Duration.ZERO);
     }
 
     @Override
+    public void onLeave(Class<? extends State> newState) {
+        resourceTimeoutFuture.cancel(false);
+    }
+
+    @Override
     public void cancel() {
         context.goToFinished(context.getArchivedExecutionGraph(JobStatus.CANCELED, null));
     }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
index 0489e77..8a433a4 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
@@ -76,6 +76,7 @@ import org.apache.flink.runtime.taskmanager.TaskExecutionState;
 import org.apache.flink.runtime.testtasks.NoOpInvokable;
 import org.apache.flink.runtime.util.ResourceCounter;
 import org.apache.flink.runtime.util.TestingFatalErrorHandler;
+import org.apache.flink.util.ExecutorUtils;
 import org.apache.flink.util.FlinkException;
 import org.apache.flink.util.TestLogger;
 
@@ -769,7 +770,7 @@ public class AdaptiveSchedulerTest extends TestLogger {
                     archivedExecutionGraph.getFailureInfo().getException(),
                     FlinkMatchers.containsMessage("Failed to rollback to checkpoint/savepoint"));
         } finally {
-            singleThreadExecutor.shutdownNow();
+            ExecutorUtils.gracefulShutdown(10L, TimeUnit.SECONDS, singleThreadExecutor);
         }
     }
 

[flink] 02/17: [FLINK-21602] Let AdaptiveScheduler create the ExecutionGraph in the ioExecutor

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit c4545e06a54d3694ad106926eae2c592e01473b8
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Sun Mar 14 12:57:39 2021 +0100

    [FLINK-21602] Let AdaptiveScheduler create the ExecutionGraph in the ioExecutor
    
    The AdaptiveScheudler creates the ExecutionGraph now in the ioExecutor.
---
 .../scheduler/adaptive/AdaptiveScheduler.java      | 19 +++++-
 .../DefaultSchedulerBatchSchedulingTest.java       | 19 ------
 .../GloballyTerminalJobStatusListener.java         | 44 ++++++++++++++
 .../scheduler/adaptive/AdaptiveSchedulerTest.java  | 68 ++++++++++++++++------
 4 files changed, 111 insertions(+), 39 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
index 1c5763e..f03e162 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
@@ -112,6 +112,7 @@ import org.apache.flink.util.function.ThrowingConsumer;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
 
 import java.io.IOException;
@@ -123,6 +124,7 @@ import java.util.Iterator;
 import java.util.Map;
 import java.util.Optional;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
 import java.util.concurrent.Executor;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
@@ -730,7 +732,8 @@ public class AdaptiveScheduler
             vertex.setParallelism(parallelismAndResourceAssignments.getParallelism(vertex.getID()));
         }
 
-        final ExecutionGraph executionGraph = createExecutionGraphAndRestoreState(adjustedJobGraph);
+        final ExecutionGraph executionGraph =
+                createExecutionGraphAndRestoreStateAsync(adjustedJobGraph).join();
 
         executionGraph.start(componentMainThreadExecutor);
         executionGraph.transitionToRunning();
@@ -749,6 +752,20 @@ public class AdaptiveScheduler
         return executionGraph;
     }
 
+    private CompletableFuture<ExecutionGraph> createExecutionGraphAndRestoreStateAsync(
+            JobGraph adjustedJobGraph) {
+        return CompletableFuture.supplyAsync(
+                () -> {
+                    try {
+                        return createExecutionGraphAndRestoreState(adjustedJobGraph);
+                    } catch (Exception exception) {
+                        throw new CompletionException(exception);
+                    }
+                },
+                ioExecutor);
+    }
+
+    @Nonnull
     private ExecutionGraph createExecutionGraphAndRestoreState(JobGraph adjustedJobGraph)
             throws Exception {
         ExecutionDeploymentListener executionDeploymentListener =
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerBatchSchedulingTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerBatchSchedulingTest.java
index 34cdfd2..a0c428a 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerBatchSchedulingTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerBatchSchedulingTest.java
@@ -18,7 +18,6 @@
 
 package org.apache.flink.runtime.scheduler;
 
-import org.apache.flink.api.common.JobID;
 import org.apache.flink.api.common.JobStatus;
 import org.apache.flink.api.common.time.Time;
 import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
@@ -189,24 +188,6 @@ public class DefaultSchedulerBatchSchedulingTest extends TestLogger {
         return JobGraphTestUtils.batchJobGraph(jobVertex);
     }
 
-    private static class GloballyTerminalJobStatusListener implements JobStatusListener {
-
-        private final CompletableFuture<JobStatus> globallyTerminalJobStatusFuture =
-                new CompletableFuture<>();
-
-        @Override
-        public void jobStatusChanges(
-                JobID jobId, JobStatus newJobStatus, long timestamp, Throwable error) {
-            if (newJobStatus.isGloballyTerminalState()) {
-                globallyTerminalJobStatusFuture.complete(newJobStatus);
-            }
-        }
-
-        public CompletableFuture<JobStatus> getTerminationFuture() {
-            return globallyTerminalJobStatusFuture;
-        }
-    }
-
     private SchedulerNG createScheduler(
             JobGraph jobGraph,
             ComponentMainThreadExecutor mainThreadExecutor,
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/GloballyTerminalJobStatusListener.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/GloballyTerminalJobStatusListener.java
new file mode 100644
index 0000000..dcc2a1b
--- /dev/null
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/GloballyTerminalJobStatusListener.java
@@ -0,0 +1,44 @@
+/*
+ * 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.flink.runtime.scheduler;
+
+import org.apache.flink.api.common.JobID;
+import org.apache.flink.api.common.JobStatus;
+import org.apache.flink.runtime.executiongraph.JobStatusListener;
+
+import java.util.concurrent.CompletableFuture;
+
+/** {@link JobStatusListener} which records a globally terminal {@link JobStatus}. */
+public class GloballyTerminalJobStatusListener implements JobStatusListener {
+
+    private final CompletableFuture<JobStatus> globallyTerminalJobStatusFuture =
+            new CompletableFuture<>();
+
+    @Override
+    public void jobStatusChanges(
+            JobID jobId, JobStatus newJobStatus, long timestamp, Throwable error) {
+        if (newJobStatus.isGloballyTerminalState()) {
+            globallyTerminalJobStatusFuture.complete(newJobStatus);
+        }
+    }
+
+    public CompletableFuture<JobStatus> getTerminationFuture() {
+        return globallyTerminalJobStatusFuture;
+    }
+}
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
index 4958a37..0489e77 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerTest.java
@@ -35,6 +35,8 @@ import org.apache.flink.runtime.checkpoint.TestingCheckpointIDCounter;
 import org.apache.flink.runtime.checkpoint.TestingCheckpointRecoveryFactory;
 import org.apache.flink.runtime.checkpoint.TestingCompletedCheckpointStore;
 import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
+import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutor;
+import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutorServiceAdapter;
 import org.apache.flink.runtime.concurrent.ManuallyTriggeredComponentMainThreadExecutor;
 import org.apache.flink.runtime.execution.ExecutionState;
 import org.apache.flink.runtime.execution.SuppressRestartsException;
@@ -67,6 +69,7 @@ import org.apache.flink.runtime.operators.coordination.CoordinationRequest;
 import org.apache.flink.runtime.operators.coordination.TaskNotRunningException;
 import org.apache.flink.runtime.operators.coordination.TestOperatorEvent;
 import org.apache.flink.runtime.rest.handler.legacy.utils.ArchivedExecutionGraphBuilder;
+import org.apache.flink.runtime.scheduler.GloballyTerminalJobStatusListener;
 import org.apache.flink.runtime.slots.ResourceRequirement;
 import org.apache.flink.runtime.taskmanager.LocalTaskManagerLocation;
 import org.apache.flink.runtime.taskmanager.TaskExecutionState;
@@ -90,6 +93,8 @@ import java.io.File;
 import java.io.IOException;
 import java.time.Duration;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
@@ -722,25 +727,50 @@ public class AdaptiveSchedulerTest extends TestLogger {
         final DefaultDeclarativeSlotPool declarativeSlotPool =
                 createDeclarativeSlotPool(jobGraphWithNewOperator.getJobID());
 
-        final AdaptiveScheduler adaptiveScheduler =
-                new AdaptiveSchedulerBuilder(jobGraphWithNewOperator, mainThreadExecutor)
-                        .setDeclarativeSlotPool(declarativeSlotPool)
-                        .build();
-
-        adaptiveScheduler.startScheduling();
-
-        offerSlots(
-                declarativeSlotPool,
-                createSlotOffersForResourceRequirements(
-                        ResourceCounter.withResource(ResourceProfile.UNKNOWN, 1)));
-
-        final ArchivedExecutionGraph archivedExecutionGraph =
-                adaptiveScheduler.requestJob().getArchivedExecutionGraph();
-
-        assertThat(archivedExecutionGraph.getState(), is(JobStatus.FAILED));
-        assertThat(
-                archivedExecutionGraph.getFailureInfo().getException(),
-                FlinkMatchers.containsMessage("Failed to rollback to checkpoint/savepoint"));
+        final GloballyTerminalJobStatusListener jobStatusListener =
+                new GloballyTerminalJobStatusListener();
+
+        final ScheduledExecutorService singleThreadExecutor =
+                Executors.newSingleThreadScheduledExecutor();
+
+        try {
+            final ComponentMainThreadExecutor singleMainThreadExecutor =
+                    ComponentMainThreadExecutorServiceAdapter.forSingleThreadExecutor(
+                            singleThreadExecutor);
+            final AdaptiveScheduler adaptiveScheduler =
+                    new AdaptiveSchedulerBuilder(jobGraphWithNewOperator, singleMainThreadExecutor)
+                            .setDeclarativeSlotPool(declarativeSlotPool)
+                            .setJobStatusListener(jobStatusListener)
+                            .build();
+
+            adaptiveScheduler.startScheduling();
+
+            singleMainThreadExecutor.execute(
+                    () ->
+                            offerSlots(
+                                    declarativeSlotPool,
+                                    createSlotOffersForResourceRequirements(
+                                            ResourceCounter.withResource(
+                                                    ResourceProfile.UNKNOWN, 1))));
+
+            assertThat(jobStatusListener.getTerminationFuture().join(), is(JobStatus.FAILED));
+
+            final ArchivedExecutionGraph archivedExecutionGraph =
+                    CompletableFuture.supplyAsync(
+                                    () ->
+                                            adaptiveScheduler
+                                                    .requestJob()
+                                                    .getArchivedExecutionGraph(),
+                                    singleMainThreadExecutor)
+                            .join();
+
+            assertThat(archivedExecutionGraph.getState(), is(JobStatus.FAILED));
+            assertThat(
+                    archivedExecutionGraph.getFailureInfo().getException(),
+                    FlinkMatchers.containsMessage("Failed to rollback to checkpoint/savepoint"));
+        } finally {
+            singleThreadExecutor.shutdownNow();
+        }
     }
 
     @Test

[flink] 07/17: [FLINK-21602] Add DeclarativeSlotPool. and AllocatedSlotPool.containsFreeSlot

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit c7a4203b433267a4fa9c0073e3d61893639b3e3e
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Mon Mar 15 12:12:13 2021 +0100

    [FLINK-21602] Add DeclarativeSlotPool. and AllocatedSlotPool.containsFreeSlot
    
    The newly introduced method containsFreeSlot allows to check whether an assumption that
    a given slot is still free holds true or not. This allows to continue reserving slots
    from the DeclarativeSlotPool or not.
---
 .../jobmaster/slotpool/AllocatedSlotPool.java      | 10 ++++++++
 .../jobmaster/slotpool/DeclarativeSlotPool.java    | 10 ++++++++
 .../slotpool/DefaultAllocatedSlotPool.java         |  5 ++++
 .../slotpool/DefaultDeclarativeSlotPool.java       |  5 ++++
 .../slotpool/DefaultAllocatedSlotPoolTest.java     | 28 ++++++++++++++++++++++
 .../slotpool/TestingDeclarativeSlotPool.java       |  9 +++++++
 .../TestingDeclarativeSlotPoolBuilder.java         |  8 +++++++
 7 files changed, 75 insertions(+)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/AllocatedSlotPool.java b/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/AllocatedSlotPool.java
index 3eed88f..221fa9d 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/AllocatedSlotPool.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/AllocatedSlotPool.java
@@ -74,6 +74,16 @@ public interface AllocatedSlotPool {
     boolean containsSlot(AllocationID allocationId);
 
     /**
+     * Checks whether the slot pool contains a slot with the given {@link AllocationID} and if it is
+     * free.
+     *
+     * @param allocationId allocationId specifies the slot to check for
+     * @return {@code true} if the slot pool contains a free slot registered under the given
+     *     allocation id; otherwise {@code false}
+     */
+    boolean containsFreeSlot(AllocationID allocationId);
+
+    /**
      * Reserves the free slot specified by the given allocationId.
      *
      * @param allocationId allocationId identifying the free slot to reserve
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/DeclarativeSlotPool.java b/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/DeclarativeSlotPool.java
index 752181f..39849bb 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/DeclarativeSlotPool.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/DeclarativeSlotPool.java
@@ -102,6 +102,16 @@ public interface DeclarativeSlotPool {
     Collection<? extends SlotInfo> getAllSlotsInformation();
 
     /**
+     * Checks whether the slot pool contains a slot with the given {@link AllocationID} and if it is
+     * free.
+     *
+     * @param allocationId allocationId specifies the slot to check for
+     * @return {@code true} if the slot pool contains a free slot registered under the given
+     *     allocation id; otherwise {@code false}
+     */
+    boolean containsFreeSlot(AllocationID allocationId);
+
+    /**
      * Reserves the free slot identified by the given allocationId and maps it to the given
      * requiredSlotProfile.
      *
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/DefaultAllocatedSlotPool.java b/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/DefaultAllocatedSlotPool.java
index c188171..a585d6b 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/DefaultAllocatedSlotPool.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/DefaultAllocatedSlotPool.java
@@ -140,6 +140,11 @@ public class DefaultAllocatedSlotPool implements AllocatedSlotPool {
     }
 
     @Override
+    public boolean containsFreeSlot(AllocationID allocationId) {
+        return freeSlotsSince.containsKey(allocationId);
+    }
+
+    @Override
     public AllocatedSlot reserveFreeSlot(AllocationID allocationId) {
         LOG.debug("Reserve free slot with allocation id {}.", allocationId);
         Preconditions.checkState(
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/DefaultDeclarativeSlotPool.java b/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/DefaultDeclarativeSlotPool.java
index 24ad556..65a2f40 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/DefaultDeclarativeSlotPool.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/DefaultDeclarativeSlotPool.java
@@ -478,6 +478,11 @@ public class DefaultDeclarativeSlotPool implements DeclarativeSlotPool {
     }
 
     @Override
+    public boolean containsFreeSlot(AllocationID allocationId) {
+        return slotPool.containsFreeSlot(allocationId);
+    }
+
+    @Override
     public boolean containsSlots(ResourceID owner) {
         return slotPool.containsSlots(owner);
     }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/DefaultAllocatedSlotPoolTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/DefaultAllocatedSlotPoolTest.java
index 548dea0..2407eaa 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/DefaultAllocatedSlotPoolTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/DefaultAllocatedSlotPoolTest.java
@@ -234,6 +234,34 @@ public class DefaultAllocatedSlotPoolTest extends TestLogger {
         slotPool.removeSlots(ResourceID.generate());
     }
 
+    @Test
+    public void testContainsFreeSlotReturnsTrueIfSlotIsFree() {
+        final DefaultAllocatedSlotPool slotPool = new DefaultAllocatedSlotPool();
+        final AllocatedSlot allocatedSlot = createAllocatedSlot(ResourceID.generate());
+
+        slotPool.addSlots(Collections.singleton(allocatedSlot), 0);
+
+        assertTrue(slotPool.containsFreeSlot(allocatedSlot.getAllocationId()));
+    }
+
+    @Test
+    public void testContainsFreeSlotReturnsFalseIfSlotDoesNotExist() {
+        final DefaultAllocatedSlotPool slotPool = new DefaultAllocatedSlotPool();
+
+        assertFalse(slotPool.containsFreeSlot(new AllocationID()));
+    }
+
+    @Test
+    public void testContainsFreeSlotReturnsFalseIfSlotIsReserved() {
+        final DefaultAllocatedSlotPool slotPool = new DefaultAllocatedSlotPool();
+        final AllocatedSlot allocatedSlot = createAllocatedSlot(ResourceID.generate());
+
+        slotPool.addSlots(Collections.singleton(allocatedSlot), 0);
+        slotPool.reserveFreeSlot(allocatedSlot.getAllocationId());
+
+        assertFalse(slotPool.containsFreeSlot(allocatedSlot.getAllocationId()));
+    }
+
     private void assertSlotPoolContainsSlots(
             DefaultAllocatedSlotPool slotPool, Collection<AllocatedSlot> slots) {
         assertThat(slotPool.getAllSlotsInformation(), hasSize(slots.size()));
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/TestingDeclarativeSlotPool.java b/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/TestingDeclarativeSlotPool.java
index 40a5687..a22a877 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/TestingDeclarativeSlotPool.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/TestingDeclarativeSlotPool.java
@@ -71,6 +71,8 @@ final class TestingDeclarativeSlotPool implements DeclarativeSlotPool {
 
     private final Function<ResourceID, Boolean> containsSlotsFunction;
 
+    private final Function<AllocationID, Boolean> containsFreeSlotFunction;
+
     private final LongConsumer releaseIdleSlotsConsumer;
 
     private final Consumer<ResourceCounter> setResourceRequirementsConsumer;
@@ -93,6 +95,7 @@ final class TestingDeclarativeSlotPool implements DeclarativeSlotPool {
             BiFunction<AllocationID, ResourceProfile, PhysicalSlot> reserveFreeSlotFunction,
             TriFunction<AllocationID, Throwable, Long, ResourceCounter> freeReservedSlotFunction,
             Function<ResourceID, Boolean> containsSlotsFunction,
+            Function<AllocationID, Boolean> containsFreeSlotFunction,
             LongConsumer releaseIdleSlotsConsumer,
             Consumer<ResourceCounter> setResourceRequirementsConsumer) {
         this.increaseResourceRequirementsByConsumer = increaseResourceRequirementsByConsumer;
@@ -106,6 +109,7 @@ final class TestingDeclarativeSlotPool implements DeclarativeSlotPool {
         this.reserveFreeSlotFunction = reserveFreeSlotFunction;
         this.freeReservedSlotFunction = freeReservedSlotFunction;
         this.containsSlotsFunction = containsSlotsFunction;
+        this.containsFreeSlotFunction = containsFreeSlotFunction;
         this.releaseIdleSlotsConsumer = releaseIdleSlotsConsumer;
         this.setResourceRequirementsConsumer = setResourceRequirementsConsumer;
     }
@@ -151,6 +155,11 @@ final class TestingDeclarativeSlotPool implements DeclarativeSlotPool {
     }
 
     @Override
+    public boolean containsFreeSlot(AllocationID allocationId) {
+        return containsFreeSlotFunction.apply(allocationId);
+    }
+
+    @Override
     public ResourceCounter releaseSlots(ResourceID owner, Exception cause) {
         return releaseSlotsFunction.apply(owner, cause);
     }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/TestingDeclarativeSlotPoolBuilder.java b/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/TestingDeclarativeSlotPoolBuilder.java
index 7982858..e2ecb34 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/TestingDeclarativeSlotPoolBuilder.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/TestingDeclarativeSlotPoolBuilder.java
@@ -68,6 +68,7 @@ public class TestingDeclarativeSlotPoolBuilder {
     private Function<ResourceID, Boolean> containsSlotsFunction = ignored -> false;
     private LongConsumer returnIdleSlotsConsumer = ignored -> {};
     private Consumer<ResourceCounter> setResourceRequirementsConsumer = ignored -> {};
+    private Function<AllocationID, Boolean> containsFreeSlotFunction = ignored -> false;
 
     public TestingDeclarativeSlotPoolBuilder setIncreaseResourceRequirementsByConsumer(
             Consumer<ResourceCounter> increaseResourceRequirementsByConsumer) {
@@ -148,6 +149,12 @@ public class TestingDeclarativeSlotPoolBuilder {
         return this;
     }
 
+    public TestingDeclarativeSlotPoolBuilder setContainsFreeSlotFunction(
+            Function<AllocationID, Boolean> containsFreeSlotFunction) {
+        this.containsFreeSlotFunction = containsFreeSlotFunction;
+        return this;
+    }
+
     public TestingDeclarativeSlotPoolBuilder setReturnIdleSlotsConsumer(
             LongConsumer returnIdleSlotsConsumer) {
         this.returnIdleSlotsConsumer = returnIdleSlotsConsumer;
@@ -167,6 +174,7 @@ public class TestingDeclarativeSlotPoolBuilder {
                 reserveFreeSlotFunction,
                 freeReservedSlotFunction,
                 containsSlotsFunction,
+                containsFreeSlotFunction,
                 returnIdleSlotsConsumer,
                 setResourceRequirementsConsumer);
     }

[flink] 08/17: [FLINK-21602] Let SlotSharingSlotAllocator check whether resources are available before reserving them

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit ce55b21d53c29e37523c82ee001f4ecf968ad84e
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Mon Mar 15 17:23:27 2021 +0100

    [FLINK-21602] Let SlotSharingSlotAllocator check whether resources are available before reserving them
    
    The SlotSharingSlotAllocator.tryReserve now checks whether the expected set of resources is still available
    before reserving slots. If the resources are no longer available, then tryReserve will return Optional.empty().
---
 .../scheduler/adaptive/AdaptiveScheduler.java      |  3 +-
 .../allocator/IsSlotAvailableAndFreeFunction.java  | 35 ++++++++++++
 .../allocator/SlotSharingSlotAllocator.java        | 62 +++++++++++++++++-----
 .../allocator/SlotSharingSlotAllocatorTest.java    | 48 ++++++++++++++---
 4 files changed, 128 insertions(+), 20 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
index 9b6799d..c1d0caa 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
@@ -257,7 +257,8 @@ public class AdaptiveScheduler
         this.slotAllocator =
                 new SlotSharingSlotAllocator(
                         declarativeSlotPool::reserveFreeSlot,
-                        declarativeSlotPool::freeReservedSlot);
+                        declarativeSlotPool::freeReservedSlot,
+                        declarativeSlotPool::containsFreeSlot);
 
         declarativeSlotPool.registerNewSlotsListener(this::newResourcesAvailable);
 
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/IsSlotAvailableAndFreeFunction.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/IsSlotAvailableAndFreeFunction.java
new file mode 100644
index 0000000..4bb5538
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/IsSlotAvailableAndFreeFunction.java
@@ -0,0 +1,35 @@
+/*
+ * 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.flink.runtime.scheduler.adaptive.allocator;
+
+import org.apache.flink.runtime.clusterframework.types.AllocationID;
+
+/** Functional interface for checking whether a slot is available and free. */
+@FunctionalInterface
+public interface IsSlotAvailableAndFreeFunction {
+
+    /**
+     * Returns {@code true} if a slot with the given {@link AllocationID} is available and free.
+     *
+     * @param allocationId allocationId specifies the slot to check
+     * @return {@code true} if a slot with the given allocationId is available and free; otherwise
+     *     {@code false}
+     */
+    boolean isSlotAvailableAndFree(AllocationID allocationId);
+}
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
index da5f7a3..fc72a45 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
@@ -17,6 +17,7 @@
 
 package org.apache.flink.runtime.scheduler.adaptive.allocator;
 
+import org.apache.flink.runtime.clusterframework.types.AllocationID;
 import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
 import org.apache.flink.runtime.instance.SlotSharingGroupId;
 import org.apache.flink.runtime.jobgraph.JobVertexID;
@@ -29,6 +30,8 @@ import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
 import org.apache.flink.runtime.util.ResourceCounter;
 import org.apache.flink.util.Preconditions;
 
+import javax.annotation.Nonnull;
+
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
@@ -45,11 +48,15 @@ public class SlotSharingSlotAllocator implements SlotAllocator {
 
     private final ReserveSlotFunction reserveSlotFunction;
     private final FreeSlotFunction freeSlotFunction;
+    private final IsSlotAvailableAndFreeFunction isSlotAvailableAndFreeFunction;
 
     public SlotSharingSlotAllocator(
-            ReserveSlotFunction reserveSlot, FreeSlotFunction freeSlotFunction) {
+            ReserveSlotFunction reserveSlot,
+            FreeSlotFunction freeSlotFunction,
+            IsSlotAvailableAndFreeFunction isSlotAvailableAndFreeFunction) {
         this.reserveSlotFunction = reserveSlot;
         this.freeSlotFunction = freeSlotFunction;
+        this.isSlotAvailableAndFreeFunction = isSlotAvailableAndFreeFunction;
     }
 
     @Override
@@ -159,23 +166,52 @@ public class SlotSharingSlotAllocator implements SlotAllocator {
         final VertexParallelismWithSlotSharing vertexParallelismWithSlotSharing =
                 (VertexParallelismWithSlotSharing) vertexParallelism;
 
-        final Map<ExecutionVertexID, LogicalSlot> assignedSlots = new HashMap<>();
+        final Collection<AllocationID> expectedSlots =
+                calculateExpectedSlots(vertexParallelismWithSlotSharing.getAssignments());
+
+        if (areAllExpectedSlotsAvailableAndFree(expectedSlots)) {
+            final Map<ExecutionVertexID, LogicalSlot> assignedSlots = new HashMap<>();
+
+            for (ExecutionSlotSharingGroupAndSlot executionSlotSharingGroup :
+                    vertexParallelismWithSlotSharing.getAssignments()) {
+                final SharedSlot sharedSlot =
+                        reserveSharedSlot(executionSlotSharingGroup.getSlotInfo());
+
+                for (ExecutionVertexID executionVertexId :
+                        executionSlotSharingGroup
+                                .getExecutionSlotSharingGroup()
+                                .getContainedExecutionVertices()) {
+                    final LogicalSlot logicalSlot = sharedSlot.allocateLogicalSlot();
+                    assignedSlots.put(executionVertexId, logicalSlot);
+                }
+            }
+
+            return Optional.of(ReservedSlots.create(assignedSlots));
+        } else {
+            return Optional.empty();
+        }
+    }
 
-        for (ExecutionSlotSharingGroupAndSlot executionSlotSharingGroup :
-                vertexParallelismWithSlotSharing.getAssignments()) {
-            final SharedSlot sharedSlot =
-                    reserveSharedSlot(executionSlotSharingGroup.getSlotInfo());
+    @Nonnull
+    private Collection<AllocationID> calculateExpectedSlots(
+            Iterable<? extends ExecutionSlotSharingGroupAndSlot> assignments) {
+        final Collection<AllocationID> requiredSlots = new ArrayList<>();
+
+        for (ExecutionSlotSharingGroupAndSlot assignment : assignments) {
+            requiredSlots.add(assignment.getSlotInfo().getAllocationId());
+        }
+        return requiredSlots;
+    }
 
-            for (ExecutionVertexID executionVertexId :
-                    executionSlotSharingGroup
-                            .getExecutionSlotSharingGroup()
-                            .getContainedExecutionVertices()) {
-                final LogicalSlot logicalSlot = sharedSlot.allocateLogicalSlot();
-                assignedSlots.put(executionVertexId, logicalSlot);
+    private boolean areAllExpectedSlotsAvailableAndFree(
+            Iterable<? extends AllocationID> requiredSlots) {
+        for (AllocationID requiredSlot : requiredSlots) {
+            if (!isSlotAvailableAndFreeFunction.isSlotAvailableAndFree(requiredSlot)) {
+                return false;
             }
         }
 
-        return Optional.of(ReservedSlots.create(assignedSlots));
+        return true;
     }
 
     private SharedSlot reserveSharedSlot(SlotInfo slotInfo) {
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocatorTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocatorTest.java
index b0e3716..22b8ddd 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocatorTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocatorTest.java
@@ -40,6 +40,7 @@ import java.util.stream.Collectors;
 
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.Matchers.contains;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertThat;
 
 /** Tests for the {@link SlotSharingSlotAllocator}. */
@@ -52,6 +53,8 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
                             .withAllocationID(allocationId)
                             .withResourceProfile(resourceProfile)
                             .build();
+    private static final IsSlotAvailableAndFreeFunction TEST_IS_SLOT_FREE_FUNCTION =
+            ignored -> true;
 
     private static final SlotSharingGroup slotSharingGroup1 = new SlotSharingGroup();
     private static final SlotSharingGroup slotSharingGroup2 = new SlotSharingGroup();
@@ -65,7 +68,10 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
     @Test
     public void testCalculateRequiredSlots() {
         final SlotSharingSlotAllocator slotAllocator =
-                new SlotSharingSlotAllocator(TEST_RESERVE_SLOT_FUNCTION, TEST_FREE_SLOT_FUNCTION);
+                new SlotSharingSlotAllocator(
+                        TEST_RESERVE_SLOT_FUNCTION,
+                        TEST_FREE_SLOT_FUNCTION,
+                        TEST_IS_SLOT_FREE_FUNCTION);
 
         final ResourceCounter resourceCounter =
                 slotAllocator.calculateRequiredSlots(Arrays.asList(vertex1, vertex2, vertex3));
@@ -81,7 +87,10 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
     @Test
     public void testDetermineParallelismWithMinimumSlots() {
         final SlotSharingSlotAllocator slotAllocator =
-                new SlotSharingSlotAllocator(TEST_RESERVE_SLOT_FUNCTION, TEST_FREE_SLOT_FUNCTION);
+                new SlotSharingSlotAllocator(
+                        TEST_RESERVE_SLOT_FUNCTION,
+                        TEST_FREE_SLOT_FUNCTION,
+                        TEST_IS_SLOT_FREE_FUNCTION);
 
         final JobInformation jobInformation =
                 new TestJobInformation(Arrays.asList(vertex1, vertex2, vertex3));
@@ -100,7 +109,10 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
     @Test
     public void testDetermineParallelismWithManySlots() {
         final SlotSharingSlotAllocator slotAllocator =
-                new SlotSharingSlotAllocator(TEST_RESERVE_SLOT_FUNCTION, TEST_FREE_SLOT_FUNCTION);
+                new SlotSharingSlotAllocator(
+                        TEST_RESERVE_SLOT_FUNCTION,
+                        TEST_FREE_SLOT_FUNCTION,
+                        TEST_IS_SLOT_FREE_FUNCTION);
 
         final JobInformation jobInformation =
                 new TestJobInformation(Arrays.asList(vertex1, vertex2, vertex3));
@@ -125,7 +137,10 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
     @Test
     public void testDetermineParallelismUnsuccessfulWithLessSlotsThanSlotSharingGroups() {
         final SlotSharingSlotAllocator slotAllocator =
-                new SlotSharingSlotAllocator(TEST_RESERVE_SLOT_FUNCTION, TEST_FREE_SLOT_FUNCTION);
+                new SlotSharingSlotAllocator(
+                        TEST_RESERVE_SLOT_FUNCTION,
+                        TEST_FREE_SLOT_FUNCTION,
+                        TEST_IS_SLOT_FREE_FUNCTION);
 
         final JobInformation jobInformation =
                 new TestJobInformation(Arrays.asList(vertex1, vertex2, vertex3));
@@ -137,9 +152,12 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
     }
 
     @Test
-    public void testReserveResources() {
+    public void testReserveAvailableResources() {
         final SlotSharingSlotAllocator slotAllocator =
-                new SlotSharingSlotAllocator(TEST_RESERVE_SLOT_FUNCTION, TEST_FREE_SLOT_FUNCTION);
+                new SlotSharingSlotAllocator(
+                        TEST_RESERVE_SLOT_FUNCTION,
+                        TEST_FREE_SLOT_FUNCTION,
+                        TEST_IS_SLOT_FREE_FUNCTION);
 
         final JobInformation jobInformation =
                 new TestJobInformation(Arrays.asList(vertex1, vertex2, vertex3));
@@ -172,6 +190,24 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
         }
     }
 
+    @Test
+    public void testReserveUnavailableResources() {
+        final SlotSharingSlotAllocator slotSharingSlotAllocator =
+                new SlotSharingSlotAllocator(
+                        TEST_RESERVE_SLOT_FUNCTION, TEST_FREE_SLOT_FUNCTION, ignored -> false);
+
+        final JobInformation jobInformation =
+                new TestJobInformation(Arrays.asList(vertex1, vertex2, vertex3));
+
+        final VertexParallelismWithSlotSharing slotAssignments =
+                slotSharingSlotAllocator.determineParallelism(jobInformation, getSlots(50)).get();
+
+        final Optional<? extends ReservedSlots> reservedSlots =
+                slotSharingSlotAllocator.tryReserveResources(slotAssignments);
+
+        assertFalse(reservedSlots.isPresent());
+    }
+
     private static Collection<SlotInfo> getSlots(int count) {
         final Collection<SlotInfo> slotInfo = new ArrayList<>();
         for (int i = 0; i < count; i++) {

[flink] 16/17: [hotfix] Add FutureUtils.switchExecutor utility

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit d6750d66bd6a6116d3fc13f90f7a7e19ac232235
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Wed Mar 17 11:39:04 2021 +0100

    [hotfix] Add FutureUtils.switchExecutor utility
    
    The FutureUtils.switchExecutor utility allows to switch the executor for a given
    CompletableFuture independent of whether it is completed normally or exceptionally.
---
 .../flink/runtime/concurrent/FutureUtils.java      | 22 +++++++
 .../flink/runtime/concurrent/FutureUtilsTest.java  | 67 +++++++++++++++++++++-
 2 files changed, 86 insertions(+), 3 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/FutureUtils.java b/flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/FutureUtils.java
index 629c144..4334eda 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/FutureUtils.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/FutureUtils.java
@@ -1344,4 +1344,26 @@ public class FutureUtils {
             }
         };
     }
+
+    /**
+     * Switches the execution context of the given source future. This works for normally and
+     * exceptionally completed futures.
+     *
+     * @param source source to switch the execution context for
+     * @param executor executor representing the new execution context
+     * @param <T> type of the source
+     * @return future which is executed by the given executor
+     */
+    public static <T> CompletableFuture<T> switchExecutor(
+            CompletableFuture<? extends T> source, Executor executor) {
+        return source.handleAsync(
+                (t, throwable) -> {
+                    if (throwable != null) {
+                        throw new CompletionException(throwable);
+                    } else {
+                        return t;
+                    }
+                },
+                executor);
+    }
 }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/concurrent/FutureUtilsTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/concurrent/FutureUtilsTest.java
index 63f221f..5d5389c 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/concurrent/FutureUtilsTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/concurrent/FutureUtilsTest.java
@@ -23,12 +23,14 @@ import org.apache.flink.core.testutils.FlinkMatchers;
 import org.apache.flink.core.testutils.OneShotLatch;
 import org.apache.flink.runtime.messages.Acknowledge;
 import org.apache.flink.runtime.testingUtils.TestingUtils;
+import org.apache.flink.testutils.executor.TestExecutorResource;
 import org.apache.flink.util.ExceptionUtils;
 import org.apache.flink.util.FlinkException;
 import org.apache.flink.util.FlinkRuntimeException;
 import org.apache.flink.util.TestLogger;
 
 import org.junit.Assert;
+import org.junit.ClassRule;
 import org.junit.Test;
 
 import java.time.Duration;
@@ -39,6 +41,7 @@ import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.CompletionException;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
@@ -67,6 +70,10 @@ import static org.junit.Assert.fail;
 /** Tests for the utility methods in {@link FutureUtils}. */
 public class FutureUtilsTest extends TestLogger {
 
+    @ClassRule
+    public static final TestExecutorResource<ScheduledExecutorService> TEST_EXECUTOR_RESOURCE =
+            new TestExecutorResource<>(Executors::newSingleThreadScheduledExecutor);
+
     /** Tests that we can retry an operation. */
     @Test
     public void testRetrySuccess() throws Exception {
@@ -409,7 +416,7 @@ public class FutureUtilsTest extends TestLogger {
 
     @Test
     public void testRetryWithDelayAndPredicate() throws Exception {
-        final ScheduledExecutorService retryExecutor = Executors.newSingleThreadScheduledExecutor();
+        final ScheduledExecutorService retryExecutor = TEST_EXECUTOR_RESOURCE.getExecutor();
         final String retryableExceptionMessage = "first exception";
         class TestStringSupplier implements Supplier<CompletableFuture<String>> {
             private final AtomicInteger counter = new AtomicInteger();
@@ -440,8 +447,6 @@ public class FutureUtilsTest extends TestLogger {
                     .get();
         } catch (final ExecutionException e) {
             assertThat(e.getMessage(), containsString("should propagate"));
-        } finally {
-            retryExecutor.shutdownNow();
         }
     }
 
@@ -953,6 +958,62 @@ public class FutureUtilsTest extends TestLogger {
         assertNull(FutureUtils.getWithoutException(completableFuture));
     }
 
+    @Test
+    public void testSwitchExecutorForNormallyCompletedFuture() {
+        final CompletableFuture<String> source = new CompletableFuture<>();
+
+        final ExecutorService singleThreadExecutor = TEST_EXECUTOR_RESOURCE.getExecutor();
+
+        final CompletableFuture<String> resultFuture =
+                FutureUtils.switchExecutor(source, singleThreadExecutor);
+
+        final String expectedThreadName =
+                FutureUtils.supplyAsync(
+                                () -> Thread.currentThread().getName(), singleThreadExecutor)
+                        .join();
+        final String expectedValue = "foobar";
+
+        final CompletableFuture<Void> assertionFuture =
+                resultFuture.handle(
+                        (s, throwable) -> {
+                            assertThat(s, is(expectedValue));
+                            assertThat(Thread.currentThread().getName(), is(expectedThreadName));
+
+                            return null;
+                        });
+        source.complete(expectedValue);
+
+        assertionFuture.join();
+    }
+
+    @Test
+    public void testSwitchExecutorForExceptionallyCompletedFuture() {
+        final CompletableFuture<String> source = new CompletableFuture<>();
+
+        final ExecutorService singleThreadExecutor = TEST_EXECUTOR_RESOURCE.getExecutor();
+
+        final CompletableFuture<String> resultFuture =
+                FutureUtils.switchExecutor(source, singleThreadExecutor);
+
+        final String expectedThreadName =
+                FutureUtils.supplyAsync(
+                                () -> Thread.currentThread().getName(), singleThreadExecutor)
+                        .join();
+        final Exception expectedException = new Exception("foobar");
+
+        final CompletableFuture<Void> assertionFuture =
+                resultFuture.handle(
+                        (s, throwable) -> {
+                            assertThat(throwable, FlinkMatchers.containsCause(expectedException));
+                            assertThat(Thread.currentThread().getName(), is(expectedThreadName));
+
+                            return null;
+                        });
+        source.completeExceptionally(expectedException);
+
+        assertionFuture.join();
+    }
+
     private static Throwable getThrowable(CompletableFuture<?> completableFuture) {
         try {
             completableFuture.join();

[flink] 06/17: [FLINK-21602] Make SlotAllocator.tryReserveSlots failable

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 2f4813d77ade0544c39d8d9edd58606d3b21bc7b
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Sun Mar 14 17:58:08 2021 +0100

    [FLINK-21602] Make SlotAllocator.tryReserveSlots failable
    
    In order to prepare the SlotAllocator to support failing SlotAllocator.tryReserveSlots
    calls, this commit changes its return type to Optional<? extends ReservedSlots>.
---
 .../scheduler/adaptive/AdaptiveScheduler.java      | 15 +++++---
 .../ParallelismAndResourceAssignments.java         | 11 +++---
 .../adaptive/allocator/ReservedSlots.java          | 42 ++++++++++++++++++++++
 .../adaptive/allocator/SlotAllocator.java          | 18 ++++------
 .../allocator/SlotSharingSlotAllocator.java        |  5 ++-
 .../adaptive/allocator/VertexParallelism.java      |  2 +-
 .../allocator/SlotSharingSlotAllocatorTest.java    |  9 +++--
 7 files changed, 73 insertions(+), 29 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
index f420ce5..9b6799d 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
@@ -94,12 +94,12 @@ import org.apache.flink.runtime.scheduler.OperatorCoordinatorHandler;
 import org.apache.flink.runtime.scheduler.SchedulerNG;
 import org.apache.flink.runtime.scheduler.SchedulerUtils;
 import org.apache.flink.runtime.scheduler.UpdateSchedulerNgOnInternalFailuresListener;
+import org.apache.flink.runtime.scheduler.adaptive.allocator.ReservedSlots;
 import org.apache.flink.runtime.scheduler.adaptive.allocator.SlotAllocator;
 import org.apache.flink.runtime.scheduler.adaptive.allocator.SlotSharingSlotAllocator;
 import org.apache.flink.runtime.scheduler.adaptive.allocator.VertexParallelism;
 import org.apache.flink.runtime.scheduler.adaptive.scalingpolicy.ReactiveScaleUpController;
 import org.apache.flink.runtime.scheduler.adaptive.scalingpolicy.ScaleUpController;
-import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
 import org.apache.flink.runtime.shuffle.ShuffleMaster;
 import org.apache.flink.runtime.state.KeyGroupRange;
 import org.apache.flink.runtime.util.ResourceCounter;
@@ -121,7 +121,6 @@ import java.time.Duration;
 import java.util.Collection;
 import java.util.HashSet;
 import java.util.Iterator;
-import java.util.Map;
 import java.util.Optional;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.CompletionException;
@@ -594,11 +593,17 @@ public class AdaptiveScheduler
                                                 jobInformation.getJobID(),
                                                 "Not enough resources available for scheduling."));
 
-        final Map<ExecutionVertexID, LogicalSlot> slotAssignments =
-                slotAllocator.reserveResources(vertexParallelism);
+        final ReservedSlots reservedSlots =
+                slotAllocator
+                        .tryReserveResources(vertexParallelism)
+                        .orElseThrow(
+                                () ->
+                                        new JobExecutionException(
+                                                jobInformation.getJobID(),
+                                                "Could not reserve all required slots."));
 
         return new ParallelismAndResourceAssignments(
-                slotAssignments, vertexParallelism.getMaxParallelismForVertices());
+                reservedSlots, vertexParallelism.getMaxParallelismForVertices());
     }
 
     @Override
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/ParallelismAndResourceAssignments.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/ParallelismAndResourceAssignments.java
index 3c4b2dd..febf3aa 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/ParallelismAndResourceAssignments.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/ParallelismAndResourceAssignments.java
@@ -20,6 +20,7 @@ package org.apache.flink.runtime.scheduler.adaptive;
 
 import org.apache.flink.runtime.jobgraph.JobVertexID;
 import org.apache.flink.runtime.jobmaster.LogicalSlot;
+import org.apache.flink.runtime.scheduler.adaptive.allocator.ReservedSlots;
 import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
 import org.apache.flink.util.Preconditions;
 
@@ -27,14 +28,13 @@ import java.util.Map;
 
 /** Assignment of slots to execution vertices. */
 public final class ParallelismAndResourceAssignments {
-    private final Map<ExecutionVertexID, ? extends LogicalSlot> assignedSlots;
+    private final ReservedSlots reservedSlots;
 
     private final Map<JobVertexID, Integer> parallelismPerJobVertex;
 
     public ParallelismAndResourceAssignments(
-            Map<ExecutionVertexID, ? extends LogicalSlot> assignedSlots,
-            Map<JobVertexID, Integer> parallelismPerJobVertex) {
-        this.assignedSlots = assignedSlots;
+            ReservedSlots reservedSlots, Map<JobVertexID, Integer> parallelismPerJobVertex) {
+        this.reservedSlots = reservedSlots;
         this.parallelismPerJobVertex = parallelismPerJobVertex;
     }
 
@@ -44,7 +44,6 @@ public final class ParallelismAndResourceAssignments {
     }
 
     public LogicalSlot getAssignedSlot(ExecutionVertexID executionVertexId) {
-        Preconditions.checkState(assignedSlots.containsKey(executionVertexId));
-        return assignedSlots.get(executionVertexId);
+        return reservedSlots.getSlotFor(executionVertexId);
     }
 }
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/ReservedSlots.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/ReservedSlots.java
new file mode 100644
index 0000000..0bb9bbd
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/ReservedSlots.java
@@ -0,0 +1,42 @@
+/*
+ * 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.flink.runtime.scheduler.adaptive.allocator;
+
+import org.apache.flink.runtime.jobmaster.LogicalSlot;
+import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
+import org.apache.flink.util.Preconditions;
+
+import java.util.Map;
+
+/** Container for the set of reserved slots for {@link ExecutionVertexID}. */
+public final class ReservedSlots {
+    private final Map<ExecutionVertexID, LogicalSlot> slotPerExecutionVertex;
+
+    private ReservedSlots(Map<ExecutionVertexID, LogicalSlot> slotPerExecutionVertex) {
+        this.slotPerExecutionVertex = slotPerExecutionVertex;
+    }
+
+    public LogicalSlot getSlotFor(ExecutionVertexID executionVertexId) {
+        return Preconditions.checkNotNull(slotPerExecutionVertex.get(executionVertexId));
+    }
+
+    public static ReservedSlots create(Map<ExecutionVertexID, LogicalSlot> assignedSlots) {
+        return new ReservedSlots(assignedSlots);
+    }
+}
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotAllocator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotAllocator.java
index 2519db8..9112b52 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotAllocator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotAllocator.java
@@ -17,13 +17,10 @@
 
 package org.apache.flink.runtime.scheduler.adaptive.allocator;
 
-import org.apache.flink.runtime.jobmaster.LogicalSlot;
 import org.apache.flink.runtime.jobmaster.SlotInfo;
-import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
 import org.apache.flink.runtime.util.ResourceCounter;
 
 import java.util.Collection;
-import java.util.Map;
 import java.util.Optional;
 
 /** Component for calculating the slot requirements and mapping of vertices to slots. */
@@ -45,12 +42,8 @@ public interface SlotAllocator {
      * <p>If a {@link VertexParallelism} is returned then it covers all vertices contained in the
      * given job information.
      *
-     * <p>A returned {@link VertexParallelism} should be directly consumed afterwards (by either
-     * discarding it or calling {@link #reserveResources(VertexParallelism)}, as there is no
-     * guarantee that the assignment remains valid over time (because slots can be lost).
-     *
      * <p>Implementations of this method must be side-effect free. There is no guarantee that the
-     * result of this method is ever passed to {@link #reserveResources(VertexParallelism)}.
+     * result of this method is ever passed to {@link #tryReserveResources(VertexParallelism)}.
      *
      * @param jobInformation information about the job graph
      * @param slots slots to consider for determining the parallelism
@@ -62,10 +55,13 @@ public interface SlotAllocator {
             JobInformation jobInformation, Collection<? extends SlotInfo> slots);
 
     /**
-     * Reserves slots according to the given assignment.
+     * Reserves slots according to the given assignment if possible. If the underlying set of
+     * resources has changed and the reservation with respect to vertexParallelism is no longer
+     * possible, then this method returns {@link Optional#empty()}.
      *
      * @param vertexParallelism information on how slots should be assigned to the slots
-     * @return mapping of vertices to slots
+     * @return Set of reserved slots if the reservation was successful; otherwise {@link
+     *     Optional#empty()}
      */
-    Map<ExecutionVertexID, LogicalSlot> reserveResources(VertexParallelism vertexParallelism);
+    Optional<ReservedSlots> tryReserveResources(VertexParallelism vertexParallelism);
 }
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
index 26853cf..da5f7a3 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
@@ -148,8 +148,7 @@ public class SlotSharingSlotAllocator implements SlotAllocator {
     }
 
     @Override
-    public Map<ExecutionVertexID, LogicalSlot> reserveResources(
-            VertexParallelism vertexParallelism) {
+    public Optional<ReservedSlots> tryReserveResources(VertexParallelism vertexParallelism) {
         Preconditions.checkArgument(
                 vertexParallelism instanceof VertexParallelismWithSlotSharing,
                 String.format(
@@ -176,7 +175,7 @@ public class SlotSharingSlotAllocator implements SlotAllocator {
             }
         }
 
-        return assignedSlots;
+        return Optional.of(ReservedSlots.create(assignedSlots));
     }
 
     private SharedSlot reserveSharedSlot(SlotInfo slotInfo) {
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/VertexParallelism.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/VertexParallelism.java
index 99e8fd6..d4be287 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/VertexParallelism.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/VertexParallelism.java
@@ -27,7 +27,7 @@ import java.util.Map;
  * the parallelism each vertex could be scheduled with.
  *
  * <p>{@link SlotAllocator} implementations may encode additional information to be used in {@link
- * SlotAllocator#reserveResources(VertexParallelism)}.
+ * SlotAllocator#tryReserveResources(VertexParallelism)}.
  */
 public interface VertexParallelism {
     Map<JobVertexID, Integer> getMaxParallelismForVertices();
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocatorTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocatorTest.java
index 80c0618..b0e3716 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocatorTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocatorTest.java
@@ -147,8 +147,11 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
         final VertexParallelismWithSlotSharing slotAssignments =
                 slotAllocator.determineParallelism(jobInformation, getSlots(50)).get();
 
-        final Map<ExecutionVertexID, LogicalSlot> assignedResources =
-                slotAllocator.reserveResources(slotAssignments);
+        final ReservedSlots reservedSlots =
+                slotAllocator
+                        .tryReserveResources(slotAssignments)
+                        .orElseThrow(
+                                () -> new RuntimeException("Expected that reservation succeeds."));
 
         final Map<ExecutionVertexID, SlotInfo> expectedAssignments = new HashMap<>();
         for (SlotSharingSlotAllocator.ExecutionSlotSharingGroupAndSlot assignment :
@@ -161,7 +164,7 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
 
         for (Map.Entry<ExecutionVertexID, SlotInfo> expectedAssignment :
                 expectedAssignments.entrySet()) {
-            final LogicalSlot assignedSlot = assignedResources.get(expectedAssignment.getKey());
+            final LogicalSlot assignedSlot = reservedSlots.getSlotFor(expectedAssignment.getKey());
 
             final SlotInfo backingSlot = expectedAssignment.getValue();
 

[flink] 10/17: [hotfix] Make SlotAllocator configurable for the AdaptiveScheduler

Posted by tr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 08094878252304c41c964eb90876d2e5b45e7515
Author: Till Rohrmann <tr...@apache.org>
AuthorDate: Tue Mar 16 10:52:40 2021 +0100

    [hotfix] Make SlotAllocator configurable for the AdaptiveScheduler
---
 .../runtime/scheduler/adaptive/AdaptiveScheduler.java      |  8 ++------
 .../scheduler/adaptive/AdaptiveSchedulerFactory.java       | 13 +++++++++++++
 .../adaptive/allocator/SlotSharingSlotAllocator.java       | 10 +++++++++-
 .../scheduler/adaptive/AdaptiveSchedulerBuilder.java       | 14 ++++++++++++++
 .../adaptive/allocator/SlotSharingSlotAllocatorTest.java   | 12 ++++++------
 5 files changed, 44 insertions(+), 13 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
index c1d0caa..3bac7a0 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveScheduler.java
@@ -96,7 +96,6 @@ import org.apache.flink.runtime.scheduler.SchedulerUtils;
 import org.apache.flink.runtime.scheduler.UpdateSchedulerNgOnInternalFailuresListener;
 import org.apache.flink.runtime.scheduler.adaptive.allocator.ReservedSlots;
 import org.apache.flink.runtime.scheduler.adaptive.allocator.SlotAllocator;
-import org.apache.flink.runtime.scheduler.adaptive.allocator.SlotSharingSlotAllocator;
 import org.apache.flink.runtime.scheduler.adaptive.allocator.VertexParallelism;
 import org.apache.flink.runtime.scheduler.adaptive.scalingpolicy.ReactiveScaleUpController;
 import org.apache.flink.runtime.scheduler.adaptive.scalingpolicy.ScaleUpController;
@@ -208,6 +207,7 @@ public class AdaptiveScheduler
             JobGraph jobGraph,
             Configuration configuration,
             DeclarativeSlotPool declarativeSlotPool,
+            SlotAllocator slotAllocator,
             ScheduledExecutorService futureExecutor,
             Executor ioExecutor,
             ClassLoader userCodeClassLoader,
@@ -254,11 +254,7 @@ public class AdaptiveScheduler
                         jobGraph, checkpointRecoveryFactory);
         this.checkpointsCleaner = new CheckpointsCleaner();
 
-        this.slotAllocator =
-                new SlotSharingSlotAllocator(
-                        declarativeSlotPool::reserveFreeSlot,
-                        declarativeSlotPool::freeReservedSlot,
-                        declarativeSlotPool::containsFreeSlot);
+        this.slotAllocator = slotAllocator;
 
         declarativeSlotPool.registerNewSlotsListener(this::newResourcesAvailable);
 
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerFactory.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerFactory.java
index c7eaf40..278baa0 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerFactory.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerFactory.java
@@ -36,6 +36,7 @@ import org.apache.flink.runtime.metrics.groups.JobManagerJobMetricGroup;
 import org.apache.flink.runtime.rpc.FatalErrorHandler;
 import org.apache.flink.runtime.scheduler.SchedulerNG;
 import org.apache.flink.runtime.scheduler.SchedulerNGFactory;
+import org.apache.flink.runtime.scheduler.adaptive.allocator.SlotSharingSlotAllocator;
 import org.apache.flink.runtime.shuffle.ShuffleMaster;
 
 import org.slf4j.Logger;
@@ -88,10 +89,14 @@ public class AdaptiveSchedulerFactory implements SchedulerNGFactory {
                 jobGraph.getName(),
                 jobGraph.getJobID());
 
+        final SlotSharingSlotAllocator slotAllocator =
+                createSlotSharingSlotAllocator(declarativeSlotPool);
+
         return new AdaptiveScheduler(
                 jobGraph,
                 jobMasterConfiguration,
                 declarativeSlotPool,
+                slotAllocator,
                 futureExecutor,
                 ioExecutor,
                 userCodeLoader,
@@ -113,4 +118,12 @@ public class AdaptiveSchedulerFactory implements SchedulerNGFactory {
     public JobManagerOptions.SchedulerType getSchedulerType() {
         return JobManagerOptions.SchedulerType.Adaptive;
     }
+
+    public static SlotSharingSlotAllocator createSlotSharingSlotAllocator(
+            DeclarativeSlotPool declarativeSlotPool) {
+        return SlotSharingSlotAllocator.createSlotSharingSlotAllocator(
+                declarativeSlotPool::reserveFreeSlot,
+                declarativeSlotPool::freeReservedSlot,
+                declarativeSlotPool::containsFreeSlot);
+    }
 }
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
index fc72a45..edc3b7f 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocator.java
@@ -50,7 +50,7 @@ public class SlotSharingSlotAllocator implements SlotAllocator {
     private final FreeSlotFunction freeSlotFunction;
     private final IsSlotAvailableAndFreeFunction isSlotAvailableAndFreeFunction;
 
-    public SlotSharingSlotAllocator(
+    private SlotSharingSlotAllocator(
             ReserveSlotFunction reserveSlot,
             FreeSlotFunction freeSlotFunction,
             IsSlotAvailableAndFreeFunction isSlotAvailableAndFreeFunction) {
@@ -59,6 +59,14 @@ public class SlotSharingSlotAllocator implements SlotAllocator {
         this.isSlotAvailableAndFreeFunction = isSlotAvailableAndFreeFunction;
     }
 
+    public static SlotSharingSlotAllocator createSlotSharingSlotAllocator(
+            ReserveSlotFunction reserveSlot,
+            FreeSlotFunction freeSlotFunction,
+            IsSlotAvailableAndFreeFunction isSlotAvailableAndFreeFunction) {
+        return new SlotSharingSlotAllocator(
+                reserveSlot, freeSlotFunction, isSlotAvailableAndFreeFunction);
+    }
+
     @Override
     public ResourceCounter calculateRequiredSlots(
             Iterable<JobInformation.VertexInformation> vertices) {
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerBuilder.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerBuilder.java
index 6d6257d..e005170 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerBuilder.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/AdaptiveSchedulerBuilder.java
@@ -37,11 +37,14 @@ import org.apache.flink.runtime.jobmaster.slotpool.DefaultDeclarativeSlotPool;
 import org.apache.flink.runtime.metrics.groups.JobManagerJobMetricGroup;
 import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
 import org.apache.flink.runtime.rpc.FatalErrorHandler;
+import org.apache.flink.runtime.scheduler.adaptive.allocator.SlotAllocator;
 import org.apache.flink.runtime.shuffle.NettyShuffleMaster;
 import org.apache.flink.runtime.shuffle.ShuffleMaster;
 import org.apache.flink.runtime.testingUtils.TestingUtils;
 import org.apache.flink.runtime.util.FatalExitExceptionHandler;
 
+import javax.annotation.Nullable;
+
 import java.util.concurrent.Executor;
 import java.util.concurrent.ScheduledExecutorService;
 
@@ -75,6 +78,8 @@ public class AdaptiveSchedulerBuilder {
     private JobStatusListener jobStatusListener = (ignoredA, ignoredB, ignoredC, ignoredD) -> {};
     private long initializationTimestamp = System.currentTimeMillis();
 
+    @Nullable private SlotAllocator slotAllocator;
+
     public AdaptiveSchedulerBuilder(
             final JobGraph jobGraph, ComponentMainThreadExecutor mainThreadExecutor) {
         this.jobGraph = jobGraph;
@@ -171,11 +176,20 @@ public class AdaptiveSchedulerBuilder {
         return this;
     }
 
+    public AdaptiveSchedulerBuilder setSlotAllocator(SlotAllocator slotAllocator) {
+        this.slotAllocator = slotAllocator;
+        return this;
+    }
+
     public AdaptiveScheduler build() throws Exception {
         return new AdaptiveScheduler(
                 jobGraph,
                 jobMasterConfiguration,
                 declarativeSlotPool,
+                slotAllocator == null
+                        ? AdaptiveSchedulerFactory.createSlotSharingSlotAllocator(
+                                declarativeSlotPool)
+                        : slotAllocator,
                 futureExecutor,
                 ioExecutor,
                 userCodeLoader,
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocatorTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocatorTest.java
index 22b8ddd..a8dc02f 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocatorTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/SlotSharingSlotAllocatorTest.java
@@ -68,7 +68,7 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
     @Test
     public void testCalculateRequiredSlots() {
         final SlotSharingSlotAllocator slotAllocator =
-                new SlotSharingSlotAllocator(
+                SlotSharingSlotAllocator.createSlotSharingSlotAllocator(
                         TEST_RESERVE_SLOT_FUNCTION,
                         TEST_FREE_SLOT_FUNCTION,
                         TEST_IS_SLOT_FREE_FUNCTION);
@@ -87,7 +87,7 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
     @Test
     public void testDetermineParallelismWithMinimumSlots() {
         final SlotSharingSlotAllocator slotAllocator =
-                new SlotSharingSlotAllocator(
+                SlotSharingSlotAllocator.createSlotSharingSlotAllocator(
                         TEST_RESERVE_SLOT_FUNCTION,
                         TEST_FREE_SLOT_FUNCTION,
                         TEST_IS_SLOT_FREE_FUNCTION);
@@ -109,7 +109,7 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
     @Test
     public void testDetermineParallelismWithManySlots() {
         final SlotSharingSlotAllocator slotAllocator =
-                new SlotSharingSlotAllocator(
+                SlotSharingSlotAllocator.createSlotSharingSlotAllocator(
                         TEST_RESERVE_SLOT_FUNCTION,
                         TEST_FREE_SLOT_FUNCTION,
                         TEST_IS_SLOT_FREE_FUNCTION);
@@ -137,7 +137,7 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
     @Test
     public void testDetermineParallelismUnsuccessfulWithLessSlotsThanSlotSharingGroups() {
         final SlotSharingSlotAllocator slotAllocator =
-                new SlotSharingSlotAllocator(
+                SlotSharingSlotAllocator.createSlotSharingSlotAllocator(
                         TEST_RESERVE_SLOT_FUNCTION,
                         TEST_FREE_SLOT_FUNCTION,
                         TEST_IS_SLOT_FREE_FUNCTION);
@@ -154,7 +154,7 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
     @Test
     public void testReserveAvailableResources() {
         final SlotSharingSlotAllocator slotAllocator =
-                new SlotSharingSlotAllocator(
+                SlotSharingSlotAllocator.createSlotSharingSlotAllocator(
                         TEST_RESERVE_SLOT_FUNCTION,
                         TEST_FREE_SLOT_FUNCTION,
                         TEST_IS_SLOT_FREE_FUNCTION);
@@ -193,7 +193,7 @@ public class SlotSharingSlotAllocatorTest extends TestLogger {
     @Test
     public void testReserveUnavailableResources() {
         final SlotSharingSlotAllocator slotSharingSlotAllocator =
-                new SlotSharingSlotAllocator(
+                SlotSharingSlotAllocator.createSlotSharingSlotAllocator(
                         TEST_RESERVE_SLOT_FUNCTION, TEST_FREE_SLOT_FUNCTION, ignored -> false);
 
         final JobInformation jobInformation =