tillrohrmann commented on a change in pull request #7662: [FLINK-10431] 
Extraction of scheduling-related code from SlotPool into preliminary Scheduler 
(rebased)
URL: https://github.com/apache/flink/pull/7662#discussion_r255131877
 
 

 ##########
 File path: 
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/SlotPool.java
 ##########
 @@ -18,1725 +18,163 @@
 
 package org.apache.flink.runtime.jobmaster.slotpool;
 
-import org.apache.flink.annotation.VisibleForTesting;
-import org.apache.flink.api.common.JobID;
 import org.apache.flink.api.common.time.Time;
-import org.apache.flink.configuration.JobManagerOptions;
-import org.apache.flink.runtime.akka.AkkaUtils;
 import org.apache.flink.runtime.clusterframework.types.AllocationID;
 import org.apache.flink.runtime.clusterframework.types.ResourceID;
 import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
-import org.apache.flink.runtime.clusterframework.types.SlotID;
-import org.apache.flink.runtime.clusterframework.types.SlotProfile;
-import org.apache.flink.runtime.concurrent.FutureUtils;
-import org.apache.flink.runtime.executiongraph.ExecutionGraph;
-import org.apache.flink.runtime.instance.SlotSharingGroupId;
-import org.apache.flink.runtime.jobmanager.scheduler.CoLocationConstraint;
-import org.apache.flink.runtime.jobmanager.scheduler.Locality;
-import 
org.apache.flink.runtime.jobmanager.scheduler.NoResourceAvailableException;
-import org.apache.flink.runtime.jobmanager.scheduler.ScheduledUnit;
+import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutor;
 import org.apache.flink.runtime.jobmanager.slots.TaskManagerGateway;
 import org.apache.flink.runtime.jobmaster.JobMasterId;
-import org.apache.flink.runtime.jobmaster.LogicalSlot;
-import org.apache.flink.runtime.jobmaster.SlotContext;
-import org.apache.flink.runtime.jobmaster.SlotOwner;
+import org.apache.flink.runtime.jobmaster.SlotInfo;
 import org.apache.flink.runtime.jobmaster.SlotRequestId;
-import org.apache.flink.runtime.messages.Acknowledge;
 import org.apache.flink.runtime.resourcemanager.ResourceManagerGateway;
-import org.apache.flink.runtime.resourcemanager.SlotRequest;
-import org.apache.flink.runtime.rpc.RpcEndpoint;
-import org.apache.flink.runtime.rpc.RpcService;
+import org.apache.flink.runtime.rpc.RpcTimeout;
 import org.apache.flink.runtime.taskexecutor.slot.SlotOffer;
 import org.apache.flink.runtime.taskmanager.TaskManagerLocation;
-import org.apache.flink.runtime.util.clock.Clock;
-import org.apache.flink.runtime.util.clock.SystemClock;
-import org.apache.flink.types.SerializableOptional;
-import org.apache.flink.util.AbstractID;
-import org.apache.flink.util.FlinkException;
-import org.apache.flink.util.Preconditions;
 
 import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
 
-import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Objects;
 import java.util.Optional;
-import java.util.Set;
 import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import static org.apache.flink.util.Preconditions.checkNotNull;
 
 /**
- * The slot pool serves slot request issued by {@link ExecutionGraph}. It will 
attempt to acquire new slots
- * from the ResourceManager when it cannot serve a slot request. If no 
ResourceManager is currently available,
- * or it gets a decline from the ResourceManager, or a request times out, it 
fails the slot request. The slot pool also
- * holds all the slots that were offered to it and accepted, and can thus 
provides registered free slots even if the
- * ResourceManager is down. The slots will only be released when they are 
useless, e.g. when the job is fully running
- * but we still have some free slots.
- *
- * <p>All the allocation or the slot offering will be identified by self 
generated AllocationID, we will use it to
- * eliminate ambiguities.
- *
- * <p>TODO : Make pending requests location preference aware
- * TODO : Make pass location preferences to ResourceManager when sending a 
slot request
+ * The Interface of a slot pool that manages slots.
  */
-public class SlotPool extends RpcEndpoint implements SlotPoolGateway, 
AllocatedSlotActions {
-
-       /** The interval (in milliseconds) in which the SlotPool writes its 
slot distribution on debug level. */
-       private static final int STATUS_LOG_INTERVAL_MS = 60_000;
-
-       private final JobID jobId;
-
-       private final SchedulingStrategy schedulingStrategy;
-
-       private final ProviderAndOwner providerAndOwner;
-
-       /** All registered TaskManagers, slots will be accepted and used only 
if the resource is registered. */
-       private final HashSet<ResourceID> registeredTaskManagers;
-
-       /** The book-keeping of all allocated slots. */
-       private final AllocatedSlots allocatedSlots;
-
-       /** The book-keeping of all available slots. */
-       private final AvailableSlots availableSlots;
-
-       /** All pending requests waiting for slots. */
-       private final DualKeyMap<SlotRequestId, AllocationID, PendingRequest> 
pendingRequests;
-
-       /** The requests that are waiting for the resource manager to be 
connected. */
-       private final HashMap<SlotRequestId, PendingRequest> 
waitingForResourceManager;
-
-       /** Timeout for external request calls (e.g. to the ResourceManager or 
the TaskExecutor). */
-       private final Time rpcTimeout;
-
-       /** Timeout for releasing idle slots. */
-       private final Time idleSlotTimeout;
-
-       private final Clock clock;
-
-       /** Managers for the different slot sharing groups. */
-       protected final Map<SlotSharingGroupId, SlotSharingManager> 
slotSharingManagers;
-
-       /** the fencing token of the job manager. */
-       private JobMasterId jobMasterId;
-
-       /** The gateway to communicate with resource manager. */
-       private ResourceManagerGateway resourceManagerGateway;
-
-       private String jobManagerAddress;
+public interface SlotPool extends AllocatedSlotActions, AutoCloseable {
 
        // 
------------------------------------------------------------------------
-
-       @VisibleForTesting
-       protected SlotPool(RpcService rpcService, JobID jobId, 
SchedulingStrategy schedulingStrategy) {
-               this(
-                       rpcService,
-                       jobId,
-                       schedulingStrategy,
-                       SystemClock.getInstance(),
-                       AkkaUtils.getDefaultTimeout(),
-                       
Time.milliseconds(JobManagerOptions.SLOT_IDLE_TIMEOUT.defaultValue()));
-       }
-
-       public SlotPool(
-                       RpcService rpcService,
-                       JobID jobId,
-                       SchedulingStrategy schedulingStrategy,
-                       Clock clock,
-                       Time rpcTimeout,
-                       Time idleSlotTimeout) {
-
-               super(rpcService);
-
-               this.jobId = checkNotNull(jobId);
-               this.schedulingStrategy = checkNotNull(schedulingStrategy);
-               this.clock = checkNotNull(clock);
-               this.rpcTimeout = checkNotNull(rpcTimeout);
-               this.idleSlotTimeout = checkNotNull(idleSlotTimeout);
-
-               this.registeredTaskManagers = new HashSet<>(16);
-               this.allocatedSlots = new AllocatedSlots();
-               this.availableSlots = new AvailableSlots();
-               this.pendingRequests = new DualKeyMap<>(16);
-               this.waitingForResourceManager = new HashMap<>(16);
-
-               this.providerAndOwner = new ProviderAndOwner(
-                       getSelfGateway(SlotPoolGateway.class),
-                       schedulingStrategy instanceof 
PreviousAllocationSchedulingStrategy);
-
-               this.slotSharingManagers = new HashMap<>(4);
-
-               this.jobMasterId = null;
-               this.resourceManagerGateway = null;
-               this.jobManagerAddress = null;
-       }
-
+       //  lifecycle
        // 
------------------------------------------------------------------------
-       //  Starting and Stopping
-       // 
------------------------------------------------------------------------
-
-       @Override
-       public void start() {
-               throw new UnsupportedOperationException("Should never call 
start() without leader ID");
-       }
 
-       /**
-        * Start the slot pool to accept RPC calls.
-        *
-        * @param jobMasterId The necessary leader id for running the job.
-        * @param newJobManagerAddress for the slot requests which are sent to 
the resource manager
-        */
-       public void start(JobMasterId jobMasterId, String newJobManagerAddress) 
throws Exception {
-               this.jobMasterId = checkNotNull(jobMasterId);
-               this.jobManagerAddress = checkNotNull(newJobManagerAddress);
+       void start(
+               JobMasterId jobMasterId,
+               String newJobManagerAddress,
+               ComponentMainThreadExecutor jmMainThreadScheduledExecutor) 
throws Exception;
 
-               // TODO - start should not throw an exception
-               try {
-                       super.start();
-               } catch (Exception e) {
-                       throw new RuntimeException("This should never happen", 
e);
-               }
-
-               scheduleRunAsync(this::checkIdleSlot, idleSlotTimeout);
-
-               if (log.isDebugEnabled()) {
-                       scheduleRunAsync(this::scheduledLogStatus, 
STATUS_LOG_INTERVAL_MS, TimeUnit.MILLISECONDS);
-               }
-       }
-
-       @Override
-       public CompletableFuture<Void> postStop() {
-               log.info("Stopping SlotPool.");
-               // cancel all pending allocations
-               Set<AllocationID> allocationIds = pendingRequests.keySetB();
-
-               for (AllocationID allocationId : allocationIds) {
-                       resourceManagerGateway.cancelSlotRequest(allocationId);
-               }
-
-               // release all registered slots by releasing the corresponding 
TaskExecutors
-               for (ResourceID taskManagerResourceId : registeredTaskManagers) 
{
-                       final FlinkException cause = new FlinkException(
-                               "Releasing TaskManager " + 
taskManagerResourceId + ", because of stopping of SlotPool");
-                       releaseTaskManagerInternal(taskManagerResourceId, 
cause);
-               }
-
-               clear();
-
-               return CompletableFuture.completedFuture(null);
-       }
-
-       /**
-        * Suspends this pool, meaning it has lost its authority to accept and 
distribute slots.
-        */
-       @Override
-       public CompletableFuture<Acknowledge> suspend() {
-               log.info("Suspending SlotPool.");
+       void suspend();
 
-               validateRunsInMainThread();
-
-               // cancel all pending allocations --> we can request these slots
-               // again after we regained the leadership
-               Set<AllocationID> allocationIds = pendingRequests.keySetB();
-
-               for (AllocationID allocationId : allocationIds) {
-                       resourceManagerGateway.cancelSlotRequest(allocationId);
-               }
-
-               // suspend this RPC endpoint
-               stop();
-
-               // do not accept any requests
-               jobMasterId = null;
-               resourceManagerGateway = null;
-
-               // Clear (but not release!) the available slots. The 
TaskManagers should re-register them
-               // at the new leader JobManager/SlotPool
-               clear();
-
-               return CompletableFuture.completedFuture(Acknowledge.get());
-       }
+       void close();
 
        // 
------------------------------------------------------------------------
-       //  Getting PoolOwner and PoolProvider
+       //  resource manager connection
        // 
------------------------------------------------------------------------
 
        /**
-        * Gets the slot owner implementation for this pool.
+        * Connects the SlotPool to the given ResourceManager. After this 
method is called, the
+        * SlotPool will be able to request resources from the given 
ResourceManager.
         *
-        * <p>This method does not mutate state and can be called directly (no 
RPC indirection)
-        *
-        * @return The slot owner implementation for this pool.
+        * @param resourceManagerGateway  The RPC gateway for the resource 
manager.
         */
-       public SlotOwner getSlotOwner() {
-               return providerAndOwner;
-       }
+       void connectToResourceManager(ResourceManagerGateway 
resourceManagerGateway);
 
        /**
-        * Gets the slot provider implementation for this pool.
-        *
-        * <p>This method does not mutate state and can be called directly (no 
RPC indirection)
+        * Disconnects the slot pool from its current Resource Manager. After 
this call, the pool will not
+        * be able to request further slots from the Resource Manager, and all 
currently pending requests
+        * to the resource manager will be canceled.
         *
-        * @return The slot provider implementation for this pool.
+        * <p>The slot pool will still be able to serve slots from its internal 
pool.
         */
-       public SlotProvider getSlotProvider() {
-               return providerAndOwner;
-       }
+       void disconnectResourceManager();
 
        // 
------------------------------------------------------------------------
-       //  Resource Manager Connection
+       //  registering / un-registering TaskManagers and slots
        // 
------------------------------------------------------------------------
 
-       @Override
-       public void connectToResourceManager(ResourceManagerGateway 
resourceManagerGateway) {
-               this.resourceManagerGateway = 
checkNotNull(resourceManagerGateway);
-
-               // work on all slots waiting for this connection
-               for (PendingRequest pendingRequest : 
waitingForResourceManager.values()) {
-                       requestSlotFromResourceManager(resourceManagerGateway, 
pendingRequest);
-               }
-
-               // all sent off
-               waitingForResourceManager.clear();
-       }
-
-       @Override
-       public void disconnectResourceManager() {
-               this.resourceManagerGateway = null;
-       }
-
-       // 
------------------------------------------------------------------------
-       //  Slot Allocation
-       // 
------------------------------------------------------------------------
-
-       @Override
-       public CompletableFuture<LogicalSlot> allocateSlot(
-                       SlotRequestId slotRequestId,
-                       ScheduledUnit task,
-                       SlotProfile slotProfile,
-                       boolean allowQueuedScheduling,
-                       Time allocationTimeout) {
-
-               log.debug("Received slot request [{}] for task: {}", 
slotRequestId, task.getTaskToExecute());
-
-               if (task.getSlotSharingGroupId() == null) {
-                       return allocateSingleSlot(slotRequestId, slotProfile, 
allowQueuedScheduling, allocationTimeout);
-               } else {
-                       return allocateSharedSlot(slotRequestId, task, 
slotProfile, allowQueuedScheduling, allocationTimeout);
-               }
-       }
-
-       private CompletableFuture<LogicalSlot> allocateSingleSlot(
-               SlotRequestId slotRequestId,
-               SlotProfile slotProfile,
-               boolean allowQueuedScheduling,
-               Time allocationTimeout) {
-               // request an allocated slot to assign a single logical slot to
-               CompletableFuture<SlotAndLocality> slotAndLocalityFuture = 
requestAllocatedSlot(
-                       slotRequestId,
-                       slotProfile,
-                       allowQueuedScheduling,
-                       allocationTimeout);
-
-               return slotAndLocalityFuture.thenApply(
-                       (SlotAndLocality slotAndLocality) -> {
-                               final AllocatedSlot allocatedSlot = 
slotAndLocality.getSlot();
-
-                               final SingleLogicalSlot singleTaskSlot = new 
SingleLogicalSlot(
-                                       slotRequestId,
-                                       allocatedSlot,
-                                       null,
-                                       slotAndLocality.getLocality(),
-                                       providerAndOwner);
-
-                               if 
(allocatedSlot.tryAssignPayload(singleTaskSlot)) {
-                                       return singleTaskSlot;
-                               } else {
-                                       final FlinkException flinkException =
-                                               new FlinkException("Could not 
assign payload to allocated slot " + allocatedSlot.getAllocationId() + '.');
-                                       releaseSingleSlot(slotRequestId, 
flinkException);
-                                       throw new 
CompletionException(flinkException);
-                               }
-                       });
-       }
-
-       private CompletableFuture<LogicalSlot> allocateSharedSlot(
-               SlotRequestId slotRequestId,
-               ScheduledUnit task,
-               SlotProfile slotProfile,
-               boolean allowQueuedScheduling,
-               Time allocationTimeout) {
-
-               // allocate slot with slot sharing
-               final SlotSharingManager multiTaskSlotManager = 
slotSharingManagers.computeIfAbsent(
-                       task.getSlotSharingGroupId(),
-                       id -> new SlotSharingManager(
-                               id,
-                               this,
-                               providerAndOwner));
-
-               final SlotSharingManager.MultiTaskSlotLocality 
multiTaskSlotLocality;
-
-               try {
-                       if (task.getCoLocationConstraint() != null) {
-                               multiTaskSlotLocality = 
allocateCoLocatedMultiTaskSlot(
-                                       task.getCoLocationConstraint(),
-                                       multiTaskSlotManager,
-                                       slotProfile,
-                                       allowQueuedScheduling,
-                                       allocationTimeout);
-                       } else {
-                               multiTaskSlotLocality = allocateMultiTaskSlot(
-                                       task.getJobVertexId(),
-                                       multiTaskSlotManager,
-                                       slotProfile,
-                                       allowQueuedScheduling,
-                                       allocationTimeout);
-                       }
-               } catch (NoResourceAvailableException noResourceException) {
-                       return 
FutureUtils.completedExceptionally(noResourceException);
-               }
-
-               // sanity check
-               
Preconditions.checkState(!multiTaskSlotLocality.getMultiTaskSlot().contains(task.getJobVertexId()));
-
-               final SlotSharingManager.SingleTaskSlot leaf = 
multiTaskSlotLocality.getMultiTaskSlot().allocateSingleTaskSlot(
-                       slotRequestId,
-                       task.getJobVertexId(),
-                       multiTaskSlotLocality.getLocality());
-
-               return leaf.getLogicalSlotFuture();
-       }
-
        /**
-        * Allocates a co-located {@link SlotSharingManager.MultiTaskSlot} for 
the given {@link CoLocationConstraint}.
-        *
-        * <p>If allowQueuedScheduling is true, then the returned {@link 
SlotSharingManager.MultiTaskSlot} can be
-        * uncompleted.
+        * Registers a TaskExecutor with the given {@link ResourceID} at {@link 
SlotPool}.
         *
-        * @param coLocationConstraint for which to allocate a {@link 
SlotSharingManager.MultiTaskSlot}
-        * @param multiTaskSlotManager responsible for the slot sharing group 
for which to allocate the slot
-        * @param slotProfile specifying the requirements for the requested slot
-        * @param allowQueuedScheduling true if queued scheduling (the returned 
task slot must not be completed yet) is allowed, otherwise false
-        * @param allocationTimeout timeout before the slot allocation times out
-        * @return A {@link SlotSharingManager.MultiTaskSlotLocality} which 
contains the allocated{@link SlotSharingManager.MultiTaskSlot}
-        *              and its locality wrt the given location preferences
-        * @throws NoResourceAvailableException if no task slot could be 
allocated
+        * @param resourceID identifying the TaskExecutor to register
+        * @return true iff a new resource id was registered
         */
-       private SlotSharingManager.MultiTaskSlotLocality 
allocateCoLocatedMultiTaskSlot(
-                       CoLocationConstraint coLocationConstraint,
-                       SlotSharingManager multiTaskSlotManager,
-                       SlotProfile slotProfile,
-                       boolean allowQueuedScheduling,
-                       Time allocationTimeout) throws 
NoResourceAvailableException {
-               final SlotRequestId coLocationSlotRequestId = 
coLocationConstraint.getSlotRequestId();
-
-               if (coLocationSlotRequestId != null) {
-                       // we have a slot assigned --> try to retrieve it
-                       final SlotSharingManager.TaskSlot taskSlot = 
multiTaskSlotManager.getTaskSlot(coLocationSlotRequestId);
-
-                       if (taskSlot != null) {
-                               Preconditions.checkState(taskSlot instanceof 
SlotSharingManager.MultiTaskSlot);
-                               return 
SlotSharingManager.MultiTaskSlotLocality.of(((SlotSharingManager.MultiTaskSlot) 
taskSlot), Locality.LOCAL);
-                       } else {
-                               // the slot may have been cancelled in the mean 
time
-                               coLocationConstraint.setSlotRequestId(null);
-                       }
-               }
-
-               if (coLocationConstraint.isAssigned()) {
-                       // refine the preferred locations of the slot profile
-                       slotProfile = new SlotProfile(
-                               slotProfile.getResourceProfile(),
-                               
Collections.singleton(coLocationConstraint.getLocation()),
-                               slotProfile.getPreferredAllocations());
-               }
-
-               // get a new multi task slot
-               final SlotSharingManager.MultiTaskSlotLocality 
multiTaskSlotLocality = allocateMultiTaskSlot(
-                       coLocationConstraint.getGroupId(),
-                       multiTaskSlotManager,
-                       slotProfile,
-                       allowQueuedScheduling,
-                       allocationTimeout);
-
-               // check whether we fulfill the co-location constraint
-               if (coLocationConstraint.isAssigned() && 
multiTaskSlotLocality.getLocality() != Locality.LOCAL) {
-                       multiTaskSlotLocality.getMultiTaskSlot().release(
-                               new FlinkException("Multi task slot is not 
local and, thus, does not fulfill the co-location constraint."));
-
-                       throw new NoResourceAvailableException("Could not 
allocate a local multi task slot for the " +
-                               "co location constraint " + 
coLocationConstraint + '.');
-               }
-
-               final SlotRequestId slotRequestId = new SlotRequestId();
-               final SlotSharingManager.MultiTaskSlot coLocationSlot = 
multiTaskSlotLocality.getMultiTaskSlot().allocateMultiTaskSlot(
-                       slotRequestId,
-                       coLocationConstraint.getGroupId());
-
-               // mark the requested slot as co-located slot for other 
co-located tasks
-               coLocationConstraint.setSlotRequestId(slotRequestId);
-
-               // lock the co-location constraint once we have obtained the 
allocated slot
-               coLocationSlot.getSlotContextFuture().whenComplete(
-                       (SlotContext slotContext, Throwable throwable) -> {
-                               if (throwable == null) {
-                                       // check whether we are still assigned 
to the co-location constraint
-                                       if 
(Objects.equals(coLocationConstraint.getSlotRequestId(), slotRequestId)) {
-                                               
coLocationConstraint.lockLocation(slotContext.getTaskManagerLocation());
-                                       } else {
-                                               log.debug("Failed to lock 
colocation constraint {} because assigned slot " +
-                                                       "request {} differs 
from fulfilled slot request {}.",
-                                                       
coLocationConstraint.getGroupId(),
-                                                       
coLocationConstraint.getSlotRequestId(),
-                                                       slotRequestId);
-                                       }
-                               } else {
-                                       log.debug("Failed to lock colocation 
constraint {} because the slot " +
-                                               "allocation for slot request {} 
failed.",
-                                               
coLocationConstraint.getGroupId(),
-                                               
coLocationConstraint.getSlotRequestId(),
-                                               throwable);
-                               }
-                       });
-
-               return 
SlotSharingManager.MultiTaskSlotLocality.of(coLocationSlot, 
multiTaskSlotLocality.getLocality());
-       }
+       boolean registerTaskManager(ResourceID resourceID);
 
        /**
-        * Allocates a {@link SlotSharingManager.MultiTaskSlot} for the given 
groupId which is in the
-        * slot sharing group for which the given {@link SlotSharingManager} is 
responsible.
+        * Releases a TaskExecutor with the given {@link ResourceID} from the 
{@link SlotPool}.
         *
-        * <p>If allowQueuedScheduling is true, then the method can return an 
uncompleted {@link SlotSharingManager.MultiTaskSlot}.
-        *
-        * @param groupId for which to allocate a new {@link 
SlotSharingManager.MultiTaskSlot}
-        * @param slotSharingManager responsible for the slot sharing group for 
which to allocate the slot
-        * @param slotProfile slot profile that specifies the requirements for 
the slot
-        * @param allowQueuedScheduling true if queued scheduling (the returned 
task slot must not be completed yet) is allowed, otherwise false
-        * @param allocationTimeout timeout before the slot allocation times out
-        * @return A {@link SlotSharingManager.MultiTaskSlotLocality} which 
contains the allocated {@link SlotSharingManager.MultiTaskSlot}
-        *              and its locality wrt the given location preferences
-        * @throws NoResourceAvailableException if no task slot could be 
allocated
-        */
-       private SlotSharingManager.MultiTaskSlotLocality allocateMultiTaskSlot(
-                       AbstractID groupId,
-                       SlotSharingManager slotSharingManager,
-                       SlotProfile slotProfile,
-                       boolean allowQueuedScheduling,
-                       Time allocationTimeout) throws 
NoResourceAvailableException {
-
-               // check first whether we have a resolved root slot which we 
can use
-               SlotSharingManager.MultiTaskSlotLocality multiTaskSlotLocality 
= slotSharingManager.getResolvedRootSlot(
-                       groupId,
-                       schedulingStrategy,
-                       slotProfile);
-
-               if (multiTaskSlotLocality != null && 
multiTaskSlotLocality.getLocality() == Locality.LOCAL) {
-                       return multiTaskSlotLocality;
-               }
-
-               final SlotRequestId allocatedSlotRequestId = new 
SlotRequestId();
-               final SlotRequestId multiTaskSlotRequestId = new 
SlotRequestId();
-
-               // check whether we have an allocated slot available which we 
can use to create a new multi task slot in
-               final SlotAndLocality polledSlotAndLocality = 
pollAndAllocateSlot(allocatedSlotRequestId, slotProfile);
-
-               if (polledSlotAndLocality != null && 
(polledSlotAndLocality.getLocality() == Locality.LOCAL || multiTaskSlotLocality 
== null)) {
-
-                       final AllocatedSlot allocatedSlot = 
polledSlotAndLocality.getSlot();
-                       final SlotSharingManager.MultiTaskSlot multiTaskSlot = 
slotSharingManager.createRootSlot(
-                               multiTaskSlotRequestId,
-                               
CompletableFuture.completedFuture(polledSlotAndLocality.getSlot()),
-                               allocatedSlotRequestId);
-
-                       if (allocatedSlot.tryAssignPayload(multiTaskSlot)) {
-                               return 
SlotSharingManager.MultiTaskSlotLocality.of(multiTaskSlot, 
polledSlotAndLocality.getLocality());
-                       } else {
-                               multiTaskSlot.release(new FlinkException("Could 
not assign payload to allocated slot " +
-                                       allocatedSlot.getAllocationId() + '.'));
-                       }
-               }
-
-               if (multiTaskSlotLocality != null) {
-                       // prefer slot sharing group slots over unused slots
-                       if (polledSlotAndLocality != null) {
-                               releaseSingleSlot(
-                                       allocatedSlotRequestId,
-                                       new FlinkException("Locality constraint 
is not better fulfilled by allocated slot."));
-                       }
-                       return multiTaskSlotLocality;
-               }
-
-               if (allowQueuedScheduling) {
-                       // there is no slot immediately available --> check 
first for uncompleted slots at the slot sharing group
-                       SlotSharingManager.MultiTaskSlot multiTaskSlotFuture = 
slotSharingManager.getUnresolvedRootSlot(groupId);
-
-                       if (multiTaskSlotFuture == null) {
-                               // it seems as if we have to request a new slot 
from the resource manager, this is always the last resort!!!
-                               final CompletableFuture<AllocatedSlot> 
futureSlot = requestNewAllocatedSlot(
-                                       allocatedSlotRequestId,
-                                       slotProfile.getResourceProfile(),
-                                       allocationTimeout);
-
-                               multiTaskSlotFuture = 
slotSharingManager.createRootSlot(
-                                       multiTaskSlotRequestId,
-                                       futureSlot,
-                                       allocatedSlotRequestId);
-
-                               futureSlot.whenComplete(
-                                       (AllocatedSlot allocatedSlot, Throwable 
throwable) -> {
-                                               final 
SlotSharingManager.TaskSlot taskSlot = 
slotSharingManager.getTaskSlot(multiTaskSlotRequestId);
-
-                                               if (taskSlot != null) {
-                                                       // still valid
-                                                       if (!(taskSlot 
instanceof SlotSharingManager.MultiTaskSlot) || throwable != null) {
-                                                               
taskSlot.release(throwable);
-                                                       } else {
-                                                               if 
(!allocatedSlot.tryAssignPayload(((SlotSharingManager.MultiTaskSlot) 
taskSlot))) {
-                                                                       
taskSlot.release(new FlinkException("Could not assign payload to allocated slot 
" +
-                                                                               
allocatedSlot.getAllocationId() + '.'));
-                                                               }
-                                                       }
-                                               } else {
-                                                       releaseSingleSlot(
-                                                               
allocatedSlotRequestId,
-                                                               new 
FlinkException("Could not find task slot with " + multiTaskSlotRequestId + 
'.'));
-                                               }
-                                       });
-                       }
-
-                       return 
SlotSharingManager.MultiTaskSlotLocality.of(multiTaskSlotFuture, 
Locality.UNKNOWN);
-
-               } else {
-                       throw new NoResourceAvailableException("Could not 
allocate a shared slot for " + groupId + '.');
-               }
-       }
-
-       /**
-        * Allocates an allocated slot first by polling from the available 
slots and then requesting a new
-        * slot from the ResourceManager if no fitting slot could be found.
-        *
-        * @param slotProfile slot profile that specifies the requirements for 
the slot
-        * @param allowQueuedScheduling true if the slot allocation can be 
completed in the future
-        * @param allocationTimeout timeout before the slot allocation times out
-        * @return Future containing the allocated simple slot
-        */
-       private CompletableFuture<SlotAndLocality> requestAllocatedSlot(
-                       SlotRequestId slotRequestId,
-                       SlotProfile slotProfile,
-                       boolean allowQueuedScheduling,
-                       Time allocationTimeout) {
-
-               final CompletableFuture<SlotAndLocality> 
allocatedSlotLocalityFuture;
-
-               // (1) do we have a slot available already?
-               SlotAndLocality slotFromPool = 
pollAndAllocateSlot(slotRequestId, slotProfile);
-
-               if (slotFromPool != null) {
-                       allocatedSlotLocalityFuture = 
CompletableFuture.completedFuture(slotFromPool);
-               } else if (allowQueuedScheduling) {
-                       // we have to request a new allocated slot
-                       CompletableFuture<AllocatedSlot> allocatedSlotFuture = 
requestNewAllocatedSlot(
-                               slotRequestId,
-                               slotProfile.getResourceProfile(),
-                               allocationTimeout);
-
-                       allocatedSlotLocalityFuture = 
allocatedSlotFuture.thenApply((AllocatedSlot allocatedSlot) -> new 
SlotAndLocality(allocatedSlot, Locality.UNKNOWN));
-               } else {
-                       allocatedSlotLocalityFuture = 
FutureUtils.completedExceptionally(new NoResourceAvailableException("Could not 
allocate a simple slot for " +
-                               slotRequestId + '.'));
-               }
-
-               return allocatedSlotLocalityFuture;
-       }
-
-       /**
-        * Requests a new slot with the given {@link ResourceProfile} from the 
ResourceManager. If there is
-        * currently not ResourceManager connected, then the request is stashed 
and send once a new
-        * ResourceManager is connected.
-        *
-        * @param slotRequestId identifying the requested slot
-        * @param resourceProfile which the requested slot should fulfill
-        * @param allocationTimeout timeout before the slot allocation times out
-        * @return An {@link AllocatedSlot} future which is completed once the 
slot is offered to the {@link SlotPool}
+        * @param resourceId identifying the TaskExecutor which shall be 
released from the SlotPool
+        * @param cause for the releasing of the TaskManager
+        * @return true iff a given registered resource id was removed
         */
-       private CompletableFuture<AllocatedSlot> requestNewAllocatedSlot(
-                       SlotRequestId slotRequestId,
-                       ResourceProfile resourceProfile,
-                       Time allocationTimeout) {
-
-               final PendingRequest pendingRequest = new PendingRequest(
-                       slotRequestId,
-                       resourceProfile);
-
-               // register request timeout
-               FutureUtils
-                       .orTimeout(pendingRequest.getAllocatedSlotFuture(), 
allocationTimeout.toMilliseconds(), TimeUnit.MILLISECONDS)
-                       .whenCompleteAsync(
-                               (AllocatedSlot ignored, Throwable throwable) -> 
{
-                                       if (throwable instanceof 
TimeoutException) {
-                                               
timeoutPendingSlotRequest(slotRequestId);
-                                       }
-                               },
-                               getMainThreadExecutor());
-
-               if (resourceManagerGateway == null) {
-                       stashRequestWaitingForResourceManager(pendingRequest);
-               } else {
-                       requestSlotFromResourceManager(resourceManagerGateway, 
pendingRequest);
-               }
-
-               return pendingRequest.getAllocatedSlotFuture();
-       }
-
-       private void requestSlotFromResourceManager(
-                       final ResourceManagerGateway resourceManagerGateway,
-                       final PendingRequest pendingRequest) {
-
-               checkNotNull(resourceManagerGateway);
-               checkNotNull(pendingRequest);
-
-               log.info("Requesting new slot [{}] and profile {} from resource 
manager.", pendingRequest.getSlotRequestId(), 
pendingRequest.getResourceProfile());
-
-               final AllocationID allocationId = new AllocationID();
-
-               pendingRequests.put(pendingRequest.getSlotRequestId(), 
allocationId, pendingRequest);
-
-               pendingRequest.getAllocatedSlotFuture().whenComplete(
-                       (AllocatedSlot allocatedSlot, Throwable throwable) -> {
-                               if (throwable != null || 
!allocationId.equals(allocatedSlot.getAllocationId())) {
-                                       // cancel the slot request if there is 
a failure or if the pending request has
-                                       // been completed with another 
allocated slot
-                                       
resourceManagerGateway.cancelSlotRequest(allocationId);
-                               }
-                       });
-
-               CompletableFuture<Acknowledge> rmResponse = 
resourceManagerGateway.requestSlot(
-                       jobMasterId,
-                       new SlotRequest(jobId, allocationId, 
pendingRequest.getResourceProfile(), jobManagerAddress),
-                       rpcTimeout);
-
-               // on failure, fail the request future
-               rmResponse.whenCompleteAsync(
-                       (Acknowledge ignored, Throwable failure) -> {
-                               if (failure != null) {
-                                       
slotRequestToResourceManagerFailed(pendingRequest.getSlotRequestId(), failure);
-                               }
-                       },
-                       getMainThreadExecutor());
-       }
-
-       private void slotRequestToResourceManagerFailed(SlotRequestId 
slotRequestID, Throwable failure) {
-               PendingRequest request = 
pendingRequests.removeKeyA(slotRequestID);
-               if (request != null) {
-                       
request.getAllocatedSlotFuture().completeExceptionally(new 
NoResourceAvailableException(
-                                       "No pooled slot available and request 
to ResourceManager for new slot failed", failure));
-               } else {
-                       if (log.isDebugEnabled()) {
-                               log.debug("Unregistered slot request [{}] 
failed.", slotRequestID, failure);
-                       }
-               }
-       }
-
-       private void stashRequestWaitingForResourceManager(final PendingRequest 
pendingRequest) {
-
-               log.info("Cannot serve slot request, no ResourceManager 
connected. " +
-                               "Adding as pending request [{}]",  
pendingRequest.getSlotRequestId());
-
-               
waitingForResourceManager.put(pendingRequest.getSlotRequestId(), 
pendingRequest);
-       }
-
-       // 
------------------------------------------------------------------------
-       //  Slot releasing & offering
-       // 
------------------------------------------------------------------------
-
-       @Override
-       public CompletableFuture<Acknowledge> releaseSlot(
-               SlotRequestId slotRequestId,
-               @Nullable SlotSharingGroupId slotSharingGroupId,
-               Throwable cause) {
-
-               log.debug("Releasing slot [{}] because: {}", slotRequestId, 
cause != null ? cause.getMessage() : "null");
-
-               if (slotSharingGroupId != null) {
-                       releaseSharedSlot(slotRequestId, slotSharingGroupId, 
cause);
-               } else {
-                       releaseSingleSlot(slotRequestId, cause);
-               }
-
-               return CompletableFuture.completedFuture(Acknowledge.get());
-       }
-
-       private void releaseSharedSlot(
-               SlotRequestId slotRequestId,
-               @Nonnull SlotSharingGroupId slotSharingGroupId, Throwable 
cause) {
-
-               final SlotSharingManager multiTaskSlotManager = 
slotSharingManagers.get(slotSharingGroupId);
-
-               if (multiTaskSlotManager != null) {
-                       final SlotSharingManager.TaskSlot taskSlot = 
multiTaskSlotManager.getTaskSlot(slotRequestId);
-
-                       if (taskSlot != null) {
-                               taskSlot.release(cause);
-                       } else {
-                               log.debug("Could not find slot [{}] in slot 
sharing group {}. Ignoring release slot request.", slotRequestId, 
slotSharingGroupId);
-                       }
-               } else {
-                       log.debug("Could not find slot sharing group {}. 
Ignoring release slot request.", slotSharingGroupId);
-               }
-       }
-
-       private void releaseSingleSlot(SlotRequestId slotRequestId, Throwable 
cause) {
-               final PendingRequest pendingRequest = 
removePendingRequest(slotRequestId);
-
-               if (pendingRequest != null) {
-                       failPendingRequest(pendingRequest, new 
FlinkException("Pending slot request with " + slotRequestId + " has been 
released."));
-               } else {
-                       final AllocatedSlot allocatedSlot = 
allocatedSlots.remove(slotRequestId);
-
-                       if (allocatedSlot != null) {
-                               allocatedSlot.releasePayload(cause);
-                               
tryFulfillSlotRequestOrMakeAvailable(allocatedSlot);
-                       } else {
-                               log.debug("There is no allocated slot [{}]. 
Ignoring the release slot request.", slotRequestId);
-                       }
-               }
-       }
+       boolean releaseTaskManager(final ResourceID resourceId, final Exception 
cause);
 
        /**
-        * Checks whether there exists a pending request with the given slot 
request id and removes it
-        * from the internal data structures.
+        * Offers a slot to the {@link SlotPool}. The slot offer can be 
accepted or
+        * rejected.
         *
-        * @param requestId identifying the pending request
-        * @return pending request if there is one, otherwise null
+        * @param taskManagerLocation from which the slot offer originates
+        * @param taskManagerGateway to talk to the slot offerer
+        * @param slotOffer slot which is offered to the {@link SlotPool}
+        * @return True if the slot has been accepted, otherwise false
         */
-       @Nullable
-       private PendingRequest removePendingRequest(SlotRequestId requestId) {
-               PendingRequest result = 
waitingForResourceManager.remove(requestId);
-
-               if (result != null) {
-                       // sanity check
-                       assert !pendingRequests.containsKeyA(requestId) : "A 
pending requests should only be part of either " +
-                               "the pendingRequests or 
waitingForResourceManager but not both.";
-
-                       return result;
-               } else {
-                       return pendingRequests.removeKeyA(requestId);
-               }
-       }
-
-       private void failPendingRequest(PendingRequest pendingRequest, 
Exception e) {
-               checkNotNull(pendingRequest);
-               checkNotNull(e);
-
-               if (!pendingRequest.getAllocatedSlotFuture().isDone()) {
-                       log.info("Failing pending slot request [{}]: {}", 
pendingRequest.getSlotRequestId(), e.getMessage());
-                       
pendingRequest.getAllocatedSlotFuture().completeExceptionally(e);
-               }
-       }
-
-       @Nullable
-       private SlotAndLocality pollAndAllocateSlot(SlotRequestId 
slotRequestId, SlotProfile slotProfile) {
-               SlotAndLocality slotFromPool = 
availableSlots.poll(schedulingStrategy, slotProfile);
-
-               if (slotFromPool != null) {
-                       allocatedSlots.add(slotRequestId, 
slotFromPool.getSlot());
-               }
-
-               return slotFromPool;
-       }
+       boolean offerSlot(
+               TaskManagerLocation taskManagerLocation,
+               TaskManagerGateway taskManagerGateway,
+               SlotOffer slotOffer);
 
 Review comment:
   I think this method does not need to be part of the interface.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to