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 2018/03/28 15:24:36 UTC
[7/8] flink git commit: [FLINK-8887] Wait for JobMaster leader
election in Dispatcher
[FLINK-8887] Wait for JobMaster leader election in Dispatcher
Before sending requests from the Dispatcher to the JobMasters, the Dispatcher must
wait until the respective JobMaster has gained leadership. Otherwise we might risk
that the messages are ignored because no fencing token was set.
This is solved by letting the JobManagerRunner expose a CompletableFuture<JobMasterGateway>
which is only completed after the JobMaster has gained leadership. The future is cleared
once the leadership is revoked.
This closes #5767.
Project: http://git-wip-us.apache.org/repos/asf/flink/repo
Commit: http://git-wip-us.apache.org/repos/asf/flink/commit/c0dddc1a
Tree: http://git-wip-us.apache.org/repos/asf/flink/tree/c0dddc1a
Diff: http://git-wip-us.apache.org/repos/asf/flink/diff/c0dddc1a
Branch: refs/heads/master
Commit: c0dddc1a6e3eef8ded1963e61ee4a8f8ecf66475
Parents: e6b1d5c
Author: Till Rohrmann <tr...@apache.org>
Authored: Mon Mar 26 17:55:10 2018 +0200
Committer: Till Rohrmann <tr...@apache.org>
Committed: Wed Mar 28 17:01:13 2018 +0200
----------------------------------------------------------------------
.../flink/client/program/MiniClusterClient.java | 51 ++----
.../flink/runtime/dispatcher/Dispatcher.java | 175 +++++++++++--------
.../nonha/embedded/EmbeddedLeaderService.java | 20 ++-
.../runtime/jobmaster/JobManagerRunner.java | 121 +++++++------
.../runtime/dispatcher/DispatcherTest.java | 38 +++-
5 files changed, 233 insertions(+), 172 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/flink/blob/c0dddc1a/flink-clients/src/main/java/org/apache/flink/client/program/MiniClusterClient.java
----------------------------------------------------------------------
diff --git a/flink-clients/src/main/java/org/apache/flink/client/program/MiniClusterClient.java b/flink-clients/src/main/java/org/apache/flink/client/program/MiniClusterClient.java
index 802622e..a135359 100644
--- a/flink-clients/src/main/java/org/apache/flink/client/program/MiniClusterClient.java
+++ b/flink-clients/src/main/java/org/apache/flink/client/program/MiniClusterClient.java
@@ -20,27 +20,18 @@ package org.apache.flink.client.program;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.JobSubmissionResult;
-import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.client.JobStatusMessage;
import org.apache.flink.runtime.clusterframework.messages.GetClusterStatusResponse;
-import org.apache.flink.runtime.concurrent.FutureUtils;
-import org.apache.flink.runtime.concurrent.ScheduledExecutor;
-import org.apache.flink.runtime.concurrent.ScheduledExecutorServiceAdapter;
import org.apache.flink.runtime.executiongraph.AccessExecutionGraph;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.JobStatus;
import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalException;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.minicluster.MiniCluster;
-import org.apache.flink.runtime.rpc.akka.exceptions.AkkaRpcException;
-import org.apache.flink.runtime.rpc.exceptions.FencingTokenException;
-import org.apache.flink.runtime.util.ExecutorThreadFactory;
import org.apache.flink.runtime.util.LeaderConnectionInfo;
import org.apache.flink.runtime.util.LeaderRetrievalUtils;
-import org.apache.flink.util.ExceptionUtils;
-import org.apache.flink.util.FlinkException;
import org.apache.flink.util.OptionalFailure;
import org.apache.flink.util.SerializedValue;
@@ -54,9 +45,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.function.Supplier;
/**
* Client to interact with a {@link MiniCluster}.
@@ -64,10 +52,8 @@ import java.util.function.Supplier;
public class MiniClusterClient extends ClusterClient<MiniClusterClient.MiniClusterId> {
private final MiniCluster miniCluster;
- private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(4, new ExecutorThreadFactory("Flink-MiniClusterClient"));
- private final ScheduledExecutor scheduledExecutor = new ScheduledExecutorServiceAdapter(scheduledExecutorService);
- public MiniClusterClient(@Nonnull Configuration configuration, @Nonnull MiniCluster miniCluster) throws Exception {
+ public MiniClusterClient(@Nonnull Configuration configuration, @Nonnull MiniCluster miniCluster) {
super(configuration, miniCluster.getHighAvailabilityServices(), true);
this.miniCluster = miniCluster;
@@ -76,7 +62,6 @@ public class MiniClusterClient extends ClusterClient<MiniClusterClient.MiniClust
@Override
public void shutdown() throws Exception {
super.shutdown();
- scheduledExecutorService.shutdown();
}
@Override
@@ -104,32 +89,32 @@ public class MiniClusterClient extends ClusterClient<MiniClusterClient.MiniClust
@Override
public void cancel(JobID jobId) throws Exception {
- guardWithSingleRetry(() -> miniCluster.cancelJob(jobId), scheduledExecutor);
+ miniCluster.cancelJob(jobId).get();
}
@Override
public String cancelWithSavepoint(JobID jobId, @Nullable String savepointDirectory) throws Exception {
- return guardWithSingleRetry(() -> miniCluster.triggerSavepoint(jobId, savepointDirectory, true), scheduledExecutor).get();
+ return miniCluster.triggerSavepoint(jobId, savepointDirectory, true).get();
}
@Override
public void stop(JobID jobId) throws Exception {
- guardWithSingleRetry(() -> miniCluster.stopJob(jobId), scheduledExecutor).get();
+ miniCluster.stopJob(jobId).get();
}
@Override
- public CompletableFuture<String> triggerSavepoint(JobID jobId, @Nullable String savepointDirectory) throws FlinkException {
- return guardWithSingleRetry(() -> miniCluster.triggerSavepoint(jobId, savepointDirectory, false), scheduledExecutor);
+ public CompletableFuture<String> triggerSavepoint(JobID jobId, @Nullable String savepointDirectory) {
+ return miniCluster.triggerSavepoint(jobId, savepointDirectory, false);
}
@Override
- public CompletableFuture<Acknowledge> disposeSavepoint(String savepointPath) throws FlinkException {
- return guardWithSingleRetry(() -> miniCluster.disposeSavepoint(savepointPath), scheduledExecutor);
+ public CompletableFuture<Acknowledge> disposeSavepoint(String savepointPath) {
+ return miniCluster.disposeSavepoint(savepointPath);
}
@Override
- public CompletableFuture<Collection<JobStatusMessage>> listJobs() throws Exception {
- return guardWithSingleRetry(miniCluster::listJobs, scheduledExecutor);
+ public CompletableFuture<Collection<JobStatusMessage>> listJobs() {
+ return miniCluster.listJobs();
}
@Override
@@ -139,7 +124,7 @@ public class MiniClusterClient extends ClusterClient<MiniClusterClient.MiniClust
@Override
public Map<String, OptionalFailure<Object>> getAccumulators(JobID jobID, ClassLoader loader) throws Exception {
- AccessExecutionGraph executionGraph = guardWithSingleRetry(() -> miniCluster.getExecutionGraph(jobID), scheduledExecutor).get();
+ AccessExecutionGraph executionGraph = miniCluster.getExecutionGraph(jobID).get();
Map<String, SerializedValue<OptionalFailure<Object>>> accumulatorsSerialized = executionGraph.getAccumulatorsSerialized();
Map<String, OptionalFailure<Object>> result = new HashMap<>(accumulatorsSerialized.size());
for (Map.Entry<String, SerializedValue<OptionalFailure<Object>>> acc : accumulatorsSerialized.entrySet()) {
@@ -150,7 +135,7 @@ public class MiniClusterClient extends ClusterClient<MiniClusterClient.MiniClust
@Override
public CompletableFuture<JobStatus> getJobStatus(JobID jobId) {
- return guardWithSingleRetry(() -> miniCluster.getJobStatus(jobId), scheduledExecutor);
+ return miniCluster.getJobStatus(jobId);
}
@Override
@@ -202,16 +187,4 @@ public class MiniClusterClient extends ClusterClient<MiniClusterClient.MiniClust
enum MiniClusterId {
INSTANCE
}
-
- private static <X> CompletableFuture<X> guardWithSingleRetry(Supplier<CompletableFuture<X>> operation, ScheduledExecutor executor) {
- return FutureUtils.retryWithDelay(
- operation,
- 1,
- Time.milliseconds(500),
- throwable -> {
- Throwable actualException = ExceptionUtils.stripCompletionException(throwable);
- return actualException instanceof FencingTokenException || actualException instanceof AkkaRpcException;
- },
- executor);
- }
}
http://git-wip-us.apache.org/repos/asf/flink/blob/c0dddc1a/flink-runtime/src/main/java/org/apache/flink/runtime/dispatcher/Dispatcher.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/dispatcher/Dispatcher.java b/flink-runtime/src/main/java/org/apache/flink/runtime/dispatcher/Dispatcher.java
index 2b353c0..2b96a09 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/dispatcher/Dispatcher.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/dispatcher/Dispatcher.java
@@ -39,6 +39,7 @@ import org.apache.flink.runtime.jobmanager.SubmittedJobGraph;
import org.apache.flink.runtime.jobmanager.SubmittedJobGraphStore;
import org.apache.flink.runtime.jobmaster.JobManagerRunner;
import org.apache.flink.runtime.jobmaster.JobManagerSharedServices;
+import org.apache.flink.runtime.jobmaster.JobMasterGateway;
import org.apache.flink.runtime.jobmaster.JobNotFinishedException;
import org.apache.flink.runtime.jobmaster.JobResult;
import org.apache.flink.runtime.jobmaster.RescalingBehaviour;
@@ -64,6 +65,7 @@ import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.Preconditions;
+import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
@@ -75,9 +77,11 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
+import java.util.function.Function;
import java.util.stream.Collectors;
/**
@@ -341,35 +345,25 @@ public abstract class Dispatcher extends FencedRpcEndpoint<DispatcherId> impleme
@Override
public CompletableFuture<Acknowledge> cancelJob(JobID jobId, Time timeout) {
- JobManagerRunner jobManagerRunner = jobManagerRunners.get(jobId);
+ final CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getJobMasterGatewayFuture(jobId);
- if (jobManagerRunner == null) {
- return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
- } else {
- return jobManagerRunner.getJobManagerGateway().cancel(timeout);
- }
+ return jobMasterGatewayFuture.thenCompose((JobMasterGateway jobMasterGateway) -> jobMasterGateway.cancel(timeout));
}
@Override
public CompletableFuture<Acknowledge> stopJob(JobID jobId, Time timeout) {
- JobManagerRunner jobManagerRunner = jobManagerRunners.get(jobId);
+ final CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getJobMasterGatewayFuture(jobId);
- if (jobManagerRunner == null) {
- return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
- } else {
- return jobManagerRunner.getJobManagerGateway().stop(timeout);
- }
+ return jobMasterGatewayFuture.thenCompose((JobMasterGateway jobMasterGateway) -> jobMasterGateway.stop(timeout));
}
@Override
public CompletableFuture<Acknowledge> rescaleJob(JobID jobId, int newParallelism, RescalingBehaviour rescalingBehaviour, Time timeout) {
- JobManagerRunner jobManagerRunner = jobManagerRunners.get(jobId);
+ final CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getJobMasterGatewayFuture(jobId);
- if (jobManagerRunner == null) {
- return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
- } else {
- return jobManagerRunner.getJobManagerGateway().rescaleJob(newParallelism, rescalingBehaviour, timeout);
- }
+ return jobMasterGatewayFuture.thenCompose(
+ (JobMasterGateway jobMasterGateway) ->
+ jobMasterGateway.rescaleJob(newParallelism, rescalingBehaviour, timeout));
}
@Override
@@ -385,15 +379,12 @@ public abstract class Dispatcher extends FencedRpcEndpoint<DispatcherId> impleme
public CompletableFuture<ClusterOverview> requestClusterOverview(Time timeout) {
CompletableFuture<ResourceOverview> taskManagerOverviewFuture = resourceManagerGateway.requestResourceOverview(timeout);
- ArrayList<CompletableFuture<JobStatus>> jobStatus = new ArrayList<>(jobManagerRunners.size());
+ final List<CompletableFuture<Optional<JobStatus>>> optionalJobInformation = queryJobMastersForInformation(
+ (JobMasterGateway jobMasterGateway) -> jobMasterGateway.requestJobStatus(timeout));
- for (Map.Entry<JobID, JobManagerRunner> jobManagerRunnerEntry : jobManagerRunners.entrySet()) {
- CompletableFuture<JobStatus> jobStatusFuture = jobManagerRunnerEntry.getValue().getJobManagerGateway().requestJobStatus(timeout);
-
- jobStatus.add(jobStatusFuture);
- }
+ CompletableFuture<Collection<Optional<JobStatus>>> allOptionalJobsFuture = FutureUtils.combineAll(optionalJobInformation);
- CompletableFuture<Collection<JobStatus>> allJobsFuture = FutureUtils.combineAll(jobStatus);
+ CompletableFuture<Collection<JobStatus>> allJobsFuture = allOptionalJobsFuture.thenApply(this::flattenOptionalCollection);
final JobsOverview completedJobsOverview = archivedExecutionGraphStore.getStoredJobsOverview();
@@ -403,76 +394,79 @@ public abstract class Dispatcher extends FencedRpcEndpoint<DispatcherId> impleme
final JobsOverview allJobsOverview = JobsOverview.create(runningJobsStatus).combine(completedJobsOverview);
return new ClusterOverview(resourceOverview, allJobsOverview);
});
-
}
@Override
public CompletableFuture<MultipleJobsDetails> requestMultipleJobDetails(Time timeout) {
- final int numberJobsRunning = jobManagerRunners.size();
+ List<CompletableFuture<Optional<JobDetails>>> individualOptionalJobDetails = queryJobMastersForInformation(
+ (JobMasterGateway jobMasterGateway) -> jobMasterGateway.requestJobDetails(timeout));
- ArrayList<CompletableFuture<JobDetails>> individualJobDetails = new ArrayList<>(numberJobsRunning);
-
- for (JobManagerRunner jobManagerRunner : jobManagerRunners.values()) {
- individualJobDetails.add(jobManagerRunner.getJobManagerGateway().requestJobDetails(timeout));
- }
+ CompletableFuture<Collection<Optional<JobDetails>>> optionalCombinedJobDetails = FutureUtils.combineAll(
+ individualOptionalJobDetails);
- CompletableFuture<Collection<JobDetails>> combinedJobDetails = FutureUtils.combineAll(individualJobDetails);
+ CompletableFuture<Collection<JobDetails>> combinedJobDetails = optionalCombinedJobDetails.thenApply(this::flattenOptionalCollection);
final Collection<JobDetails> completedJobDetails = archivedExecutionGraphStore.getAvailableJobDetails();
return combinedJobDetails.thenApply(
(Collection<JobDetails> runningJobDetails) -> {
final Collection<JobDetails> allJobDetails = new ArrayList<>(completedJobDetails.size() + runningJobDetails.size());
+
allJobDetails.addAll(runningJobDetails);
allJobDetails.addAll(completedJobDetails);
+
return new MultipleJobsDetails(allJobDetails);
});
}
@Override
public CompletableFuture<JobStatus> requestJobStatus(JobID jobId, Time timeout) {
- final JobManagerRunner jobManagerRunner = jobManagerRunners.get(jobId);
- if (jobManagerRunner != null) {
- return jobManagerRunner.getJobManagerGateway().requestJobStatus(timeout);
- } else {
- final JobDetails jobDetails = archivedExecutionGraphStore.getAvailableJobDetails(jobId);
+ final CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getJobMasterGatewayFuture(jobId);
- if (jobDetails != null) {
- return CompletableFuture.completedFuture(jobDetails.getStatus());
- } else {
- return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
- }
- }
+ final CompletableFuture<JobStatus> jobStatusFuture = jobMasterGatewayFuture.thenCompose(
+ (JobMasterGateway jobMasterGateway) -> jobMasterGateway.requestJobStatus(timeout));
+
+ return jobStatusFuture.exceptionally(
+ (Throwable throwable) -> {
+ final JobDetails jobDetails = archivedExecutionGraphStore.getAvailableJobDetails(jobId);
+
+ // check whether it is a completed job
+ if (jobDetails == null) {
+ throw new CompletionException(ExceptionUtils.stripCompletionException(throwable));
+ } else {
+ return jobDetails.getStatus();
+ }
+ });
}
@Override
public CompletableFuture<OperatorBackPressureStatsResponse> requestOperatorBackPressureStats(
- final JobID jobId, final JobVertexID jobVertexId) {
- final JobManagerRunner jobManagerRunner = jobManagerRunners.get(jobId);
- if (jobManagerRunner == null) {
- return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
- } else {
- return jobManagerRunner.getJobManagerGateway().requestOperatorBackPressureStats(jobVertexId);
- }
+ final JobID jobId,
+ final JobVertexID jobVertexId) {
+ final CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getJobMasterGatewayFuture(jobId);
+
+ return jobMasterGatewayFuture.thenCompose((JobMasterGateway jobMasterGateway) -> jobMasterGateway.requestOperatorBackPressureStats(jobVertexId));
}
@Override
public CompletableFuture<ArchivedExecutionGraph> requestJob(JobID jobId, Time timeout) {
- final JobManagerRunner jobManagerRunner = jobManagerRunners.get(jobId);
+ final CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getJobMasterGatewayFuture(jobId);
- if (jobManagerRunner == null) {
- final ArchivedExecutionGraph serializableExecutionGraph = archivedExecutionGraphStore.get(jobId);
+ final CompletableFuture<ArchivedExecutionGraph> archivedExecutionGraphFuture = jobMasterGatewayFuture.thenCompose(
+ (JobMasterGateway jobMasterGateway) -> jobMasterGateway.requestJob(timeout));
- // check whether it is a completed job
- if (serializableExecutionGraph == null) {
- return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
- } else {
- return CompletableFuture.completedFuture(serializableExecutionGraph);
- }
- } else {
- return jobManagerRunner.getJobManagerGateway().requestJob(timeout);
- }
+ return archivedExecutionGraphFuture.exceptionally(
+ (Throwable throwable) -> {
+ final ArchivedExecutionGraph serializableExecutionGraph = archivedExecutionGraphStore.get(jobId);
+
+ // check whether it is a completed job
+ if (serializableExecutionGraph == null) {
+ throw new CompletionException(ExceptionUtils.stripCompletionException(throwable));
+ } else {
+ return serializableExecutionGraph;
+ }
+ });
}
@Override
@@ -517,13 +511,11 @@ public abstract class Dispatcher extends FencedRpcEndpoint<DispatcherId> impleme
final String targetDirectory,
final boolean cancelJob,
final Time timeout) {
- if (jobManagerRunners.containsKey(jobId)) {
- return jobManagerRunners.get(jobId)
- .getJobManagerGateway()
- .triggerSavepoint(targetDirectory, cancelJob, timeout);
- } else {
- return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
- }
+ final CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getJobMasterGatewayFuture(jobId);
+
+ return jobMasterGatewayFuture.thenCompose(
+ (JobMasterGateway jobMasterGateway) ->
+ jobMasterGateway.triggerSavepoint(targetDirectory, cancelJob, timeout));
}
/**
@@ -644,6 +636,49 @@ public abstract class Dispatcher extends FencedRpcEndpoint<DispatcherId> impleme
jobManagerRunnerTerminationFuture));
}
+ private CompletableFuture<JobMasterGateway> getJobMasterGatewayFuture(JobID jobId) {
+ final JobManagerRunner jobManagerRunner = jobManagerRunners.get(jobId);
+
+ if (jobManagerRunner == null) {
+ return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
+ } else {
+ final CompletableFuture<JobMasterGateway> leaderGatewayFuture = jobManagerRunner.getLeaderGatewayFuture();
+ return leaderGatewayFuture.thenApplyAsync(
+ (JobMasterGateway jobMasterGateway) -> {
+ // check whether the retrieved JobMasterGateway belongs still to a running JobMaster
+ if (jobManagerRunners.containsKey(jobId)) {
+ return jobMasterGateway;
+ } else {
+ throw new CompletionException(new FlinkJobNotFoundException(jobId));
+ }
+ },
+ getMainThreadExecutor());
+ }
+ }
+
+ private <T> List<T> flattenOptionalCollection(Collection<Optional<T>> optionalCollection) {
+ return optionalCollection.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
+ }
+
+ @Nonnull
+ private <T> List<CompletableFuture<Optional<T>>> queryJobMastersForInformation(Function<JobMasterGateway, CompletableFuture<T>> queryFunction) {
+ final int numberJobsRunning = jobManagerRunners.size();
+
+ ArrayList<CompletableFuture<Optional<T>>> optionalJobInformation = new ArrayList<>(
+ numberJobsRunning);
+
+ for (JobID jobId : jobManagerRunners.keySet()) {
+ final CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getJobMasterGatewayFuture(jobId);
+
+ final CompletableFuture<Optional<T>> optionalRequest = jobMasterGatewayFuture
+ .thenCompose(queryFunction::apply)
+ .handle((T value, Throwable throwable) -> Optional.ofNullable(value));
+
+ optionalJobInformation.add(optionalRequest);
+ }
+ return optionalJobInformation;
+ }
+
//------------------------------------------------------
// Leader contender
//------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/flink/blob/c0dddc1a/flink-runtime/src/main/java/org/apache/flink/runtime/highavailability/nonha/embedded/EmbeddedLeaderService.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/highavailability/nonha/embedded/EmbeddedLeaderService.java b/flink-runtime/src/main/java/org/apache/flink/runtime/highavailability/nonha/embedded/EmbeddedLeaderService.java
index ce964a3..f89cd2c 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/highavailability/nonha/embedded/EmbeddedLeaderService.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/highavailability/nonha/embedded/EmbeddedLeaderService.java
@@ -212,7 +212,7 @@ public class EmbeddedLeaderService {
}
/**
- * Callback from leader contenders when they confirm a leader grant
+ * Callback from leader contenders when they confirm a leader grant.
*/
void confirmLeader(final EmbeddedLeaderElectionService service, final UUID leaderSessionId) {
synchronized (lock) {
@@ -222,7 +222,7 @@ public class EmbeddedLeaderService {
}
try {
- // check if the confirmation is for the same grant, or whether it is a stale grant
+ // check if the confirmation is for the same grant, or whether it is a stale grant
if (service == currentLeaderProposed && currentLeaderSessionId.equals(leaderSessionId)) {
final String address = service.contender.getAddress();
LOG.info("Received confirmation of leadership for leader {} , session={}", address, leaderSessionId);
@@ -231,7 +231,6 @@ public class EmbeddedLeaderService {
currentLeaderConfirmed = service;
currentLeaderAddress = address;
currentLeaderProposed = null;
- service.isLeader = true;
// notify all listeners
for (EmbeddedLeaderRetrievalService listener : listeners) {
@@ -275,7 +274,7 @@ public class EmbeddedLeaderService {
leaderService.contender, leaderService.contender.getAddress());
notificationExecutor.execute(
- new GrantLeadershipCall(leaderService.contender, leaderSessionId, LOG));
+ new GrantLeadershipCall(leaderService, leaderSessionId, LOG));
}
}
}
@@ -328,7 +327,7 @@ public class EmbeddedLeaderService {
}
// ------------------------------------------------------------------------
- // election and retrieval service implementations
+ // election and retrieval service implementations
// ------------------------------------------------------------------------
private class EmbeddedLeaderElectionService implements LeaderElectionService {
@@ -440,28 +439,33 @@ public class EmbeddedLeaderService {
private static class GrantLeadershipCall implements Runnable {
- private final LeaderContender contender;
+ private final EmbeddedLeaderElectionService leaderElectionService;
private final UUID leaderSessionId;
private final Logger logger;
GrantLeadershipCall(
- LeaderContender contender,
+ EmbeddedLeaderElectionService leaderElectionService,
UUID leaderSessionId,
Logger logger) {
- this.contender = checkNotNull(contender);
+ this.leaderElectionService = checkNotNull(leaderElectionService);
this.leaderSessionId = checkNotNull(leaderSessionId);
this.logger = checkNotNull(logger);
}
@Override
public void run() {
+ leaderElectionService.isLeader = true;
+
+ final LeaderContender contender = leaderElectionService.contender;
+
try {
contender.grantLeadership(leaderSessionId);
}
catch (Throwable t) {
logger.warn("Error granting leadership to contender", t);
contender.handleError(t instanceof Exception ? (Exception) t : new Exception(t));
+ leaderElectionService.isLeader = false;
}
}
}
http://git-wip-us.apache.org/repos/asf/flink/blob/c0dddc1a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobManagerRunner.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobManagerRunner.java b/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobManagerRunner.java
index 3b44ed7..034232e 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobManagerRunner.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobManagerRunner.java
@@ -76,7 +76,7 @@ public class JobManagerRunner implements LeaderContender, OnCompletionActions, F
private final JobManagerSharedServices jobManagerSharedServices;
- private final JobMaster jobManager;
+ private final JobMaster jobMaster;
private final Time rpcTimeout;
@@ -87,6 +87,8 @@ public class JobManagerRunner implements LeaderContender, OnCompletionActions, F
/** flag marking the runner as shut down. */
private volatile boolean shutdown;
+ private volatile CompletableFuture<JobMasterGateway> leaderGatewayFuture;
+
// ------------------------------------------------------------------------
/**
@@ -139,8 +141,10 @@ public class JobManagerRunner implements LeaderContender, OnCompletionActions, F
this.rpcTimeout = jobMasterConfiguration.getRpcTimeout();
+ this.leaderGatewayFuture = new CompletableFuture<>();
+
// now start the JobManager
- this.jobManager = new JobMaster(
+ this.jobMaster = new JobMaster(
rpcService,
jobMasterConfiguration,
resourceId,
@@ -166,8 +170,8 @@ public class JobManagerRunner implements LeaderContender, OnCompletionActions, F
// Getter
//----------------------------------------------------------------------------------------------
- public JobMasterGateway getJobManagerGateway() {
- return jobManager.getSelfGateway(JobMasterGateway.class);
+ public CompletableFuture<JobMasterGateway> getLeaderGatewayFuture() {
+ return leaderGatewayFuture;
}
public JobGraph getJobGraph() {
@@ -185,8 +189,7 @@ public class JobManagerRunner implements LeaderContender, OnCompletionActions, F
public void start() throws Exception {
try {
leaderElectionService.start(this);
- }
- catch (Exception e) {
+ } catch (Exception e) {
log.error("Could not start the JobManager because the leader election service did not start.", e);
throw new Exception("Could not start the leader election service.", e);
}
@@ -198,9 +201,11 @@ public class JobManagerRunner implements LeaderContender, OnCompletionActions, F
if (!shutdown) {
shutdown = true;
- jobManager.shutDown();
+ setNewLeaderGatewayFuture();
+ leaderGatewayFuture.completeExceptionally(new FlinkException("JobMaster has been shut down."));
- final CompletableFuture<Void> jobManagerTerminationFuture = jobManager.getTerminationFuture();
+ jobMaster.shutDown();
+ final CompletableFuture<Void> jobManagerTerminationFuture = jobMaster.getTerminationFuture();
jobManagerTerminationFuture.whenComplete(
(Void ignored, Throwable throwable) -> {
@@ -294,54 +299,47 @@ public class JobManagerRunner implements LeaderContender, OnCompletionActions, F
return;
}
- log.info("JobManager runner for job {} ({}) was granted leadership with session id {} at {}.",
- jobGraph.getName(), jobGraph.getJobID(), leaderSessionID, getAddress());
-
- // The operation may be blocking, but since this runner is idle before it been granted the leadership,
- // it's okay that job manager wait for the operation complete
- leaderElectionService.confirmLeaderSessionID(leaderSessionID);
-
- final JobSchedulingStatus schedulingStatus;
try {
- schedulingStatus = runningJobsRegistry.getJobSchedulingStatus(jobGraph.getJobID());
- }
- catch (Throwable t) {
- log.error("Could not access status (running/finished) of job {}. ", jobGraph.getJobID(), t);
- onFatalError(t);
- return;
+ verifyJobSchedulingStatusAndStartJobManager(leaderSessionID);
+ } catch (Exception e) {
+ onFatalError(new FlinkException("Could not start the JobMaster.", e));
}
+ }
+ }
- if (schedulingStatus == JobSchedulingStatus.DONE) {
- log.info("Granted leader ship but job {} has been finished. ", jobGraph.getJobID());
- jobFinishedByOther();
- return;
- }
+ private void verifyJobSchedulingStatusAndStartJobManager(UUID leaderSessionId) throws Exception {
+ final JobSchedulingStatus jobSchedulingStatus = runningJobsRegistry.getJobSchedulingStatus(jobGraph.getJobID());
+
+ if (jobSchedulingStatus == JobSchedulingStatus.DONE) {
+ log.info("Granted leader ship but job {} has been finished. ", jobGraph.getJobID());
+ jobFinishedByOther();
+ } else {
+ log.info("JobManager runner for job {} ({}) was granted leadership with session id {} at {}.",
+ jobGraph.getName(), jobGraph.getJobID(), leaderSessionId, getAddress());
+
+ runningJobsRegistry.setJobRunning(jobGraph.getJobID());
+
+ final CompletableFuture<Acknowledge> startFuture = jobMaster.start(new JobMasterId(leaderSessionId), rpcTimeout);
+ final CompletableFuture<JobMasterGateway> currentLeaderGatewayFuture = leaderGatewayFuture;
- // Double check the leadership after we confirm that, there is a small chance that multiple
- // job managers schedule the same job after if they try to recover at the same time.
- // This will eventually be noticed, but can not be ruled out from the beginning.
- if (leaderElectionService.hasLeadership()) {
- try {
- // Now set the running status is after getting leader ship and
- // set finished status after job in terminated status.
- // So if finding the job is running, it means someone has already run the job, need recover.
- if (schedulingStatus == JobSchedulingStatus.PENDING) {
- runningJobsRegistry.setJobRunning(jobGraph.getJobID());
+ startFuture.whenCompleteAsync(
+ (Acknowledge ack, Throwable throwable) -> {
+ if (throwable != null) {
+ onFatalError(new FlinkException("Could not start the job manager.", throwable));
+ } else {
+ confirmLeaderSessionIdIfStillLeader(leaderSessionId, currentLeaderGatewayFuture);
}
+ },
+ jobManagerSharedServices.getScheduledExecutorService());
+ }
+ }
- CompletableFuture<Acknowledge> startingFuture = jobManager.start(new JobMasterId(leaderSessionID), rpcTimeout);
-
- startingFuture.whenCompleteAsync(
- (Acknowledge ack, Throwable throwable) -> {
- if (throwable != null) {
- onFatalError(new Exception("Could not start the job manager.", throwable));
- }
- },
- jobManagerSharedServices.getScheduledExecutorService());
- } catch (Exception e) {
- onFatalError(new Exception("Could not start the job manager.", e));
- }
- }
+ private void confirmLeaderSessionIdIfStillLeader(UUID leaderSessionId, CompletableFuture<JobMasterGateway> currentLeaderGatewayFuture) {
+ if (leaderElectionService.hasLeadership()) {
+ currentLeaderGatewayFuture.complete(jobMaster.getSelfGateway(JobMasterGateway.class));
+ leaderElectionService.confirmLeaderSessionID(leaderSessionId);
+ } else {
+ log.debug("Ignoring confirmation of leader session id because {} is no longer the leader.", getAddress());
}
}
@@ -356,7 +354,9 @@ public class JobManagerRunner implements LeaderContender, OnCompletionActions, F
log.info("JobManager for job {} ({}) was revoked leadership at {}.",
jobGraph.getName(), jobGraph.getJobID(), getAddress());
- CompletableFuture<Acknowledge> suspendFuture = jobManager.suspend(new FlinkException("JobManager is no longer the leader."), rpcTimeout);
+ setNewLeaderGatewayFuture();
+
+ CompletableFuture<Acknowledge> suspendFuture = jobMaster.suspend(new FlinkException("JobManager is no longer the leader."), rpcTimeout);
suspendFuture.whenCompleteAsync(
(Acknowledge ack, Throwable throwable) -> {
@@ -368,9 +368,26 @@ public class JobManagerRunner implements LeaderContender, OnCompletionActions, F
}
}
+ private void setNewLeaderGatewayFuture() {
+ final CompletableFuture<JobMasterGateway> oldLeaderGatewayFuture = leaderGatewayFuture;
+
+ leaderGatewayFuture = new CompletableFuture<>();
+
+ if (!oldLeaderGatewayFuture.isDone()) {
+ leaderGatewayFuture.whenComplete(
+ (JobMasterGateway jobMasterGateway, Throwable throwable) -> {
+ if (throwable != null) {
+ oldLeaderGatewayFuture.completeExceptionally(throwable);
+ } else {
+ oldLeaderGatewayFuture.complete(jobMasterGateway);
+ }
+ });
+ }
+ }
+
@Override
public String getAddress() {
- return jobManager.getAddress();
+ return jobMaster.getAddress();
}
@Override
http://git-wip-us.apache.org/repos/asf/flink/blob/c0dddc1a/flink-runtime/src/test/java/org/apache/flink/runtime/dispatcher/DispatcherTest.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/dispatcher/DispatcherTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/dispatcher/DispatcherTest.java
index fb1ec63..cafdf54 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/dispatcher/DispatcherTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/dispatcher/DispatcherTest.java
@@ -96,6 +96,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.hamcrest.Matchers.contains;
@@ -103,11 +104,13 @@ import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
+import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
@@ -368,13 +371,13 @@ public class DispatcherTest extends TestLogger {
*/
@Test
public void testSavepointDisposal() throws Exception {
+ final URI externalPointer = createTestingSavepoint();
+ final Path savepointPath = Paths.get(externalPointer);
+
final DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class);
dispatcherLeaderElectionService.isLeader(UUID.randomUUID()).get();
- final URI externalPointer = createTestingSavepoint();
- final Path savepointPath = Paths.get(externalPointer);
-
assertThat(Files.exists(savepointPath), is(true));
dispatcherGateway.disposeSavepoint(externalPointer.toString(), TIMEOUT).get();
@@ -397,6 +400,35 @@ public class DispatcherTest extends TestLogger {
final CompletedCheckpointStorageLocation completedCheckpointStorageLocation = metadataOutputStream.closeAndFinalizeCheckpoint();
return new URI(completedCheckpointStorageLocation.getExternalPointer());
+
+ }
+
+ /**
+ * Tests that we wait until the JobMaster has gained leader ship before sending requests
+ * to it. See FLINK-8887.
+ */
+ @Test
+ public void testWaitingForJobMasterLeadership() throws ExecutionException, InterruptedException {
+ final DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class);
+
+ dispatcherLeaderElectionService.isLeader(UUID.randomUUID()).get();
+
+ dispatcherGateway.submitJob(jobGraph, TIMEOUT).get();
+
+ final CompletableFuture<JobStatus> jobStatusFuture = dispatcherGateway.requestJobStatus(jobGraph.getJobID(), TIMEOUT);
+
+ assertThat(jobStatusFuture.isDone(), is(false));
+
+ try {
+ jobStatusFuture.get(10, TimeUnit.MILLISECONDS);
+ fail("Should not complete.");
+ } catch (TimeoutException ignored) {
+ // ignored
+ }
+
+ jobMasterLeaderElectionService.isLeader(UUID.randomUUID()).get();
+
+ assertThat(jobStatusFuture.get(), notNullValue());
}
private static class TestingDispatcher extends Dispatcher {