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/29 16:08:26 UTC

[5/6] flink git commit: [FLINK-9097] Fail fatally if job submission fails when recovering jobs

[FLINK-9097] Fail fatally if job submission fails when recovering jobs

In order to not drop jobs, we have to fail fatally if a job submission fails when
recovering jobs. In HA mode, this will restart the Dispatcher and let it retry
to recover all jobs.

This closes #5774.


Project: http://git-wip-us.apache.org/repos/asf/flink/repo
Commit: http://git-wip-us.apache.org/repos/asf/flink/commit/cc190a64
Tree: http://git-wip-us.apache.org/repos/asf/flink/tree/cc190a64
Diff: http://git-wip-us.apache.org/repos/asf/flink/diff/cc190a64

Branch: refs/heads/master
Commit: cc190a6457cdf6186ea8e449f7b38be04761af8b
Parents: 3f767a6
Author: Till Rohrmann <tr...@apache.org>
Authored: Tue Mar 27 10:59:54 2018 +0200
Committer: Till Rohrmann <tr...@apache.org>
Committed: Thu Mar 29 18:07:43 2018 +0200

----------------------------------------------------------------------
 .../flink/runtime/dispatcher/Dispatcher.java    | 194 +++++++++++--------
 .../runtime/dispatcher/DispatcherTest.java      | 114 +++++++----
 2 files changed, 180 insertions(+), 128 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/flink/blob/cc190a64/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 6aeebf4..b0e9985 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
@@ -230,90 +230,89 @@ public abstract class Dispatcher extends FencedRpcEndpoint<DispatcherId> impleme
 
 	@Override
 	public CompletableFuture<Acknowledge> submitJob(JobGraph jobGraph, Time timeout) {
-
 		final JobID jobId = jobGraph.getJobID();
 
-		log.info("Submitting job {} ({}).", jobGraph.getJobID(), jobGraph.getName());
-
-		final RunningJobsRegistry.JobSchedulingStatus jobSchedulingStatus;
+		log.info("Submitting job {} ({}).", jobId, jobGraph.getName());
 
 		try {
-			jobSchedulingStatus = runningJobsRegistry.getJobSchedulingStatus(jobId);
-		} catch (IOException e) {
-			log.warn("Cannot retrieve job status for {}.", jobId, e);
-			return FutureUtils.completedExceptionally(
-				new JobSubmissionException(jobId, "Could not retrieve the job status.", e));
-		}
+			final RunningJobsRegistry.JobSchedulingStatus jobSchedulingStatus = runningJobsRegistry.getJobSchedulingStatus(jobId);
 
-		if (jobSchedulingStatus != RunningJobsRegistry.JobSchedulingStatus.DONE &&
-			!jobManagerRunners.containsKey(jobId)) {
-			try {
-				submittedJobGraphStore.putJobGraph(new SubmittedJobGraph(jobGraph, null));
-			} catch (Exception e) {
-				log.warn("Cannot persist JobGraph.", e);
+			if (jobSchedulingStatus == RunningJobsRegistry.JobSchedulingStatus.DONE || jobManagerRunners.containsKey(jobId)) {
 				return FutureUtils.completedExceptionally(
-					new JobSubmissionException(jobId, "Could not persist JobGraph.", e));
+					new JobSubmissionException(jobId, String.format("Job has already been submitted and is in state %s.", jobSchedulingStatus)));
+			} else {
+				persistAndRunJob(jobGraph);
+
+				return CompletableFuture.completedFuture(Acknowledge.get());
 			}
+		} catch (Exception e) {
+			return FutureUtils.completedExceptionally(new FlinkException(String.format("Failed to submit job %s.", jobId), e));
+		}
+	}
 
-			final JobManagerRunner jobManagerRunner;
+	private void persistAndRunJob(JobGraph jobGraph) throws Exception {
+		submittedJobGraphStore.putJobGraph(new SubmittedJobGraph(jobGraph, null));
 
+		try {
+			runJob(jobGraph);
+		} catch (Exception e) {
 			try {
-				jobManagerRunner = jobManagerRunnerFactory.createJobManagerRunner(
-					ResourceID.generate(),
-					jobGraph,
-					configuration,
-					getRpcService(),
-					highAvailabilityServices,
-					heartbeatServices,
-					blobServer,
-					jobManagerSharedServices,
-					new DefaultJobManagerJobMetricGroupFactory(jobManagerMetricGroup),
-					fatalErrorHandler);
-
-				jobManagerRunner.getResultFuture().whenCompleteAsync(
-					(ArchivedExecutionGraph archivedExecutionGraph, Throwable throwable) -> {
-						// check if we are still the active JobManagerRunner by checking the identity
-						//noinspection ObjectEquality
-						if (jobManagerRunner == jobManagerRunners.get(jobId)) {
-							if (archivedExecutionGraph != null) {
-								jobReachedGloballyTerminalState(archivedExecutionGraph);
-							} else {
-								final Throwable strippedThrowable = ExceptionUtils.stripCompletionException(throwable);
-
-								if (strippedThrowable instanceof JobNotFinishedException) {
-									jobNotFinished(jobId);
-								} else {
-									onFatalError(new FlinkException("JobManagerRunner for job " + jobId + " failed.", strippedThrowable));
-								}
-							}
-						} else {
-							log.debug("There is a newer JobManagerRunner for the job {}.", jobId);
-						}
-					}, getMainThreadExecutor());
+				submittedJobGraphStore.removeJobGraph(jobGraph.getJobID());
+			} catch (Exception ie) {
+				e.addSuppressed(ie);
+			}
 
-				jobManagerRunner.start();
-			} catch (Exception e) {
-				try {
-					// We should only remove a job from the submitted job graph store
-					// if the initial submission failed. Never in case of a recovery
-					submittedJobGraphStore.removeJobGraph(jobId);
-				} catch (Throwable t) {
-					log.warn("Cannot remove job graph from submitted job graph store.", t);
-					e.addSuppressed(t);
-				}
+			throw e;
+		}
+	}
 
-				return FutureUtils.completedExceptionally(
-					new JobSubmissionException(jobId, "Could not start JobManager.", e));
-			}
+	private void runJob(JobGraph jobGraph) throws Exception {
+		Preconditions.checkState(!jobManagerRunners.containsKey(jobGraph.getJobID()));
 
-			jobManagerRunners.put(jobId, jobManagerRunner);
+		final JobManagerRunner jobManagerRunner = createJobManagerRunner(jobGraph);
 
-			return CompletableFuture.completedFuture(Acknowledge.get());
-		} else {
-			return FutureUtils.completedExceptionally(
-				new JobSubmissionException(jobId, "Job has already been submitted and " +
-					"is currently in state " + jobSchedulingStatus + '.'));
-		}
+		jobManagerRunner.start();
+
+		jobManagerRunners.put(jobGraph.getJobID(), jobManagerRunner);
+	}
+
+	private JobManagerRunner createJobManagerRunner(JobGraph jobGraph) throws Exception {
+		final JobID jobId = jobGraph.getJobID();
+
+		final JobManagerRunner jobManagerRunner = jobManagerRunnerFactory.createJobManagerRunner(
+			ResourceID.generate(),
+			jobGraph,
+			configuration,
+			getRpcService(),
+			highAvailabilityServices,
+			heartbeatServices,
+			blobServer,
+			jobManagerSharedServices,
+			new DefaultJobManagerJobMetricGroupFactory(jobManagerMetricGroup),
+			fatalErrorHandler);
+
+		jobManagerRunner.getResultFuture().whenCompleteAsync(
+			(ArchivedExecutionGraph archivedExecutionGraph, Throwable throwable) -> {
+				// check if we are still the active JobManagerRunner by checking the identity
+				//noinspection ObjectEquality
+				if (jobManagerRunner == jobManagerRunners.get(jobId)) {
+					if (archivedExecutionGraph != null) {
+						jobReachedGloballyTerminalState(archivedExecutionGraph);
+					} else {
+						final Throwable strippedThrowable = ExceptionUtils.stripCompletionException(throwable);
+
+						if (strippedThrowable instanceof JobNotFinishedException) {
+							jobNotFinished(jobId);
+						} else {
+							jobMasterFailed(jobId, strippedThrowable);
+						}
+					}
+				} else {
+					log.debug("There is a newer JobManagerRunner for the job {}.", jobId);
+				}
+			}, getMainThreadExecutor());
+
+		return jobManagerRunner;
 	}
 
 	@Override
@@ -526,7 +525,7 @@ public abstract class Dispatcher extends FencedRpcEndpoint<DispatcherId> impleme
 	 * @param jobId JobID identifying the job to clean up
 	 * @param cleanupHA True iff HA data shall also be cleaned up
 	 */
-	private void removeJob(JobID jobId, boolean cleanupHA) throws Exception {
+	private void removeJob(JobID jobId, boolean cleanupHA) {
 		JobManagerRunner jobManagerRunner = jobManagerRunners.remove(jobId);
 
 		if (jobManagerRunner != null) {
@@ -537,7 +536,11 @@ public abstract class Dispatcher extends FencedRpcEndpoint<DispatcherId> impleme
 		jobManagerMetricGroup.removeJob(jobId);
 
 		if (cleanupHA) {
-			submittedJobGraphStore.removeJobGraph(jobId);
+			try {
+				submittedJobGraphStore.removeJobGraph(jobId);
+			} catch (Exception e) {
+				log.warn("Could not properly remove job {} from submitted job graph store.", jobId);
+			}
 		}
 
 		// TODO: remove job related files from blob server
@@ -577,9 +580,7 @@ public abstract class Dispatcher extends FencedRpcEndpoint<DispatcherId> impleme
 
 				for (JobID jobId : jobIds) {
 					try {
-						SubmittedJobGraph submittedJobGraph = submittedJobGraphStore.recoverJobGraph(jobId);
-
-						runAsync(() -> submitJob(submittedJobGraph.getJobGraph(), RpcUtils.INF_TIMEOUT));
+						recoverJob(jobId);
 					} catch (Exception e) {
 						onFatalError(new FlinkException("Could not recover the job graph for " + jobId + '.', e));
 					}
@@ -587,6 +588,31 @@ public abstract class Dispatcher extends FencedRpcEndpoint<DispatcherId> impleme
 			});
 	}
 
+	private void recoverJob(JobID jobId) throws Exception {
+		SubmittedJobGraph submittedJobGraph = submittedJobGraphStore.recoverJobGraph(jobId);
+
+		if (submittedJobGraph != null) {
+			final CompletableFuture<Void> runJobFuture = callAsync(
+				() -> {
+					runJob(submittedJobGraph.getJobGraph());
+					return null;
+				},
+				RpcUtils.INF_TIMEOUT);
+
+			runJobFuture.whenComplete(
+				(Void ignored, Throwable throwable) -> {
+					if (throwable != null) {
+						onFatalError(new FlinkException(
+							String.format("Could not run the recovered job %s.", jobId),
+							throwable));
+					}
+				});
+		} else {
+			log.warn("Could not find job {} in submitted job graph store. Ignoring recover call.", jobId);
+		}
+
+	}
+
 	protected void onFatalError(Throwable throwable) {
 		fatalErrorHandler.onFatalError(throwable);
 	}
@@ -612,21 +638,19 @@ public abstract class Dispatcher extends FencedRpcEndpoint<DispatcherId> impleme
 
 		final JobID jobId = archivedExecutionGraph.getJobID();
 
-		try {
-			removeJob(jobId, true);
-		} catch (Exception e) {
-			log.warn("Could not properly remove job {} from the dispatcher.", jobId, e);
-		}
+		removeJob(jobId, true);
 	}
 
 	protected void jobNotFinished(JobID jobId) {
 		log.info("Job {} was not finished by JobManager.", jobId);
 
-		try {
-			removeJob(jobId, false);
-		} catch (Exception e) {
-			log.warn("Could not properly remove job {} from the dispatcher.", jobId, e);
-		}
+		removeJob(jobId, false);
+	}
+
+	private void jobMasterFailed(JobID jobId, Throwable cause) {
+		// we fail fatally in case of a JobMaster failure in order to restart the
+		// dispatcher to recover the jobs again. This only works in HA mode, though
+		onFatalError(new FlinkException(String.format("JobMaster for job %s failed.", jobId), cause));
 	}
 
 	private void registerOrphanedJobManagerTerminationFuture(CompletableFuture<Void> jobManagerRunnerTerminationFuture) {

http://git-wip-us.apache.org/repos/asf/flink/blob/cc190a64/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 9ff901a..6d8392e 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
@@ -144,6 +144,8 @@ public class DispatcherTest extends TestLogger {
 
 	private RunningJobsRegistry runningJobsRegistry;
 
+	private CountDownLatch createdJobManagerRunnerLatch;
+
 	private Configuration configuration;
 
 	/** Instance under test. */
@@ -191,6 +193,7 @@ public class DispatcherTest extends TestLogger {
 			BlobServerOptions.STORAGE_DIRECTORY,
 			temporaryFolder.newFolder().getAbsolutePath());
 
+		createdJobManagerRunnerLatch = new CountDownLatch(2);
 		dispatcher = new TestingDispatcher(
 			rpcService,
 			Dispatcher.DISPATCHER_NAME + '_' + name.getMethodName(),
@@ -202,8 +205,8 @@ public class DispatcherTest extends TestLogger {
 			UnregisteredMetricGroups.createUnregisteredJobManagerMetricGroup(),
 			null,
 			new MemoryArchivedExecutionGraphStore(),
-			fatalErrorHandler,
-			TEST_JOB_ID);
+			new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch),
+			fatalErrorHandler);
 
 		dispatcher.start();
 	}
@@ -251,16 +254,7 @@ public class DispatcherTest extends TestLogger {
 				return jobIds;
 			});
 
-		UUID expectedLeaderSessionId = UUID.randomUUID();
-
-		assertNull(dispatcherLeaderElectionService.getConfirmationFuture());
-
-		dispatcherLeaderElectionService.isLeader(expectedLeaderSessionId);
-
-		UUID actualLeaderSessionId = dispatcherLeaderElectionService.getConfirmationFuture()
-			.get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
-
-		assertEquals(expectedLeaderSessionId, actualLeaderSessionId);
+		electDispatcher();
 
 		// wait that we asked the SubmittedJobGraphStore for the stored jobs
 		jobIdsFuture.get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
@@ -292,7 +286,7 @@ public class DispatcherTest extends TestLogger {
 		runningJobsRegistry.clearJob(TEST_JOB_ID);
 		submittedJobGraphStore.putJobGraph(submittedJobGraph);
 		dispatcher.onAddedJobGraph(TEST_JOB_ID);
-		dispatcher.submitJobLatch.await();
+		createdJobManagerRunnerLatch.await();
 		assertThat(dispatcherGateway.listJobs(TIMEOUT).get(), hasSize(1));
 	}
 
@@ -364,7 +358,7 @@ public class DispatcherTest extends TestLogger {
 		dispatcherLeaderElectionService.isLeader(UUID.randomUUID()).get();
 
 		// wait until we have recovered the job
-		dispatcher.submitJobLatch.await();
+		createdJobManagerRunnerLatch.await();
 
 		// check whether the job has been recovered
 		final Collection<JobID> jobIds = dispatcherGateway.listJobs(TIMEOUT).get();
@@ -450,16 +444,7 @@ public class DispatcherTest extends TestLogger {
 				throw testException;
 			});
 
-		UUID expectedLeaderSessionId = UUID.randomUUID();
-
-		assertNull(dispatcherLeaderElectionService.getConfirmationFuture());
-
-		dispatcherLeaderElectionService.isLeader(expectedLeaderSessionId);
-
-		UUID actualLeaderSessionId = dispatcherLeaderElectionService.getConfirmationFuture()
-			.get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
-
-		assertEquals(expectedLeaderSessionId, actualLeaderSessionId);
+		electDispatcher();
 
 		// we expect that a fatal error occurred
 		final Throwable error = fatalErrorHandler.getErrorFuture().get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
@@ -485,6 +470,39 @@ public class DispatcherTest extends TestLogger {
 				throw testException;
 			});
 
+		electDispatcher();
+
+		// we expect that a fatal error occurred
+		final Throwable error = fatalErrorHandler.getErrorFuture().get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
+
+		assertThat(ExceptionUtils.findThrowableWithMessage(error, testException.getMessage()).isPresent(), is(true));
+
+		fatalErrorHandler.clearError();
+	}
+
+	/**
+	 * Tests that the {@link Dispatcher} fails fatally if the job submission of a recovered job fails.
+	 * See FLINK-9097.
+	 */
+	@Test
+	public void testJobSubmissionErrorAfterJobRecovery() throws Exception {
+		final FlinkException testException = new FlinkException("Test exception");
+
+		final JobGraph failingJobGraph = createFailingJobGraph(testException);
+
+		final SubmittedJobGraph submittedJobGraph = new SubmittedJobGraph(failingJobGraph, null);
+		submittedJobGraphStore.putJobGraph(submittedJobGraph);
+
+		electDispatcher();
+
+		final Throwable error = fatalErrorHandler.getErrorFuture().get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
+
+		assertThat(ExceptionUtils.findThrowableWithMessage(error, testException.getMessage()).isPresent(), is(true));
+
+		fatalErrorHandler.clearError();
+	}
+
+	private void electDispatcher() throws InterruptedException, ExecutionException, java.util.concurrent.TimeoutException {
 		UUID expectedLeaderSessionId = UUID.randomUUID();
 
 		assertNull(dispatcherLeaderElectionService.getConfirmationFuture());
@@ -495,19 +513,33 @@ public class DispatcherTest extends TestLogger {
 			.get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
 
 		assertEquals(expectedLeaderSessionId, actualLeaderSessionId);
+	}
 
-		// we expect that a fatal error occurred
-		final Throwable error = fatalErrorHandler.getErrorFuture().get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
+	private JobGraph createFailingJobGraph(Exception failureCause) {
+		final FailingJobVertex jobVertex = new FailingJobVertex("Failing JobVertex", failureCause);
+		jobVertex.setInvokableClass(NoOpInvokable.class);
+		return new JobGraph(jobGraph.getJobID(), "Failing JobGraph", jobVertex);
+	}
 
-		assertThat(ExceptionUtils.findThrowableWithMessage(error, testException.getMessage()).isPresent(), is(true));
+	private static class FailingJobVertex extends JobVertex {
 
-		fatalErrorHandler.clearError();
+		private static final long serialVersionUID = 3218428829168840760L;
+
+		private final Exception failure;
+
+		private FailingJobVertex(String name, Exception failure) {
+			super(name);
+			this.failure = failure;
+		}
+
+		@Override
+		public void initializeOnMaster(ClassLoader loader) throws Exception {
+			throw failure;
+		}
 	}
 
 	private static class TestingDispatcher extends Dispatcher {
 
-		private final CountDownLatch submitJobLatch = new CountDownLatch(2);
-
 		/**
 		 * Controls whether existing jobs in {@link SubmittedJobGraphStore} should be recovered
 		 * when {@link TestingDispatcher} is granted leadership.
@@ -525,8 +557,8 @@ public class DispatcherTest extends TestLogger {
 				JobManagerMetricGroup jobManagerMetricGroup,
 				@Nullable String metricQueryServicePath,
 				ArchivedExecutionGraphStore archivedExecutionGraphStore,
-				FatalErrorHandler fatalErrorHandler,
-				JobID expectedJobId) throws Exception {
+				JobManagerRunnerFactory jobManagerRunnerFactory,
+				FatalErrorHandler fatalErrorHandler) throws Exception {
 			super(
 				rpcService,
 				endpointId,
@@ -539,21 +571,12 @@ public class DispatcherTest extends TestLogger {
 				jobManagerMetricGroup,
 				metricQueryServicePath,
 				archivedExecutionGraphStore,
-				new ExpectedJobIdJobManagerRunnerFactory(expectedJobId),
+				jobManagerRunnerFactory,
 				fatalErrorHandler,
 				null);
 		}
 
 		@Override
-		public CompletableFuture<Acknowledge> submitJob(final JobGraph jobGraph, final Time timeout) {
-			final CompletableFuture<Acknowledge> submitJobFuture = super.submitJob(jobGraph, timeout);
-
-			submitJobFuture.thenAccept(ignored -> submitJobLatch.countDown());
-
-			return submitJobFuture;
-		}
-
-		@Override
 		void recoverJobs() {
 			if (recoverJobsEnabled.get()) {
 				super.recoverJobs();
@@ -571,8 +594,11 @@ public class DispatcherTest extends TestLogger {
 
 		private final JobID expectedJobId;
 
-		private ExpectedJobIdJobManagerRunnerFactory(JobID expectedJobId) {
+		private final CountDownLatch createdJobManagerRunnerLatch;
+
+		private ExpectedJobIdJobManagerRunnerFactory(JobID expectedJobId, CountDownLatch createdJobManagerRunnerLatch) {
 			this.expectedJobId = expectedJobId;
+			this.createdJobManagerRunnerLatch = createdJobManagerRunnerLatch;
 		}
 
 		@Override
@@ -589,6 +615,8 @@ public class DispatcherTest extends TestLogger {
 				FatalErrorHandler fatalErrorHandler) throws Exception {
 			assertEquals(expectedJobId, jobGraph.getJobID());
 
+			createdJobManagerRunnerLatch.countDown();
+
 			return Dispatcher.DefaultJobManagerRunnerFactory.INSTANCE.createJobManagerRunner(
 				resourceId,
 				jobGraph,