You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by rm...@apache.org on 2026/10/15 14:40:35 UTC
(flink) branch master updated: [FLINK-40860][container] Add bin/minicluster.sh to run an application in a MiniCluster (#29379)
This is an automated email from the ASF dual-hosted git repository.
rmetzger pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink.git
The following commit(s) were added to refs/heads/master by this push:
new 047597e0cce [FLINK-40860][container] Add bin/minicluster.sh to run an application in a MiniCluster (#29379)
047597e0cce is described below
commit 047597e0ccede18905755f66a9fe90d2bfe61075
Author: Dale Lane <da...@uk.ibm.com>
AuthorDate: Thu Oct 15 15:40:26 2026 +0100
[FLINK-40860][container] Add bin/minicluster.sh to run an application in a MiniCluster (#29379)
* [FLINK-40860][container] Refactoring ApplicationClusterEntryPoint methods
This commit moves a couple of methods out of
StandaloneApplicationClusterEntryPoint to make it easier for me
to reuse them in the new MiniCluster entrypoint I'll add next.
ClusterEntrypoint#loadConfiguration is made public so that it can
still be reused from outside the ClusterEntrypoint hierarchy.
No functional changes in this commit - just moving existing code
as-is.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
Generated-by: Claude Opus 5.5
* [FLINK-40860][container] New entrypoint for MiniCluster applications
Introduces ApplicationModeMiniCluster which is a MiniCluster that
runs a single application, in the way that a distributed
application cluster does. Its dispatcher is built with the
provided program, and starts the application itself once it has
leadership, and recovers it from high availability metadata when
there is some.
It never discards high availability metadata when it closes
(whatever closes it - the application finishing, a fatal error,
or the process being stopped) which means a replacement process
can always recover from it.
This is run by MiniClusterJobEntrypoint which is an entrypoint
for running a Flink application in a single JVM. It takes the same
command line parameters as StandaloneApplicationClusterEntryPoint
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] MiniClusterJobEntryPointITCase
Adds an ITCase test for the new MiniClusterJobEntryPoint that runs
a few different scenarios, including running a restart against a
normal distributed standalone application cluster as a reference
for the MiniCluster launcher.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] minicluster launcher script
A new flink-console shell script that runs a job in the new
MiniClusterJobEntrypoint
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] doc updates for bin/minicluster.sh
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Exit the MiniCluster process on TaskManager fatal errors
By default, a fatal error in a MiniCluster TaskManager closes that
TaskManager and leaves the rest of the MiniCluster running. A
MiniCluster started by MiniClusterJobEntryPoint has a single
TaskManager and nothing that replaces it, so after a fatal error
(such as a task that doesn't respond to cancellation within
task.cancellation.timeout) the job can never get slots again. With
an unbounded restart strategy, which is the default when
checkpointing is enabled, the process keeps running without making
progress and never exits, so a process supervisor never restarts it.
A distributed cluster avoids this because the TaskManager process
exits and is replaced. ApplicationModeMiniCluster now does the same
for the whole process: JVM-fatal errors and OOMs force the process to
exit, and other fatal errors close the MiniCluster without discarding
high availability data, so that the entry point exits with a non-zero
exit code and a restarted process recovers the job.
To allow this, MiniCluster gets a protected
createTaskManagerFatalErrorHandler hook, whose default keeps the
existing behaviour.
The entry point's shutdown hook no longer closes the MiniCluster if
main() has already started closing it. Otherwise, when a stuck task
stops the close from completing, the shutdown hook waits on the same
close until JvmShutdownSafeguard halts the JVM, replacing the exit
code of 1 with -17.
Generated-by: Claude Code 2.1.289 (Claude Opus 5.5)
* [FLINK-40860][container] Add savepoint restore and application-error ITCases
Cover two behaviours the Kubernetes Operator relies on that were not
yet tested end to end:
- restoring a job with --fromSavepoint, after stopping it with a
savepoint through the REST API, into a new HA cluster
- an application error with shutdown-on-application-finish disabled,
which is reported as a FAILED job under the fixed JobID while the
process stays up, and doesn't run main() again after a restart
Generated-by: Claude Code (Claude Opus 5.5)
* [FLINK-40860][container] Register MiniCluster shutdown hook before starting
The shutdown hook was registered only after MiniCluster#start()
returned, so a SIGTERM during startup could exit the JVM without
closing the MiniCluster.
This commit registers the hook before starting using
ShutdownHookUtil, copying the pattern in ClusterEntrypoint and
TaskManagerRunner.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][e2e] Add end-to-end test for bin/minicluster.sh
Runs bin/minicluster.sh from the distribution to check that it
runs an application with the given arguments and JVM options, and
that SIGTERM and the exit code pass through the script to and from
the JVM, as a process supervisor relies on.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
Generated-by: Claude Opus 5.5
* [FLINK-40860][container] Suspend jobs before stopping the TaskManagers
MiniCluster was stopping TaskManagers at the same time as the
dispatcher, which only suspends the jobs once its REST endpoint has
closed. This fails the jobs over, so a job without restarts fails
globally on SIGTERM, and the dispatcher discards HA metadata so a
restarted process could not recover.
This commit stops the dispatcher before the MiniCluster closes, so
it suspends the jobs first. (This doesn't wait for MiniCluster's lock,
so it also suspends them when SIGTERM arrives during startup.)
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Use cluster entrypoint's exit codes
This commit updates the MiniCluster entrypoint to use the exit
codes from ClusterEntrypoint. (1 if the cluster can't be started,
2 if it fails while running).
The exit code is logged before exiting, unless the JVM is already
exiting.
ClusterEntrypoint's exit code constants are made public to let
them be reused.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Start the JMX server
This commit starts a JMX server before MiniCluster, copying the pattern
from ClusterEntrypoint and TaskManagerRunner. (Nothing is started
unless jmx.server.port is configured.)
Unlike those launchers, I'm not stopping the JMX server explicitly.
They stop it when their entrypoint or runner object is closed, because
the JMX server is a JVM-wide singleton and those objects can be
created/closed in one JVM. The MiniCluster entrypoint is a static main
that always ends with the JVM exiting, so there is no need to stop the
JMX server separately.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Size the RPC thread pool from config
By default, MiniCluster creates its RPC service with a small fixed
thread pool (at most 4 threads), ignoring pekko.fork-join-executor
options.
This commit changes the MiniCluster entrypoint to use the configured
pool, with a default of two threads per core, started on demand.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Use distributed defaults for ask timeout & IO pool
If pekko.ask.timeout and cluster.io-pool.size aren't configured,
MiniClusterConfiguration uses small defaults (5 minute ask timeout and
4 IO threads).
This commit adopts the defaults used by distributed clusters (10 secs,
and 4 threads per core).
These defaults can be overridden by the provided config.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Load changelog storage from plugins
The changelog storage loader only finds storages on the classpath
unless it is initialized with the plugin manager.
This commit initialises the plugin manager, copying the pattern
from TaskManagerRunner.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Use configured failure enrichers
MiniCluster creates its dispatcher without failure enrichers.
This commit adds a hook to MiniCluster for creating failure
enrichers, still creating none by default for compatibility, but
allowing the entrypoint to load the ones specified in the cluster
configuration.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Handle JobManager fatal errors like TaskManager
MiniCluster handles fatal errors in its JobManager components and high
availability services by logging a warning and closing.
This commit adds a hook to MiniCluster for that handler, with the
behaviour unchanged by default. The MiniCluster entrypoint uses the
hook to set up the same handler as for TaskManager fatal errors.
This logs the error, and forces the process to exit for JVM fatal
errors and out of memory errors, and otherwise close the MiniCluster,
making the process exit with the runtime failure exit code.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Provide configured external resources
MiniCluster starts TaskManagers without external resources by default.
This commit adds a hook for creating TaskManager external resources,
creating none by default for compatibility, and then uses the hook from
the entrypoint to create the external resources specified in the
cluster configuration.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Remove cluster HA data when application finishes
Improves the close down so that cluster HA metadata isn't kept if the
application finishes and execution.shutdown-on-application-finish is set
copying the pattern from the distributed application clusters.
The HA data is still kept if the process stops for any other reason,
such as a SIGTERM or fatal error, allowing a restarted process to
recover.
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][docs] Update MiniCluster
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Avoid deadlock when MiniCluster startup fails
If MiniCluster startup fails after the dispatcher has been created, it
closes itself while holding its lock. Closing stops the dispatcher
first and then closes the MiniCluster from another thread, which waits
for that same lock, so startup never returns and the process hangs
instead of exiting.
Until the MiniCluster has started, closing it does nothing, so this
commit only stops the dispatcher in that case.
Generated-by: Claude Code (Claude Opus 5.5)
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Exit with failure code if shutting down fails
If closing the MiniCluster fails after the application finishes, such
as when removing the HA data fails, the failure was only logged and the
process exited with the application's exit code.
This commit uses the cluster entrypoint's runtime failure exit code in
that case instead, so that supervisors can tell a failed shut down from
a successful one.
Generated-by: Claude Code (Claude Opus 5.5)
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Test closing the MiniCluster during startup
Adds a test that closing the MiniCluster from another thread while it is
starting doesn't wait for the startup to finish, so a shutdown hook's
timeout bounds the close.
Generated-by: Claude Code (Claude Opus 5.5)
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Wait for an ongoing shutdown on SIGTERM
If SIGTERM arrived while the main thread was shutting down after the
application finished, the shutdown hook returned immediately, so the
JVM exited part way through the shutdown, such as while removing the
HA data.
This commit makes the shutdown hook wait for the shutdown already under
way, within the hook's timeout, as the cluster entrypoint's does.
Generated-by: Claude Code (Claude Opus 5.5)
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Use a web directory per process
The MiniCluster used web.tmpdir as it is, so processes on the same host
shared their web UI and upload directories, and one process shutting
down removed the web UI files of the others.
This commit gives each process its own directory under web.tmpdir, and
removes it on shutdown, as the cluster entrypoint does.
If SIGTERM arrives while the MiniCluster is still starting, the shutdown
hook removes the directory without waiting for the startup, which may
then create the REST endpoint's directories in it again, leaving it
behind as when the process is killed. This is deliberate: waiting for
the startup could delay the shutdown hook until the JVM halts.
Generated-by: Claude Code (Claude Opus 5.5)
Signed-off-by: Dale Lane <da...@uk.ibm.com>
* [FLINK-40860][container] Handle fatal errors during shutdown
Once the MiniCluster had been asked to close, fatal errors were only
logged at DEBUG, so errors during shutdown were hidden, and an OOM or
other JVM-fatal error didn't force the process to exit.
This commit always forces the process to exit for JVM-fatal errors, as
the TaskManager does, and logs other fatal errors during shutdown as
warnings.
Generated-by: Claude Code (Claude Opus 5.5)
Signed-off-by: Dale Lane <da...@uk.ibm.com>
---------
Signed-off-by: Dale Lane <da...@uk.ibm.com>
---
docs/content.zh/docs/deployment/overview.md | 5 +
.../resource-providers/standalone/overview.md | 49 +
docs/content/docs/deployment/overview.md | 5 +
.../resource-providers/standalone/overview.md | 50 +
.../application/ApplicationClusterEntryPoint.java | 2 +-
flink-container/pom.xml | 15 +
.../ApplicationClusterEntryPointUtils.java | 87 +
.../entrypoint/ApplicationModeMiniCluster.java | 251 +++
.../entrypoint/MiniClusterJobEntryPoint.java | 272 ++++
.../StandaloneApplicationClusterEntryPoint.java | 56 +-
.../entrypoint/ApplicationModeMiniClusterTest.java | 258 +++
.../entrypoint/MiniClusterJobEntryPointITCase.java | 1675 ++++++++++++++++++++
.../entrypoint/MiniClusterJobEntryPointTest.java | 154 ++
flink-dist/src/main/flink-bin/bin/flink-console.sh | 6 +-
flink-dist/src/main/flink-bin/bin/minicluster.sh | 37 +
flink-end-to-end-tests/run-nightly-tests.sh | 2 +
.../test-scripts/test_minicluster.sh | 149 ++
.../runtime/entrypoint/ClusterEntrypoint.java | 6 +-
.../flink/runtime/minicluster/MiniCluster.java | 66 +-
19 files changed, 3063 insertions(+), 82 deletions(-)
diff --git a/docs/content.zh/docs/deployment/overview.md b/docs/content.zh/docs/deployment/overview.md
index 290569c8c1e..ec366bb8a41 100644
--- a/docs/content.zh/docs/deployment/overview.md
+++ b/docs/content.zh/docs/deployment/overview.md
@@ -228,6 +228,11 @@ This behavior can be configured through the [`execution.terminate-application-on
Regular job completions (by the sources shutting down) are supported.
{{< /hint >}}
+{{< hint info >}}
+For low-throughput applications, the JobManager and TaskManager of an Application Mode cluster can also be run together in a
+single process. See [Application Mode in a MiniCluster]({{< ref "docs/deployment/resource-providers/standalone/overview" >}}#application-mode-in-a-minicluster).
+{{< /hint >}}
+
#### Session Mode
*Session mode* assumes an already running cluster and uses the resources of that cluster to execute any
diff --git a/docs/content.zh/docs/deployment/resource-providers/standalone/overview.md b/docs/content.zh/docs/deployment/resource-providers/standalone/overview.md
index 4fe2e4f228a..14ae582337f 100644
--- a/docs/content.zh/docs/deployment/resource-providers/standalone/overview.md
+++ b/docs/content.zh/docs/deployment/resource-providers/standalone/overview.md
@@ -170,6 +170,55 @@ bin/taskmanager.sh start|start-foreground|stop|stop-all
确保在你想启动/关闭相应实例的主机上执行这些脚本。
+## Application Mode in a MiniCluster
+
+An application can also be run with the JobManager and a TaskManager in a single process, using the `bin/minicluster.sh` script.
+This is useful for low-throughput jobs where running a separate TaskManager is not worth the additional resources.
+The process runs the same components as a distributed application cluster, so savepoints, checkpoints, state backends, metrics and the web interface all work in the same way.
+
+The script takes the same arguments as `bin/standalone-job.sh`, except that it always runs in the foreground (so there is no `start` or `stop`) and arguments for the application should be put after `--`:
+
+```bash
+$ ./bin/minicluster.sh --jars local://$(pwd)/examples/streaming/TopSpeedWindowing.jar
+```
+
+The web interface is now available at [localhost:8081](http://localhost:8081). No TaskManager needs to be started.
+
+The full set of arguments is:
+
+```bash
+$ ./bin/minicluster.sh \
+ [--jars <jar>[,<jar>...]] \
+ [--job-classname <class name>] \
+ [--job-id <job id>] \
+ [--fromSavepoint <path> [--allowNonRestoredState]] \
+ [-D <key>=<value> ...] \
+ [-- <application arguments>]
+```
+
+As with `standalone-job.sh`, if `--jars` is not given, the application is loaded from the `usrlib` folder or the classpath.
+
+The MiniCluster has one TaskManager instance within the JVM with `taskmanager.numberOfTaskSlots` slots, so the parallelism of the application cannot be greater than this.
+JobManager and TaskManager process memory options (such as `jobmanager.memory.process.size` and `taskmanager.memory.process.size`) do not apply, and the JVM heap size is set by the JVM defaults unless set using `env.java.opts.jobmanager` or `env.java.opts.all`.
+
+### Restarting the process
+
+If [High Availability]({{< ref "docs/deployment/ha/overview" >}}) is configured, the process can be restarted after a failure and will resume the application from the latest checkpoint.
+The application is given a fixed job ID derived from the `high-availability.cluster-id` (or from `--job-id`, if given), so a restarted process recovers the existing job from the high availability metadata rather than starting a new one.
+Stopping the process with `SIGTERM` keeps the high availability metadata, so that it can be recovered in the same way.
+
+Task failures are handled by the application's restart strategy within the process, in the same way as in a distributed cluster.
+A fatal error in the JobManager or the TaskManager cannot be recovered within the process, because there is no other process to take over.
+Examples are an `OutOfMemoryError`, or a task that does not stop within [`task.cancellation.timeout`]({{< ref "docs/deployment/config" >}}#task-cancellation-timeout) after it is cancelled (unless that is set to `0`, which disables this check).
+In these cases the process exits with a non-zero exit code, keeping the high availability metadata, so it should be run under a supervisor that restarts it, such as Kubernetes or systemd.
+
+Without High Availability, a restarted process starts the application again from the beginning (or from `--fromSavepoint`, if given).
+
+### When the application finishes
+
+By default, the process exits once the application reaches a terminal state, with an exit code of `0` if the application finished or was cancelled, and a non-zero exit code if it failed.
+If [`execution.shutdown-on-application-finish`]({{< ref "docs/deployment/config" >}}#execution-shutdown-on-application-finish) is set to `false`, the process keeps running after the application finishes, so that its final status can still be retrieved from the web interface and REST API.
+
## High-Availability with Standalone
In order to enable HA for a standalone cluster, you have to use the [ZooKeeper HA services]({{< ref "docs/deployment/ha/zookeeper_ha" >}}).
diff --git a/docs/content/docs/deployment/overview.md b/docs/content/docs/deployment/overview.md
index d5004ea087a..0242c9aa044 100644
--- a/docs/content/docs/deployment/overview.md
+++ b/docs/content/docs/deployment/overview.md
@@ -231,6 +231,11 @@ This behavior can be configured through the [`execution.terminate-application-on
Regular job completions (by the sources shutting down) are supported.
{{< /hint >}}
+{{< hint info >}}
+For low-throughput applications, the JobManager and TaskManager of an Application Mode cluster can also be run together in a
+single process. See [Application Mode in a MiniCluster]({{< ref "docs/deployment/resource-providers/standalone/overview" >}}#application-mode-in-a-minicluster).
+{{< /hint >}}
+
### Session Mode
*Session mode* assumes an already running cluster and uses the resources of that cluster to execute any
diff --git a/docs/content/docs/deployment/resource-providers/standalone/overview.md b/docs/content/docs/deployment/resource-providers/standalone/overview.md
index eda2e62fb14..ed54ce505e6 100644
--- a/docs/content/docs/deployment/resource-providers/standalone/overview.md
+++ b/docs/content/docs/deployment/resource-providers/standalone/overview.md
@@ -123,6 +123,55 @@ $ ./bin/taskmanager.sh stop
$ ./bin/standalone-job.sh stop
```
+### Application Mode in a MiniCluster
+
+An application can also be run with the JobManager and a TaskManager in a single process, using the `bin/minicluster.sh` script.
+This is useful for low-throughput jobs where running a separate TaskManager is not worth the additional resources.
+The process runs the same components as a distributed application cluster, so savepoints, checkpoints, state backends, metrics and the web interface all work in the same way.
+
+The script takes the same arguments as `bin/standalone-job.sh`, except that it always runs in the foreground (so there is no `start` or `stop`) and arguments for the application should be put after `--`:
+
+```bash
+$ ./bin/minicluster.sh --jars local://$(pwd)/examples/streaming/TopSpeedWindowing.jar
+```
+
+The web interface is now available at [localhost:8081](http://localhost:8081). No TaskManager needs to be started.
+
+The full set of arguments is:
+
+```bash
+$ ./bin/minicluster.sh \
+ [--jars <jar>[,<jar>...]] \
+ [--job-classname <class name>] \
+ [--job-id <job id>] \
+ [--fromSavepoint <path> [--allowNonRestoredState]] \
+ [-D <key>=<value> ...] \
+ [-- <application arguments>]
+```
+
+As with `standalone-job.sh`, if `--jars` is not given, the application is loaded from the `usrlib` folder or the classpath.
+
+The MiniCluster has one TaskManager instance within the JVM with `taskmanager.numberOfTaskSlots` slots, so the parallelism of the application cannot be greater than this.
+JobManager and TaskManager process memory options (such as `jobmanager.memory.process.size` and `taskmanager.memory.process.size`) do not apply, and the JVM heap size is set by the JVM defaults unless set using `env.java.opts.jobmanager` or `env.java.opts.all`.
+
+#### Restarting the process
+
+If [High Availability]({{< ref "docs/deployment/ha/overview" >}}) is configured, the process can be restarted after a failure and will resume the application from the latest checkpoint.
+The application is given a fixed job ID derived from the `high-availability.cluster-id` (or from `--job-id`, if given), so a restarted process recovers the existing job from the high availability metadata rather than starting a new one.
+Stopping the process with `SIGTERM` keeps the high availability metadata, so that it can be recovered in the same way.
+
+Task failures are handled by the application's restart strategy within the process, in the same way as in a distributed cluster.
+A fatal error in the JobManager or the TaskManager cannot be recovered within the process, because there is no other process to take over.
+Examples are an `OutOfMemoryError`, or a task that does not stop within [`task.cancellation.timeout`]({{< ref "docs/deployment/config" >}}#task-cancellation-timeout) after it is cancelled (unless that is set to `0`, which disables this check).
+In these cases the process exits with a non-zero exit code, keeping the high availability metadata, so it should be run under a supervisor that restarts it, such as Kubernetes or systemd.
+
+Without High Availability, a restarted process starts the application again from the beginning (or from `--fromSavepoint`, if given).
+
+#### When the application finishes
+
+By default, the process exits once the application reaches a terminal state, with an exit code of `0` if the application finished or was cancelled, and a non-zero exit code if it failed.
+If [`execution.shutdown-on-application-finish`]({{< ref "docs/deployment/config" >}}#execution-shutdown-on-application-finish) is set to `false`, the process keeps running after the application finishes, so that its final status can still be retrieved from the web interface and REST API.
+
### Session Mode
{{< hint info >}}
@@ -140,6 +189,7 @@ All available configuration options are listed on the [configuration page]({{< r
The following scripts also allow configuration parameters to be set via dynamic properties:
* `jobmanager.sh`
* `standalone-job.sh`
+* `minicluster.sh`
* `taskmanager.sh`
* `historyserver.sh`
diff --git a/flink-clients/src/main/java/org/apache/flink/client/deployment/application/ApplicationClusterEntryPoint.java b/flink-clients/src/main/java/org/apache/flink/client/deployment/application/ApplicationClusterEntryPoint.java
index c6953d95f51..2764da5d30f 100644
--- a/flink-clients/src/main/java/org/apache/flink/client/deployment/application/ApplicationClusterEntryPoint.java
+++ b/flink-clients/src/main/java/org/apache/flink/client/deployment/application/ApplicationClusterEntryPoint.java
@@ -83,7 +83,7 @@ public class ApplicationClusterEntryPoint extends ClusterEntrypoint {
return new MemoryArchivedApplicationStore();
}
- protected static void configureExecution(
+ public static void configureExecution(
final Configuration configuration, final PackagedProgram program) throws Exception {
configuration.set(DeploymentOptions.TARGET, EmbeddedExecutor.NAME);
ConfigUtils.encodeCollectionToConfig(
diff --git a/flink-container/pom.xml b/flink-container/pom.xml
index b307d8fdcfe..33ef566e4c7 100644
--- a/flink-container/pom.xml
+++ b/flink-container/pom.xml
@@ -64,5 +64,20 @@ under the License.
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-runtime</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.curator</groupId>
+ <artifactId>curator-test</artifactId>
+ <version>${curator.version}</version>
+ <scope>test</scope>
+ </dependency>
+
</dependencies>
</project>
diff --git a/flink-container/src/main/java/org/apache/flink/container/entrypoint/ApplicationClusterEntryPointUtils.java b/flink-container/src/main/java/org/apache/flink/container/entrypoint/ApplicationClusterEntryPointUtils.java
new file mode 100644
index 00000000000..233952eae4f
--- /dev/null
+++ b/flink-container/src/main/java/org/apache/flink/container/entrypoint/ApplicationClusterEntryPointUtils.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.container.entrypoint;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.common.JobID;
+import org.apache.flink.client.program.DefaultPackagedProgramRetriever;
+import org.apache.flink.client.program.PackagedProgram;
+import org.apache.flink.client.program.PackagedProgramRetriever;
+import org.apache.flink.client.program.artifact.ArtifactFetchManager;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.PipelineOptionsInternal;
+import org.apache.flink.runtime.entrypoint.ClusterEntrypoint;
+import org.apache.flink.runtime.entrypoint.ClusterEntrypointUtils;
+import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
+
+import java.io.File;
+import java.util.Collection;
+
+@Internal
+final class ApplicationClusterEntryPointUtils {
+
+ static Configuration loadConfiguration(
+ StandaloneApplicationClusterConfiguration clusterConfiguration) {
+ final Configuration configuration =
+ ClusterEntrypoint.loadConfiguration(clusterConfiguration);
+
+ setStaticJobId(clusterConfiguration, configuration);
+
+ SavepointRestoreSettings.toConfiguration(
+ clusterConfiguration.getSavepointRestoreSettings(), configuration);
+ return configuration;
+ }
+
+ static PackagedProgram getPackagedProgram(
+ final StandaloneApplicationClusterConfiguration clusterConfiguration,
+ Configuration flinkConfiguration)
+ throws Exception {
+ final File userLibDir = ClusterEntrypointUtils.tryFindUserLibDirectory().orElse(null);
+
+ File jobJar = null;
+ Collection<File> artifacts = null;
+ if (clusterConfiguration.hasJars()) {
+ ArtifactFetchManager fetchMgr = new ArtifactFetchManager(flinkConfiguration);
+ ArtifactFetchManager.Result res =
+ fetchMgr.fetchArtifacts(clusterConfiguration.getJars());
+
+ jobJar = res.getJobJar();
+ artifacts = res.getArtifacts();
+ }
+
+ final PackagedProgramRetriever programRetriever =
+ DefaultPackagedProgramRetriever.create(
+ userLibDir,
+ jobJar,
+ artifacts,
+ clusterConfiguration.getJobClassName(),
+ clusterConfiguration.getArgs(),
+ flinkConfiguration);
+ return programRetriever.getPackagedProgram();
+ }
+
+ private static void setStaticJobId(
+ StandaloneApplicationClusterConfiguration clusterConfiguration,
+ Configuration configuration) {
+ final JobID jobId = clusterConfiguration.getJobId();
+ if (jobId != null) {
+ configuration.set(PipelineOptionsInternal.PIPELINE_FIXED_JOB_ID, jobId.toHexString());
+ }
+ }
+}
diff --git a/flink-container/src/main/java/org/apache/flink/container/entrypoint/ApplicationModeMiniCluster.java b/flink-container/src/main/java/org/apache/flink/container/entrypoint/ApplicationModeMiniCluster.java
new file mode 100644
index 00000000000..68137cc1b72
--- /dev/null
+++ b/flink-container/src/main/java/org/apache/flink/container/entrypoint/ApplicationModeMiniCluster.java
@@ -0,0 +1,251 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.container.entrypoint;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.client.deployment.application.ApplicationDispatcherLeaderProcessFactoryFactory;
+import org.apache.flink.client.program.PackagedProgram;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.failure.FailureEnricher;
+import org.apache.flink.core.plugin.PluginManager;
+import org.apache.flink.core.security.FlinkSecurityManager;
+import org.apache.flink.runtime.blob.BlobServer;
+import org.apache.flink.runtime.clusterframework.ApplicationStatus;
+import org.apache.flink.runtime.dispatcher.SessionDispatcherFactory;
+import org.apache.flink.runtime.dispatcher.runner.DefaultDispatcherRunnerFactory;
+import org.apache.flink.runtime.entrypoint.ClusterEntrypoint;
+import org.apache.flink.runtime.entrypoint.component.DefaultDispatcherResourceManagerComponentFactory;
+import org.apache.flink.runtime.entrypoint.component.DispatcherResourceManagerComponent;
+import org.apache.flink.runtime.entrypoint.component.DispatcherResourceManagerComponentFactory;
+import org.apache.flink.runtime.externalresource.ExternalResourceInfoProvider;
+import org.apache.flink.runtime.externalresource.ExternalResourceUtils;
+import org.apache.flink.runtime.failure.FailureEnricherUtils;
+import org.apache.flink.runtime.heartbeat.HeartbeatServices;
+import org.apache.flink.runtime.metrics.MetricRegistry;
+import org.apache.flink.runtime.minicluster.MiniCluster;
+import org.apache.flink.runtime.minicluster.MiniClusterConfiguration;
+import org.apache.flink.runtime.resourcemanager.StandaloneResourceManagerFactory;
+import org.apache.flink.runtime.rest.ApplicationRestEndpointFactory;
+import org.apache.flink.runtime.rpc.FatalErrorHandler;
+import org.apache.flink.runtime.rpc.RpcService;
+import org.apache.flink.runtime.rpc.RpcSystem;
+import org.apache.flink.runtime.security.token.DelegationTokenManager;
+import org.apache.flink.runtime.webmonitor.retriever.MetricQueryServiceRetriever;
+import org.apache.flink.util.ExceptionUtils;
+import org.apache.flink.util.concurrent.FutureUtils;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.Collection;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+/**
+ * A {@link MiniCluster} that runs a single application in the same way as a distributed application
+ * cluster. The dispatcher is built with the user's program and starts the application itself once
+ * it has leadership, recovering from high availability metadata where available.
+ */
+@Internal
+class ApplicationModeMiniCluster extends MiniCluster {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ApplicationModeMiniCluster.class);
+
+ private final Configuration configuration;
+ private final PackagedProgram program;
+ @Nullable private final PluginManager pluginManager;
+
+ private final CompletableFuture<ApplicationStatus> applicationShutDownFuture =
+ new CompletableFuture<>();
+ private final CompletableFuture<Void> closeRequestedFuture = new CompletableFuture<>();
+ private final Collection<DispatcherResourceManagerComponent>
+ dispatcherResourceManagerComponents = new CopyOnWriteArrayList<>();
+
+ /** The close that is under way, once one has started while the MiniCluster was running. */
+ private final AtomicReference<CompletableFuture<Void>> closeFuture = new AtomicReference<>();
+
+ ApplicationModeMiniCluster(
+ final MiniClusterConfiguration miniClusterConfiguration,
+ final PackagedProgram program) {
+ super(miniClusterConfiguration);
+ this.configuration = new Configuration(miniClusterConfiguration.getConfiguration());
+ this.program = checkNotNull(program);
+ this.pluginManager = miniClusterConfiguration.getPluginManager();
+ }
+
+ CompletableFuture<ApplicationStatus> getApplicationShutDownFuture() {
+ return applicationShutDownFuture;
+ }
+
+ CompletableFuture<Void> getCloseRequestedFuture() {
+ return closeRequestedFuture;
+ }
+
+ @Override
+ protected DispatcherResourceManagerComponentFactory
+ createDispatcherResourceManagerComponentFactory() {
+ return new DefaultDispatcherResourceManagerComponentFactory(
+ new DefaultDispatcherRunnerFactory(
+ ApplicationDispatcherLeaderProcessFactoryFactory.create(
+ configuration, SessionDispatcherFactory.INSTANCE, program)),
+ StandaloneResourceManagerFactory.getInstance(),
+ ApplicationRestEndpointFactory.INSTANCE);
+ }
+
+ @Override
+ protected Collection<? extends DispatcherResourceManagerComponent>
+ createDispatcherResourceManagerComponents(
+ Configuration configuration,
+ RpcServiceFactory rpcServiceFactory,
+ BlobServer blobServer,
+ HeartbeatServices heartbeatServices,
+ DelegationTokenManager delegationTokenManager,
+ MetricRegistry metricRegistry,
+ MetricQueryServiceRetriever metricQueryServiceRetriever,
+ FatalErrorHandler fatalErrorHandler)
+ throws Exception {
+ final Collection<? extends DispatcherResourceManagerComponent> components =
+ super.createDispatcherResourceManagerComponents(
+ configuration,
+ rpcServiceFactory,
+ blobServer,
+ heartbeatServices,
+ delegationTokenManager,
+ metricRegistry,
+ metricQueryServiceRetriever,
+ fatalErrorHandler);
+ for (DispatcherResourceManagerComponent component : components) {
+ FutureUtils.forward(component.getShutDownFuture(), applicationShutDownFuture);
+ }
+ dispatcherResourceManagerComponents.addAll(components);
+ return components;
+ }
+
+ @Override
+ protected FatalErrorHandler createJobManagerFatalErrorHandler() {
+ return createProcessFatalErrorHandler("JobManager");
+ }
+
+ @Override
+ protected FatalErrorHandler createTaskManagerFatalErrorHandler(int index) {
+ return createProcessFatalErrorHandler("TaskManager #" + index);
+ }
+
+ /**
+ * Nothing replaces a JobManager or TaskManager that fails, so the whole process has to fail
+ * instead, like their processes do in a distributed cluster. That leaves the restart to the
+ * process supervisor, with high availability recovering the job.
+ */
+ private FatalErrorHandler createProcessFatalErrorHandler(String component) {
+ return exception -> {
+ if (ExceptionUtils.isJvmFatalOrOutOfMemoryError(exception)) {
+ LOG.error(
+ "{} failed. Terminating the process with exit code {}.",
+ component,
+ ClusterEntrypoint.RUNTIME_FAILURE_RETURN_CODE,
+ exception);
+ FlinkSecurityManager.forceProcessExit(
+ ClusterEntrypoint.RUNTIME_FAILURE_RETURN_CODE);
+ } else if (closeRequestedFuture.isDone()) {
+ LOG.warn("{} failed while shutting down.", component, exception);
+ } else {
+ LOG.error("{} failed. Shutting the MiniCluster down.", component, exception);
+ closeAsync();
+ }
+ };
+ }
+
+ @Override
+ protected Collection<FailureEnricher> createFailureEnrichers(Configuration configuration) {
+ return FailureEnricherUtils.getFailureEnrichers(configuration);
+ }
+
+ @Override
+ protected ExternalResourceInfoProvider createExternalResourceInfoProvider(
+ Configuration configuration) {
+ return ExternalResourceUtils.createStaticExternalResourceInfoProviderFromConfig(
+ configuration, pluginManager);
+ }
+
+ /** Sizes the RPC thread pool from the {@code pekko.fork-join-executor} options. */
+ @Override
+ protected RpcService createLocalRpcService(Configuration configuration, RpcSystem rpcSystem)
+ throws Exception {
+ return rpcSystem.localServiceBuilder(configuration).createAndStart();
+ }
+
+ @Override
+ public CompletableFuture<Void> closeAsync() {
+ closeRequestedFuture.complete(null);
+ // checked first, as a close is recorded before it stops the MiniCluster running
+ final boolean running = isRunning();
+ final CompletableFuture<Void> closeUnderWay = closeFuture.get();
+ if (closeUnderWay != null) {
+ return closeUnderWay;
+ }
+ if (!running) {
+ // Nothing more to close while it is not running. A failed start calls this while
+ // holding the lock that closing it waits for, so returning now to avoid deadlock
+ return stopDispatcher();
+ }
+ final CompletableFuture<Void> newCloseFuture = new CompletableFuture<>();
+ if (!closeFuture.compareAndSet(null, newCloseFuture)) {
+ return closeFuture.get();
+ }
+ // the cluster's high availability data is only removed if the dispatcher has shut down,
+ // which it does when the application finishes if execution.shutdown-on-application-finish
+ // is set. Otherwise, the data is kept so that a restarted process can recover.
+ final boolean cleanupHighAvailabilityData = isDispatcherShutDown();
+ FutureUtils.forward(
+ FutureUtils.composeAfterwards(
+ // stop the dispatcher before the MiniCluster stops TaskManagers so it
+ // suspends jobs first
+ stopDispatcher(),
+ cleanupHighAvailabilityData
+ ? super::closeAsync
+ : super::closeAsyncWithoutCleaningHighAvailabilityData),
+ newCloseFuture);
+ return newCloseFuture;
+ }
+
+ private CompletableFuture<Void> stopDispatcher() {
+ return FutureUtils.completeAll(
+ dispatcherResourceManagerComponents.stream()
+ .map(DispatcherResourceManagerComponent::stopProcess)
+ .collect(Collectors.toList()));
+ }
+
+ @VisibleForTesting
+ boolean isDispatcherShutDown() {
+ return !dispatcherResourceManagerComponents.isEmpty()
+ && dispatcherResourceManagerComponents.stream()
+ .map(DispatcherResourceManagerComponent::getShutDownFuture)
+ .allMatch(
+ shutDownFuture ->
+ shutDownFuture.isDone()
+ && !shutDownFuture.isCompletedExceptionally());
+ }
+}
diff --git a/flink-container/src/main/java/org/apache/flink/container/entrypoint/MiniClusterJobEntryPoint.java b/flink-container/src/main/java/org/apache/flink/container/entrypoint/MiniClusterJobEntryPoint.java
new file mode 100644
index 00000000000..f7a84477da9
--- /dev/null
+++ b/flink-container/src/main/java/org/apache/flink/container/entrypoint/MiniClusterJobEntryPoint.java
@@ -0,0 +1,272 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.container.entrypoint;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.client.deployment.application.ApplicationClusterEntryPoint;
+import org.apache.flink.client.program.PackagedProgram;
+import org.apache.flink.configuration.ClusterOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.JMXServerOptions;
+import org.apache.flink.configuration.RpcOptions;
+import org.apache.flink.configuration.TaskManagerOptions;
+import org.apache.flink.configuration.WebOptions;
+import org.apache.flink.core.fs.FileSystem;
+import org.apache.flink.core.plugin.PluginManager;
+import org.apache.flink.core.plugin.PluginUtils;
+import org.apache.flink.core.security.FlinkSecurityManager;
+import org.apache.flink.management.jmx.JMXService;
+import org.apache.flink.runtime.clusterframework.ApplicationStatus;
+import org.apache.flink.runtime.entrypoint.ClusterEntrypoint;
+import org.apache.flink.runtime.entrypoint.ClusterEntrypointUtils;
+import org.apache.flink.runtime.minicluster.MiniCluster;
+import org.apache.flink.runtime.minicluster.MiniClusterConfiguration;
+import org.apache.flink.runtime.security.contexts.SecurityContext;
+import org.apache.flink.runtime.state.changelog.StateChangelogStorageLoader;
+import org.apache.flink.runtime.util.EnvironmentInformation;
+import org.apache.flink.runtime.util.JvmShutdownSafeguard;
+import org.apache.flink.runtime.util.SignalHandler;
+import org.apache.flink.util.FileUtils;
+import org.apache.flink.util.ShutdownHookUtil;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Entry point that runs a single application in a {@link MiniCluster}. It takes the same command
+ * line parameters as {@link StandaloneApplicationClusterEntryPoint}, and the MiniCluster is built
+ * with the same application-mode dispatcher.
+ */
+@Internal
+public final class MiniClusterJobEntryPoint {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MiniClusterJobEntryPoint.class);
+
+ private static final Duration SHUTDOWN_TIMEOUT = Duration.ofSeconds(30);
+
+ /** The safeguard's default, as used by the other cluster entrypoints. */
+ private static final Duration JVM_SHUTDOWN_SAFEGUARD_DELAY = Duration.ofSeconds(5);
+
+ /** Shorter than the safeguard delay, so that a slow close is logged before the JVM halts. */
+ private static final Duration SHUTDOWN_HOOK_TIMEOUT = Duration.ofSeconds(4);
+
+ private static final AtomicBoolean STOPPING = new AtomicBoolean();
+
+ /** Completed once whichever of the main thread and the shutdown hook is stopping is done. */
+ private static final CompletableFuture<Void> STOPPED = new CompletableFuture<>();
+
+ /** Whether the JVM is exiting for another reason, which decides its exit code. */
+ private static volatile boolean closedByShutdownHook;
+
+ public static void main(String[] args) {
+ EnvironmentInformation.logEnvironmentInfo(
+ LOG, MiniClusterJobEntryPoint.class.getSimpleName(), args);
+ SignalHandler.register(LOG);
+ JvmShutdownSafeguard.installAsShutdownHook(LOG, JVM_SHUTDOWN_SAFEGUARD_DELAY.toMillis());
+
+ final StandaloneApplicationClusterConfiguration clusterConfiguration =
+ ClusterEntrypointUtils.parseParametersOrExit(
+ args,
+ new StandaloneApplicationClusterConfigurationParserFactory(),
+ MiniClusterJobEntryPoint.class);
+
+ int exitCode;
+ try {
+ final Configuration configuration =
+ ApplicationClusterEntryPointUtils.loadConfiguration(clusterConfiguration);
+ FlinkSecurityManager.setFromConfiguration(configuration);
+ final PluginManager pluginManager =
+ PluginUtils.createPluginManagerFromRootFolder(configuration);
+ FileSystem.initialize(configuration, pluginManager);
+ StateChangelogStorageLoader.initialize(pluginManager);
+
+ final SecurityContext securityContext =
+ ClusterEntrypoint.installSecurityContext(configuration);
+ ClusterEntrypointUtils.configureUncaughtExceptionHandler(configuration);
+ exitCode =
+ securityContext.runSecured(
+ () ->
+ runApplication(
+ clusterConfiguration, configuration, pluginManager));
+ } catch (Throwable t) {
+ LOG.error("Could not run the application on a MiniCluster.", t);
+ exitCode = ClusterEntrypoint.STARTUP_FAILURE_RETURN_CODE;
+ }
+ if (closedByShutdownHook) {
+ return;
+ }
+ LOG.info(
+ "Terminating {} with exit code {}.",
+ MiniClusterJobEntryPoint.class.getSimpleName(),
+ exitCode);
+ System.exit(exitCode);
+ }
+
+ private static int runApplication(
+ final StandaloneApplicationClusterConfiguration clusterConfiguration,
+ final Configuration configuration,
+ final PluginManager pluginManager)
+ throws Exception {
+ final PackagedProgram program =
+ ApplicationClusterEntryPointUtils.getPackagedProgram(
+ clusterConfiguration, configuration);
+ final File webTmpDir =
+ new File(configuration.get(WebOptions.TMP_DIR), "flink-web-" + UUID.randomUUID());
+ final ApplicationModeMiniCluster miniCluster;
+ try {
+ ApplicationClusterEntryPoint.configureExecution(configuration, program);
+
+ miniCluster =
+ new ApplicationModeMiniCluster(
+ buildMiniClusterConfiguration(configuration, pluginManager, webTmpDir),
+ program);
+ final String serviceName = MiniClusterJobEntryPoint.class.getSimpleName();
+ ShutdownHookUtil.addShutdownHookThread(
+ new Thread(
+ () -> {
+ if (STOPPING.compareAndSet(false, true)) {
+ closedByShutdownHook = true;
+ tryClose(miniCluster, webTmpDir, SHUTDOWN_HOOK_TIMEOUT);
+ program.close();
+ } else {
+ // the JVM halts once the hooks finish, so wait for the
+ // main thread to finish stopping
+ awaitStopped();
+ }
+ },
+ serviceName + " shutdown hook"),
+ serviceName,
+ LOG);
+ JMXService.startInstance(configuration.get(JMXServerOptions.JMX_SERVER_PORT));
+ miniCluster.start();
+ } catch (Throwable t) {
+ if (STOPPING.compareAndSet(false, true)) {
+ tryDeleteWebTmpDir(webTmpDir);
+ program.close();
+ STOPPED.complete(null);
+ }
+ throw t;
+ }
+
+ CompletableFuture.anyOf(
+ miniCluster.getApplicationShutDownFuture(),
+ miniCluster.getCloseRequestedFuture())
+ .handle((ignored, throwable) -> null)
+ .join();
+
+ // only one of this and the shutdown hook closes the MiniCluster, so that a close that
+ // times out here isn't waited for again during JVM shutdown
+ if (!STOPPING.compareAndSet(false, true)) {
+ return 0;
+ }
+
+ final boolean closed;
+ try {
+ closed = tryClose(miniCluster, webTmpDir, SHUTDOWN_TIMEOUT);
+ program.close();
+ } finally {
+ STOPPED.complete(null);
+ }
+
+ final CompletableFuture<ApplicationStatus> applicationShutDown =
+ miniCluster.getApplicationShutDownFuture();
+ if (!applicationShutDown.isDone() || applicationShutDown.isCompletedExceptionally()) {
+ LOG.error("MiniCluster shut down before the application finished.");
+ return ClusterEntrypoint.RUNTIME_FAILURE_RETURN_CODE;
+ }
+ final ApplicationStatus applicationStatus = applicationShutDown.join();
+ LOG.info("Application finished with status {}.", applicationStatus);
+ // report a failed shut down (e.g. not removing the HA data) over application's status
+ return closed
+ ? applicationStatus.processExitCode()
+ : ClusterEntrypoint.RUNTIME_FAILURE_RETURN_CODE;
+ }
+
+ private static MiniClusterConfiguration buildMiniClusterConfiguration(
+ final Configuration configuration,
+ final PluginManager pluginManager,
+ final File webTmpDir) {
+ final Configuration clusterConfiguration = new Configuration(configuration);
+ clusterConfiguration.set(WebOptions.TMP_DIR, webTmpDir.getAbsolutePath());
+ if (!clusterConfiguration.contains(RpcOptions.ASK_TIMEOUT_DURATION)) {
+ clusterConfiguration.set(
+ RpcOptions.ASK_TIMEOUT_DURATION,
+ RpcOptions.ASK_TIMEOUT_DURATION.defaultValue());
+ }
+ if (!clusterConfiguration.contains(ClusterOptions.CLUSTER_IO_EXECUTOR_POOL_SIZE)) {
+ clusterConfiguration.set(
+ ClusterOptions.CLUSTER_IO_EXECUTOR_POOL_SIZE,
+ ClusterEntrypointUtils.getPoolSize(clusterConfiguration));
+ }
+ return new MiniClusterConfiguration.Builder()
+ .setConfiguration(clusterConfiguration)
+ .setNumSlotsPerTaskManager(configuration.get(TaskManagerOptions.NUM_TASK_SLOTS))
+ .setPluginManager(pluginManager)
+ .build();
+ }
+
+ /**
+ * Returns whether the MiniCluster closed within the timeout and its web directory was removed.
+ */
+ private static boolean tryClose(
+ final MiniCluster miniCluster, final File webTmpDir, final Duration timeout) {
+ boolean closed = true;
+ try {
+ miniCluster.closeAsync().get(timeout.toMillis(), TimeUnit.MILLISECONDS);
+ } catch (Exception e) {
+ LOG.error("Could not close the MiniCluster.", e);
+ closed = false;
+ }
+ return tryDeleteWebTmpDir(webTmpDir) && closed;
+ }
+
+ private static boolean tryDeleteWebTmpDir(final File webTmpDir) {
+ try {
+ FileUtils.deleteDirectory(webTmpDir);
+ return true;
+ } catch (IOException e) {
+ LOG.error("Could not remove the web directory {}.", webTmpDir, e);
+ return false;
+ }
+ }
+
+ private static void awaitStopped() {
+ try {
+ STOPPED.get(SHUTDOWN_HOOK_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
+ } catch (TimeoutException e) {
+ LOG.warn("Stopping did not finish within {}.", SHUTDOWN_HOOK_TIMEOUT);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } catch (ExecutionException e) {
+ // never completed exceptionally
+ }
+ }
+
+ private MiniClusterJobEntryPoint() {}
+}
diff --git a/flink-container/src/main/java/org/apache/flink/container/entrypoint/StandaloneApplicationClusterEntryPoint.java b/flink-container/src/main/java/org/apache/flink/container/entrypoint/StandaloneApplicationClusterEntryPoint.java
index 1dbd12b6cfc..e19897fc33a 100644
--- a/flink-container/src/main/java/org/apache/flink/container/entrypoint/StandaloneApplicationClusterEntryPoint.java
+++ b/flink-container/src/main/java/org/apache/flink/container/entrypoint/StandaloneApplicationClusterEntryPoint.java
@@ -20,30 +20,21 @@ package org.apache.flink.container.entrypoint;
import org.apache.flink.annotation.Internal;
import org.apache.flink.annotation.VisibleForTesting;
-import org.apache.flink.api.common.JobID;
import org.apache.flink.client.deployment.application.ApplicationClusterEntryPoint;
-import org.apache.flink.client.program.DefaultPackagedProgramRetriever;
import org.apache.flink.client.program.PackagedProgram;
-import org.apache.flink.client.program.PackagedProgramRetriever;
-import org.apache.flink.client.program.artifact.ArtifactFetchManager;
import org.apache.flink.configuration.Configuration;
-import org.apache.flink.configuration.PipelineOptionsInternal;
import org.apache.flink.core.execution.RecoveryClaimMode;
import org.apache.flink.core.fs.FileSystem;
import org.apache.flink.core.plugin.PluginManager;
import org.apache.flink.core.plugin.PluginUtils;
import org.apache.flink.runtime.entrypoint.ClusterEntrypoint;
import org.apache.flink.runtime.entrypoint.ClusterEntrypointUtils;
-import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.resourcemanager.StandaloneResourceManagerFactory;
import org.apache.flink.runtime.security.contexts.SecurityContext;
import org.apache.flink.runtime.util.EnvironmentInformation;
import org.apache.flink.runtime.util.JvmShutdownSafeguard;
import org.apache.flink.runtime.util.SignalHandler;
-import java.io.File;
-import java.util.Collection;
-
/** An {@link ApplicationClusterEntryPoint} which is started with a job in a predefined location. */
@Internal
public final class StandaloneApplicationClusterEntryPoint extends ApplicationClusterEntryPoint {
@@ -87,7 +78,9 @@ public final class StandaloneApplicationClusterEntryPoint extends ApplicationClu
SecurityContext securityContext = installSecurityContext(configuration);
program =
securityContext.runSecured(
- () -> getPackagedProgram(clusterConfiguration, configuration));
+ () ->
+ ApplicationClusterEntryPointUtils.getPackagedProgram(
+ clusterConfiguration, configuration));
} catch (Exception e) {
LOG.error("Could not create application program.", e);
System.exit(1);
@@ -114,47 +107,6 @@ public final class StandaloneApplicationClusterEntryPoint extends ApplicationClu
@VisibleForTesting
static Configuration loadConfigurationFromClusterConfig(
StandaloneApplicationClusterConfiguration clusterConfiguration) {
- Configuration configuration = loadConfiguration(clusterConfiguration);
- setStaticJobId(clusterConfiguration, configuration);
- SavepointRestoreSettings.toConfiguration(
- clusterConfiguration.getSavepointRestoreSettings(), configuration);
- return configuration;
- }
-
- private static PackagedProgram getPackagedProgram(
- final StandaloneApplicationClusterConfiguration clusterConfiguration,
- Configuration flinkConfiguration)
- throws Exception {
- final File userLibDir = ClusterEntrypointUtils.tryFindUserLibDirectory().orElse(null);
-
- File jobJar = null;
- Collection<File> artifacts = null;
- if (clusterConfiguration.hasJars()) {
- ArtifactFetchManager fetchMgr = new ArtifactFetchManager(flinkConfiguration);
- ArtifactFetchManager.Result res =
- fetchMgr.fetchArtifacts(clusterConfiguration.getJars());
-
- jobJar = res.getJobJar();
- artifacts = res.getArtifacts();
- }
-
- final PackagedProgramRetriever programRetriever =
- DefaultPackagedProgramRetriever.create(
- userLibDir,
- jobJar,
- artifacts,
- clusterConfiguration.getJobClassName(),
- clusterConfiguration.getArgs(),
- flinkConfiguration);
- return programRetriever.getPackagedProgram();
- }
-
- private static void setStaticJobId(
- StandaloneApplicationClusterConfiguration clusterConfiguration,
- Configuration configuration) {
- final JobID jobId = clusterConfiguration.getJobId();
- if (jobId != null) {
- configuration.set(PipelineOptionsInternal.PIPELINE_FIXED_JOB_ID, jobId.toHexString());
- }
+ return ApplicationClusterEntryPointUtils.loadConfiguration(clusterConfiguration);
}
}
diff --git a/flink-container/src/test/java/org/apache/flink/container/entrypoint/ApplicationModeMiniClusterTest.java b/flink-container/src/test/java/org/apache/flink/container/entrypoint/ApplicationModeMiniClusterTest.java
new file mode 100644
index 00000000000..eb80109a4aa
--- /dev/null
+++ b/flink-container/src/test/java/org/apache/flink/container/entrypoint/ApplicationModeMiniClusterTest.java
@@ -0,0 +1,258 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.container.entrypoint;
+
+import org.apache.flink.client.program.PackagedProgram;
+import org.apache.flink.client.program.ProgramInvocationException;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.testutils.OneShotLatch;
+import org.apache.flink.runtime.blob.BlobServer;
+import org.apache.flink.runtime.entrypoint.component.DispatcherResourceManagerComponent;
+import org.apache.flink.runtime.heartbeat.HeartbeatServices;
+import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
+import org.apache.flink.runtime.highavailability.nonha.embedded.EmbeddedHaServices;
+import org.apache.flink.runtime.metrics.MetricRegistry;
+import org.apache.flink.runtime.minicluster.MiniClusterConfiguration;
+import org.apache.flink.runtime.rpc.FatalErrorHandler;
+import org.apache.flink.runtime.security.token.DelegationTokenManager;
+import org.apache.flink.runtime.webmonitor.retriever.MetricQueryServiceRetriever;
+import org.apache.flink.testutils.logging.LoggerAuditingExtension;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.slf4j.event.Level;
+
+import java.time.Duration;
+import java.util.Collection;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.Executor;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Tests for {@link ApplicationModeMiniCluster}. */
+class ApplicationModeMiniClusterTest {
+
+ @RegisterExtension
+ private final LoggerAuditingExtension loggerAuditingExtension =
+ new LoggerAuditingExtension(ApplicationModeMiniCluster.class, Level.WARN);
+
+ private MiniClusterConfiguration miniClusterConfiguration;
+ private PackagedProgram program;
+
+ @BeforeEach
+ void setUp() throws ProgramInvocationException {
+ miniClusterConfiguration = new MiniClusterConfiguration.Builder().build();
+ program =
+ PackagedProgram.newBuilder()
+ .setEntryPointClassName(NoOpProgram.class.getName())
+ .build();
+ }
+
+ @Test
+ void rejectsNullProgram() {
+ assertThatThrownBy(() -> new ApplicationModeMiniCluster(miniClusterConfiguration, null))
+ .isInstanceOf(NullPointerException.class);
+ }
+
+ @Test
+ void futuresIncompleteOnConstruction() {
+ final ApplicationModeMiniCluster miniCluster =
+ new ApplicationModeMiniCluster(miniClusterConfiguration, program);
+
+ assertThat(miniCluster.getApplicationShutDownFuture()).isNotDone();
+ assertThat(miniCluster.getCloseRequestedFuture()).isNotDone();
+ }
+
+ @Test
+ void closeBeforeStartRecordsCloseRequestOnly() {
+ final ApplicationModeMiniCluster miniCluster =
+ new ApplicationModeMiniCluster(miniClusterConfiguration, program);
+
+ final CompletableFuture<Void> closeFuture = miniCluster.closeAsync();
+
+ assertThat(closeFuture).isCompleted();
+ assertThat(miniCluster.getCloseRequestedFuture()).isCompleted();
+ assertThat(miniCluster.getApplicationShutDownFuture())
+ .as("closing the cluster must not look like the application finishing")
+ .isNotDone();
+ }
+
+ @Test
+ void dispatcherNotShutDownBeforeStart() {
+ final ApplicationModeMiniCluster miniCluster =
+ new ApplicationModeMiniCluster(miniClusterConfiguration, program);
+
+ assertThat(miniCluster.isDispatcherShutDown())
+ .as("closing during startup must not clean up the HA data")
+ .isFalse();
+ }
+
+ @Test
+ void closeIsIdempotent() {
+ final ApplicationModeMiniCluster miniCluster =
+ new ApplicationModeMiniCluster(miniClusterConfiguration, program);
+
+ assertThat(miniCluster.closeAsync()).isCompleted();
+ assertThat(miniCluster.closeAsync()).isCompleted();
+ assertThat(miniCluster.getCloseRequestedFuture()).isCompleted();
+ assertThat(miniCluster.getApplicationShutDownFuture()).isNotDone();
+ }
+
+ @Test
+ void taskManagerFatalErrorLoggedAsWarningAfterCloseRequested() {
+ final ApplicationModeMiniCluster miniCluster =
+ new ApplicationModeMiniCluster(miniClusterConfiguration, program);
+ miniCluster.closeAsync();
+
+ miniCluster
+ .createTaskManagerFatalErrorHandler(0)
+ .onFatalError(new RuntimeException("error during shutdown"));
+
+ assertThat(loggerAuditingExtension.getMessages())
+ .containsExactly("TaskManager #0 failed while shutting down.");
+ }
+
+ @Test
+ void failedStartAfterDispatcherCreationDoesNotDeadlock() {
+ final ApplicationModeMiniCluster miniCluster =
+ new ApplicationModeMiniCluster(miniClusterConfiguration, program) {
+ @Override
+ protected Collection<? extends DispatcherResourceManagerComponent>
+ createDispatcherResourceManagerComponents(
+ Configuration configuration,
+ RpcServiceFactory rpcServiceFactory,
+ BlobServer blobServer,
+ HeartbeatServices heartbeatServices,
+ DelegationTokenManager delegationTokenManager,
+ MetricRegistry metricRegistry,
+ MetricQueryServiceRetriever metricQueryServiceRetriever,
+ FatalErrorHandler fatalErrorHandler)
+ throws Exception {
+ super.createDispatcherResourceManagerComponents(
+ configuration,
+ rpcServiceFactory,
+ blobServer,
+ heartbeatServices,
+ delegationTokenManager,
+ metricRegistry,
+ metricQueryServiceRetriever,
+ fatalErrorHandler);
+ throw new Exception("startup failure");
+ }
+ };
+
+ assertThatThrownBy(miniCluster::start).hasMessage("startup failure");
+ }
+
+ @Test
+ void closeDuringStartDoesNotWaitForStart() throws Exception {
+ final OneShotLatch startBlocked = new OneShotLatch();
+ final OneShotLatch unblockStart = new OneShotLatch();
+ final ApplicationModeMiniCluster miniCluster =
+ new ApplicationModeMiniCluster(miniClusterConfiguration, program) {
+ @Override
+ protected Collection<? extends DispatcherResourceManagerComponent>
+ createDispatcherResourceManagerComponents(
+ Configuration configuration,
+ RpcServiceFactory rpcServiceFactory,
+ BlobServer blobServer,
+ HeartbeatServices heartbeatServices,
+ DelegationTokenManager delegationTokenManager,
+ MetricRegistry metricRegistry,
+ MetricQueryServiceRetriever metricQueryServiceRetriever,
+ FatalErrorHandler fatalErrorHandler)
+ throws Exception {
+ startBlocked.trigger();
+ unblockStart.await();
+ return super.createDispatcherResourceManagerComponents(
+ configuration,
+ rpcServiceFactory,
+ blobServer,
+ heartbeatServices,
+ delegationTokenManager,
+ metricRegistry,
+ metricQueryServiceRetriever,
+ fatalErrorHandler);
+ }
+ };
+ final CompletableFuture<Void> startFuture =
+ CompletableFuture.runAsync(
+ () -> {
+ try {
+ miniCluster.start();
+ } catch (Exception e) {
+ throw new CompletionException(e);
+ }
+ });
+ try {
+ startBlocked.await();
+
+ assertThat(CompletableFuture.supplyAsync(miniCluster::closeAsync))
+ .as("closing must not wait for the lock held by start()")
+ .succeedsWithin(Duration.ofSeconds(10));
+ } finally {
+ unblockStart.trigger();
+ startFuture.get();
+ miniCluster.close();
+ }
+ }
+
+ @Test
+ void closeWhileAnotherCloseIsUnderWayWaitsForIt() throws Exception {
+ final OneShotLatch haServicesClosing = new OneShotLatch();
+ final OneShotLatch finishClosingHaServices = new OneShotLatch();
+ final ApplicationModeMiniCluster miniCluster =
+ new ApplicationModeMiniCluster(miniClusterConfiguration, program) {
+ @Override
+ protected HighAvailabilityServices createHighAvailabilityServices(
+ Configuration configuration, Executor executor) {
+ return new EmbeddedHaServices(executor) {
+ @Override
+ public void close() throws Exception {
+ haServicesClosing.trigger();
+ finishClosingHaServices.await();
+ super.close();
+ }
+ };
+ }
+ };
+ miniCluster.start();
+ final CompletableFuture<Void> firstClose = miniCluster.closeAsync();
+ haServicesClosing.await();
+ assertThat(miniCluster.isRunning()).isFalse();
+
+ final CompletableFuture<Void> secondClose = miniCluster.closeAsync();
+ try {
+ assertThat(secondClose)
+ .as("a second close must wait for the close under way")
+ .isNotDone();
+ } finally {
+ finishClosingHaServices.trigger();
+ }
+ assertThat(secondClose).succeedsWithin(Duration.ofSeconds(30));
+ assertThat(firstClose).succeedsWithin(Duration.ofSeconds(30));
+ }
+
+ public static class NoOpProgram {
+ public static void main(String[] args) {}
+ }
+}
diff --git a/flink-container/src/test/java/org/apache/flink/container/entrypoint/MiniClusterJobEntryPointITCase.java b/flink-container/src/test/java/org/apache/flink/container/entrypoint/MiniClusterJobEntryPointITCase.java
new file mode 100644
index 00000000000..0714bbe2b32
--- /dev/null
+++ b/flink-container/src/test/java/org/apache/flink/container/entrypoint/MiniClusterJobEntryPointITCase.java
@@ -0,0 +1,1675 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.container.entrypoint;
+
+import org.apache.flink.api.common.JobID;
+import org.apache.flink.api.common.eventtime.WatermarkStrategy;
+import org.apache.flink.api.common.externalresource.ExternalResourceDriver;
+import org.apache.flink.api.common.externalresource.ExternalResourceDriverFactory;
+import org.apache.flink.api.common.externalresource.ExternalResourceInfo;
+import org.apache.flink.api.common.functions.OpenContext;
+import org.apache.flink.api.common.functions.RichMapFunction;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.connector.source.util.ratelimit.RateLimiterStrategy;
+import org.apache.flink.client.program.PackagedProgram;
+import org.apache.flink.configuration.CheckpointingOptions;
+import org.apache.flink.configuration.ClusterOptions;
+import org.apache.flink.configuration.ConfigConstants;
+import org.apache.flink.configuration.ConfigOption;
+import org.apache.flink.configuration.ConfigOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.DeploymentOptions;
+import org.apache.flink.configuration.ExternalResourceOptions;
+import org.apache.flink.configuration.GlobalConfiguration;
+import org.apache.flink.configuration.HighAvailabilityOptions;
+import org.apache.flink.configuration.JMXServerOptions;
+import org.apache.flink.configuration.JobManagerOptions;
+import org.apache.flink.configuration.MemorySize;
+import org.apache.flink.configuration.PipelineOptionsInternal;
+import org.apache.flink.configuration.RestOptions;
+import org.apache.flink.configuration.RestartStrategyOptions;
+import org.apache.flink.configuration.RpcOptions;
+import org.apache.flink.configuration.StateChangelogOptions;
+import org.apache.flink.configuration.TaskManagerOptions;
+import org.apache.flink.configuration.WebOptions;
+import org.apache.flink.connector.datagen.source.DataGeneratorSource;
+import org.apache.flink.core.failure.FailureEnricher;
+import org.apache.flink.core.failure.FailureEnricherFactory;
+import org.apache.flink.core.testutils.AllCallbackWrapper;
+import org.apache.flink.runtime.clusterframework.ApplicationStatus;
+import org.apache.flink.runtime.clusterframework.TaskExecutorProcessUtils;
+import org.apache.flink.runtime.highavailability.ApplicationResultStoreOptions;
+import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
+import org.apache.flink.runtime.highavailability.HighAvailabilityServicesFactory;
+import org.apache.flink.runtime.highavailability.JobResultStoreOptions;
+import org.apache.flink.runtime.highavailability.nonha.embedded.EmbeddedHaServices;
+import org.apache.flink.runtime.metrics.groups.TaskManagerJobMetricGroup;
+import org.apache.flink.runtime.minicluster.MiniClusterConfiguration;
+import org.apache.flink.runtime.state.LocalRecoveryConfig;
+import org.apache.flink.runtime.state.changelog.StateChangelogStorage;
+import org.apache.flink.runtime.state.changelog.StateChangelogStorageFactory;
+import org.apache.flink.runtime.state.changelog.inmemory.InMemoryStateChangelogStorageFactory;
+import org.apache.flink.runtime.taskexecutor.TaskManagerRunner;
+import org.apache.flink.runtime.util.Hardware;
+import org.apache.flink.runtime.util.TestingFatalErrorHandler;
+import org.apache.flink.runtime.zookeeper.ZooKeeperExtension;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.sink.v2.DiscardingSink;
+import org.apache.flink.util.NetUtils;
+import org.apache.flink.util.jackson.JacksonMapperFactory;
+
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXServiceURL;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.jar.Attributes;
+import java.util.jar.JarEntry;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+import java.util.stream.Collectors;
+import java.util.stream.LongStream;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Runs {@link MiniClusterJobEntryPoint}, configured the way that Flink Kubernetes Operator
+ * configures an application deployment: ZooKeeper HA, a fixed JobID in the config file, the cluster
+ * kept up after the application finishes, and result stores retained on commit.
+ */
+class MiniClusterJobEntryPointITCase {
+
+ private static final Duration TIMEOUT = Duration.ofMinutes(2);
+ private static final Duration POLL_INTERVAL = Duration.ofMillis(200);
+ private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(5);
+
+ /** How long a restarted process has to stay up to count as having survived the restart. */
+ private static final Duration STAYS_UP_WINDOW = Duration.ofSeconds(5);
+
+ @RegisterExtension
+ static final AllCallbackWrapper<ZooKeeperExtension> ZOOKEEPER =
+ new AllCallbackWrapper<>(new ZooKeeperExtension());
+
+ private static final ObjectMapper OBJECT_MAPPER = JacksonMapperFactory.createObjectMapper();
+ private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient();
+
+ @TempDir private Path tempDir;
+
+ private Path confDir;
+ private Path markerFile;
+ private JobID jobId;
+ private Path log4jConfig;
+ private int restPort;
+ private String haClusterId;
+
+ @BeforeEach
+ void writeOperatorStyleConfiguration() throws Exception {
+ confDir = Files.createDirectories(tempDir.resolve("conf"));
+ markerFile = tempDir.resolve("main-invocations");
+ jobId = JobID.generate();
+ try (NetUtils.Port port = NetUtils.getAvailablePort()) {
+ restPort = port.getPort();
+ }
+
+ log4jConfig = tempDir.resolve("log4j2.properties");
+ Files.write(
+ log4jConfig,
+ List.of(
+ "rootLogger.level = INFO",
+ "rootLogger.appenderRef.console.ref = ConsoleAppender",
+ "appender.console.name = ConsoleAppender",
+ "appender.console.type = CONSOLE",
+ "appender.console.layout.type = PatternLayout",
+ "appender.console.layout.pattern = %d{HH:mm:ss,SSS} %-5p %c{1} - %m%n"));
+
+ haClusterId = "minicluster-itcase-" + UUID.randomUUID();
+ final String haStorage = tempDir.resolve("ha").toUri().toString();
+ Files.write(
+ confDir.resolve(GlobalConfiguration.FLINK_CONF_FILENAME),
+ List.of(
+ entry(HighAvailabilityOptions.HA_MODE, "zookeeper"),
+ entry(
+ HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM,
+ ZOOKEEPER.getCustomExtension().getConnectString()),
+ entry(HighAvailabilityOptions.HA_STORAGE_PATH, haStorage),
+ entry(HighAvailabilityOptions.HA_CLUSTER_ID, haClusterId),
+ entry(PipelineOptionsInternal.PIPELINE_FIXED_JOB_ID, jobId.toHexString()),
+ entry(DeploymentOptions.SHUTDOWN_ON_APPLICATION_FINISH, false),
+ entry(DeploymentOptions.SUBMIT_FAILED_JOB_ON_APPLICATION_ERROR, true),
+ entry(JobResultStoreOptions.DELETE_ON_COMMIT, false),
+ entry(ApplicationResultStoreOptions.DELETE_ON_COMMIT, false),
+ entry(RestOptions.ADDRESS, "localhost"),
+ entry(RestOptions.PORT, restPort),
+ entry(RestOptions.BIND_PORT, restPort)));
+ }
+
+ @Test
+ void restartAfterApplicationFinishedDoesNotRerunMain() throws Exception {
+ final Process first = startMiniClusterProcess("first");
+ try {
+ awaitJobState(first, "first", "FINISHED");
+ assertThat(first.isAlive())
+ .as("the process stays up after the application finishes")
+ .isTrue();
+ } finally {
+ // SIGTERM is what Kubernetes sends when pods are deleted
+ stop(first);
+ }
+ assertThat(mainInvocations()).isEqualTo(1);
+ assertThat(zooKeeperNodeExists("/flink/" + haClusterId))
+ .as("stopping the process keeps the HA metadata, although the application finished")
+ .isTrue();
+
+ final Process second = startMiniClusterProcess("second");
+ try {
+ awaitClusterServing(second, "second");
+ assertStaysUp(second, "second");
+ assertThat(mainInvocations())
+ .as("the restarted process must not run main() again")
+ .isEqualTo(1);
+ } finally {
+ stop(second);
+ }
+ }
+
+ @Test
+ void applicationErrorIsReportedAsFailedJobWhileProcessStaysUp() throws Exception {
+ final List<String> arguments = applicationArguments(FailingJob.class, List.of());
+
+ final Process first = startProcess("first", MiniClusterJobEntryPoint.class, arguments);
+ try {
+ awaitJobState(first, "first", "FAILED");
+ assertStaysUp(first, "first");
+ } finally {
+ stop(first);
+ }
+ assertThat(mainInvocations()).isEqualTo(1);
+
+ final Process second = startProcess("second", MiniClusterJobEntryPoint.class, arguments);
+ try {
+ awaitClusterServing(second, "second");
+ assertStaysUp(second, "second");
+ assertThat(mainInvocations())
+ .as("the restarted process must not run main() again")
+ .isEqualTo(1);
+ } finally {
+ stop(second);
+ }
+ }
+
+ @Test
+ void standaloneApplicationClusterRestartAfterApplicationFinishes() throws Exception {
+ final Configuration taskManagerMemory = new Configuration();
+ taskManagerMemory.set(TaskManagerOptions.TOTAL_PROCESS_MEMORY, MemorySize.parse("1536m"));
+
+ final String dynamicConfigs =
+ TaskExecutorProcessUtils.generateDynamicConfigsStr(
+ TaskExecutorProcessUtils.processSpecFromConfig(taskManagerMemory));
+
+ final List<String> taskManagerArguments = new ArrayList<>();
+ Collections.addAll(
+ taskManagerArguments,
+ "--configDir",
+ confDir.toString(),
+ "-D" + TaskManagerOptions.HOST.key() + "=localhost");
+ Collections.addAll(taskManagerArguments, dynamicConfigs.trim().split("\\s+"));
+
+ final Process taskManager =
+ startProcess("taskmanager", TaskManagerRunner.class, taskManagerArguments);
+ try {
+ final Process first = startJobManagerProcess("first");
+ try {
+ awaitJobState(first, "first", "FINISHED");
+ assertThat(first.isAlive())
+ .as("the process stays up after the application finishes")
+ .isTrue();
+ } finally {
+ stop(first);
+ }
+ assertThat(mainInvocations()).isEqualTo(1);
+
+ final Process second = startJobManagerProcess("second");
+ try {
+ awaitClusterServing(second, "second");
+ assertStaysUp(second, "second");
+ assertThat(mainInvocations())
+ .as("the restarted process must not run main() again")
+ .isEqualTo(1);
+ } finally {
+ stop(second);
+ }
+ } catch (AssertionError e) {
+ printLog("taskmanager");
+ throw e;
+ } finally {
+ stop(taskManager);
+ }
+ }
+
+ private Process startJobManagerProcess(String name) throws IOException {
+ final List<String> arguments = new ArrayList<>(applicationArguments());
+ arguments.addAll(0, List.of("-D" + JobManagerOptions.ADDRESS.key() + "=localhost"));
+ return startProcess(name, StandaloneApplicationClusterEntryPoint.class, arguments);
+ }
+
+ /** How the pod's previous process ended. */
+ enum Termination {
+ /** The pod was deleted or rescheduled: the process got to shut down. */
+ SIGTERM,
+ /** The process crashed, was OOM-killed, or its node was lost. */
+ SIGKILL
+ }
+
+ @ParameterizedTest
+ @EnumSource(Termination.class)
+ void restartResumesJobFromLatestCheckpoint(Termination termination) throws Exception {
+ final List<String> arguments = unboundedJobArguments();
+
+ final Process first = startProcess("first", MiniClusterJobEntryPoint.class, arguments);
+ final long lastCheckpointBeforeRestart;
+ try {
+ lastCheckpointBeforeRestart =
+ awaitRest(
+ first,
+ "first",
+ checkpointsPath(),
+ "three completed checkpoints",
+ json -> json.at("/latest/completed/id").asLong() >= 3)
+ .at("/latest/completed/id")
+ .asLong();
+ } finally {
+ if (termination == Termination.SIGKILL) {
+ first.destroyForcibly().waitFor();
+ } else {
+ stop(first);
+ }
+ }
+
+ final Process second = startProcess("second", MiniClusterJobEntryPoint.class, arguments);
+ try {
+ final JsonNode restored =
+ awaitRest(
+ second,
+ "second",
+ checkpointsPath(),
+ "a restored checkpoint",
+ json -> json.at("/latest/restored/id").isNumber())
+ .at("/latest/restored");
+ assertThat(restored.get("is_savepoint").asBoolean()).isFalse();
+ assertThat(restored.get("id").asLong())
+ .as("job resumes from latest checkpoint")
+ .isGreaterThanOrEqualTo(lastCheckpointBeforeRestart);
+
+ awaitJobState(second, "second", "RUNNING");
+ assertThat(second.isAlive()).isTrue();
+ assertThat(mainInvocations())
+ .as("main() runs again when the restarted process recovers the job")
+ .isEqualTo(2);
+ } finally {
+ stop(second);
+ }
+ }
+
+ @Test
+ void restartAfterSigtermRecoversJobWithoutRestartStrategy() throws Exception {
+ // A job failed over by its TaskManager stopping would fail globally without restarts,
+ // which discards its high availability data. Only deployed tasks can be failed over, so
+ // the test waits for them to run.
+ final List<String> arguments =
+ applicationArguments(
+ UnboundedJob.class,
+ List.of(dynamicProperty(RestartStrategyOptions.RESTART_STRATEGY, "none")));
+
+ final Process first = startProcess("first", MiniClusterJobEntryPoint.class, arguments);
+ try {
+ awaitRest(
+ first,
+ "first",
+ "/jobs/" + jobId,
+ "the job's tasks to be running",
+ MiniClusterJobEntryPointITCase::allTasksRunning);
+ } finally {
+ stop(first);
+ }
+
+ final Process second = startProcess("second", MiniClusterJobEntryPoint.class, arguments);
+ try {
+ final Set<String> runningOrTerminal =
+ Set.of("RUNNING", "FAILED", "CANCELED", "FINISHED", "SUSPENDED");
+ final String state =
+ awaitRest(
+ second,
+ "second",
+ "/jobs/" + jobId,
+ "the job to be running or terminal",
+ json -> runningOrTerminal.contains(json.get("state").asText()))
+ .get("state")
+ .asText();
+ assertThat(state).as("the restarted process recovers the job").isEqualTo("RUNNING");
+ } finally {
+ stop(second);
+ }
+ }
+
+ @Test
+ void restartLoopAfterSigkillResumesJobFromLatestCheckpoint() throws Exception {
+ final List<String> arguments = unboundedJobArguments();
+
+ final Process first = startProcess("first", MiniClusterJobEntryPoint.class, arguments);
+ final long lastCheckpointBeforeRestart;
+ try {
+ lastCheckpointBeforeRestart =
+ awaitRest(
+ first,
+ "first",
+ checkpointsPath(),
+ "three completed checkpoints",
+ json -> json.at("/latest/completed/id").asLong() >= 3)
+ .at("/latest/completed/id")
+ .asLong();
+ } finally {
+ first.destroyForcibly().waitFor();
+ }
+
+ final long deadline = System.nanoTime() + TIMEOUT.toNanos();
+ final List<Integer> exitCodes = new ArrayList<>();
+ while (System.nanoTime() < deadline) {
+ final String name = "attempt-" + (exitCodes.size() + 1);
+ final Process attempt = startProcess(name, MiniClusterJobEntryPoint.class, arguments);
+ try {
+ final Optional<JsonNode> restored =
+ pollRest(
+ attempt,
+ checkpointsPath(),
+ json -> json.at("/latest/restored/id").isNumber(),
+ deadline);
+ if (restored.isEmpty()) {
+ exitCodes.add(attempt.exitValue());
+ continue;
+ }
+ System.out.println(
+ "Resumed on attempt "
+ + (exitCodes.size() + 1)
+ + "; earlier attempts exited with "
+ + exitCodes);
+ assertThat(restored.get().at("/latest/restored/id").asLong())
+ .as("the job resumes from latest checkpoint")
+ .isGreaterThanOrEqualTo(lastCheckpointBeforeRestart);
+ awaitJobState(attempt, name, "RUNNING");
+ return;
+ } finally {
+ stop(attempt);
+ }
+ }
+ fail(
+ "The job was not resumed within %s; %d attempts exited with %s.",
+ TIMEOUT, exitCodes.size(), exitCodes);
+ }
+
+ @Test
+ void restoresJobFromSavepointGivenOnCommandLine() throws Exception {
+ final Process first =
+ startProcess("first", MiniClusterJobEntryPoint.class, unboundedJobArguments());
+ final String savepointPath;
+ try {
+ awaitRest(
+ first,
+ "first",
+ checkpointsPath(),
+ "a completed checkpoint",
+ json -> json.at("/latest/completed/id").asLong() >= 1);
+ savepointPath = stopWithSavepoint(first, "first");
+ awaitJobState(first, "first", "FINISHED");
+ } finally {
+ stop(first);
+ }
+
+ // a separate HA cluster, as for a job moved to a new deployment, so that the job can only
+ // be restored from the savepoint and not recovered from HA metadata
+ final List<String> arguments =
+ new ArrayList<>(
+ List.of(
+ "--fromSavepoint",
+ savepointPath,
+ dynamicProperty(
+ HighAvailabilityOptions.HA_CLUSTER_ID,
+ haClusterId + "-restored")));
+ arguments.addAll(unboundedJobArguments());
+
+ final Process second = startProcess("second", MiniClusterJobEntryPoint.class, arguments);
+ try {
+ final JsonNode restored =
+ awaitRest(
+ second,
+ "second",
+ checkpointsPath(),
+ "a restored savepoint",
+ json -> json.at("/latest/restored/id").isNumber())
+ .at("/latest/restored");
+ assertThat(restored.get("is_savepoint").asBoolean()).isTrue();
+ assertThat(restored.get("external_path").asText()).isEqualTo(savepointPath);
+
+ awaitJobState(second, "second", "RUNNING");
+ } finally {
+ stop(second);
+ }
+ }
+
+ /** Stops the job with a savepoint, as the operator does for a savepoint upgrade. */
+ private String stopWithSavepoint(Process process, String name) throws Exception {
+ final JsonNode trigger =
+ postRest(
+ "/jobs/" + jobId + "/stop",
+ OBJECT_MAPPER
+ .createObjectNode()
+ .put(
+ "targetDirectory",
+ tempDir.resolve("savepoints").toUri().toString())
+ .put("drain", false));
+ final JsonNode operation =
+ awaitRest(
+ process,
+ name,
+ "/jobs/"
+ + jobId
+ + "/savepoints/"
+ + trigger.get("request-id").asText(),
+ "the savepoint",
+ json -> "COMPLETED".equals(json.at("/status/id").asText()))
+ .get("operation");
+ assertThat(operation.has("failure-cause"))
+ .as("the savepoint failed: %s", operation.get("failure-cause"))
+ .isFalse();
+ return operation.get("location").asText();
+ }
+
+ private List<String> unboundedJobArguments() {
+ return applicationArguments(
+ UnboundedJob.class,
+ List.of(
+ dynamicProperty(CheckpointingOptions.CHECKPOINTING_INTERVAL, "500 ms"),
+ dynamicProperty(
+ CheckpointingOptions.CHECKPOINTS_DIRECTORY,
+ tempDir.resolve("checkpoints").toUri()),
+ dynamicProperty(HighAvailabilityOptions.ZOOKEEPER_SESSION_TIMEOUT, "5 s")));
+ }
+
+ @Test
+ void fatalErrorExitsProcessWithoutDiscardingHAData() throws Exception {
+ final List<String> arguments = unboundedJobArguments();
+
+ final Process first = startProcess("first", MiniClusterJobEntryPoint.class, arguments);
+ try {
+ awaitRest(
+ first,
+ "first",
+ checkpointsPath(),
+ "a completed checkpoint",
+ json -> json.at("/latest/completed/id").asLong() >= 1);
+ } finally {
+ first.destroyForcibly().waitFor();
+ }
+
+ // break the job's HA state, so that recovering it is a fatal error
+ try (Stream<Path> files = Files.list(tempDir.resolve("ha").resolve(haClusterId))) {
+ for (Path file : (Iterable<Path>) files::iterator) {
+ if (file.getFileName().toString().startsWith("submittedExecutionPlan")) {
+ Files.delete(file);
+ }
+ }
+ }
+
+ final Process second = startProcess("second", MiniClusterJobEntryPoint.class, arguments);
+ try {
+ assertThat(awaitExit(second, "second"))
+ .as("the process exits so supervisor can restart")
+ .isEqualTo(2);
+ assertThat(logFile("second"))
+ .content()
+ .contains(
+ "ERROR ApplicationModeMiniCluster - JobManager failed. Shutting the"
+ + " MiniCluster down.");
+ assertThat(zooKeeperNodeExists(executionPlanZooKeeperPath()))
+ .as("the job's HA metadata survives the error")
+ .isTrue();
+ } finally {
+ stop(second);
+ }
+ }
+
+ @Test
+ void taskManagerFatalErrorExitsProcessWithoutDiscardingHAData() throws Exception {
+ final List<String> arguments =
+ applicationArguments(
+ StuckOnCancelJob.class,
+ List.of(
+ dynamicProperty(
+ CheckpointingOptions.CHECKPOINTING_INTERVAL, "500 ms"),
+ dynamicProperty(
+ TaskManagerOptions.TASK_CANCELLATION_TIMEOUT, "2 s"),
+ dynamicProperty(
+ TaskManagerOptions.TASK_CANCELLATION_INTERVAL, "500 ms")));
+
+ final Process process = startProcess("process", MiniClusterJobEntryPoint.class, arguments);
+ try {
+ assertThat(awaitExit(process, "process"))
+ .as("the process exits so supervisor can restart")
+ .isEqualTo(2);
+ assertThat(logFile("process"))
+ .content()
+ .contains(
+ "ERROR ApplicationModeMiniCluster - TaskManager #0 failed. Shutting the"
+ + " MiniCluster down.");
+ assertThat(zooKeeperNodeExists(executionPlanZooKeeperPath()))
+ .as("the job's HA metadata survives the error")
+ .isTrue();
+ } finally {
+ stop(process);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(classes = {RecordingJob.class, FailingJob.class})
+ void shutdownOnApplicationFinishExitsWithApplicationsExitCode(Class<?> jobClass)
+ throws Exception {
+ final Path webTmpDir = Files.createDirectories(tempDir.resolve("web"));
+ final Process process =
+ startProcess(
+ "process",
+ MiniClusterJobEntryPoint.class,
+ applicationArguments(
+ jobClass,
+ List.of(
+ dynamicProperty(
+ DeploymentOptions.SHUTDOWN_ON_APPLICATION_FINISH,
+ true),
+ dynamicProperty(WebOptions.TMP_DIR, webTmpDir))));
+ try {
+ final ApplicationStatus expected =
+ jobClass == RecordingJob.class
+ ? ApplicationStatus.SUCCEEDED
+ : ApplicationStatus.FAILED;
+ assertThat(awaitExit(process, "process"))
+ .as("the same exit code a standalone application cluster uses for %s", expected)
+ // as the operating system reports it: only the low eight bits survive
+ .isEqualTo(expected.processExitCode() & 0xFF);
+ assertThat(zooKeeperNodeExists("/flink/" + haClusterId))
+ .as("the HA metadata is removed, as by a standalone application cluster")
+ .isFalse();
+ assertThat(webTmpDir).as("the process's web directory is removed").isEmptyDirectory();
+ } finally {
+ stop(process);
+ }
+ }
+
+ @Test
+ void failedShutdownAfterApplicationFinishesExitsWithRuntimeFailureCode() throws Exception {
+ final Process process =
+ startProcess(
+ "process",
+ MiniClusterJobEntryPoint.class,
+ applicationArguments(
+ RecordingJob.class,
+ List.of(
+ dynamicProperty(
+ DeploymentOptions.SHUTDOWN_ON_APPLICATION_FINISH,
+ true),
+ dynamicProperty(
+ HighAvailabilityOptions.HA_MODE,
+ FailingCleanupHaServicesFactory.class.getName()))));
+ try {
+ assertThat(awaitExit(process, "process"))
+ .as(
+ "the exit code a standalone application cluster uses if shutting down fails")
+ .isEqualTo(2);
+ assertThat(logFile("process"))
+ .content()
+ .contains("ERROR MiniClusterJobEntryPoint - Could not close the MiniCluster.")
+ .contains(FailingCleanupHaServicesFactory.FAILURE_MESSAGE)
+ .contains("Application finished with status SUCCEEDED.");
+ } finally {
+ stop(process);
+ }
+ }
+
+ @Test
+ void sigtermDuringShutdownWaitsForTheShutdown() throws Exception {
+ final Process process =
+ startProcess(
+ "process",
+ MiniClusterJobEntryPoint.class,
+ applicationArguments(
+ RecordingJob.class,
+ List.of(
+ dynamicProperty(
+ DeploymentOptions.SHUTDOWN_ON_APPLICATION_FINISH,
+ true),
+ dynamicProperty(
+ HighAvailabilityOptions.HA_MODE,
+ SlowCleanupHaServicesFactory.class.getName()),
+ dynamicProperty(
+ SlowCleanupHaServicesFactory.MARKER_DIR,
+ tempDir))));
+ try {
+ awaitFile(process, "process", tempDir.resolve(SlowCleanupHaServicesFactory.STARTED));
+ process.destroy();
+ awaitExit(process, "process");
+
+ assertThat(tempDir.resolve(SlowCleanupHaServicesFactory.FINISHED))
+ .as("the HA cleanup that was under way when SIGTERM arrived finishes")
+ .exists();
+ } finally {
+ stop(process);
+ }
+ }
+
+ @Test
+ void usesItsOwnWebDirectoryAndRemovesItOnShutdown() throws Exception {
+ final Path webTmpDir = Files.createDirectories(tempDir.resolve("web"));
+ final Process process =
+ startProcess(
+ "process",
+ MiniClusterJobEntryPoint.class,
+ applicationArguments(
+ RecordingJob.class,
+ List.of(dynamicProperty(WebOptions.TMP_DIR, webTmpDir))));
+ try {
+ awaitClusterServing(process, "process");
+ try (Stream<Path> webDirs = Files.list(webTmpDir)) {
+ assertThat(webDirs)
+ .as("a directory of its own, as a cluster entrypoint uses")
+ .singleElement()
+ .satisfies(
+ dir ->
+ assertThat(dir.getFileName().toString())
+ .matches("flink-web-[0-9a-f-]{36}"));
+ }
+
+ stop(process);
+
+ assertThat(webTmpDir).isEmptyDirectory();
+ } finally {
+ stop(process);
+ }
+ }
+
+ @Test
+ void outOfMemoryErrorDuringShutdownExitsProcess() throws Exception {
+ final Process process =
+ startProcess("process", OutOfMemoryErrorAfterCloseProgram.class, List.of());
+ try {
+ assertThat(awaitExit(process, "process"))
+ .as("the exit code a cluster entrypoint uses for fatal errors")
+ .isEqualTo(2);
+ assertThat(logFile("process"))
+ .content()
+ .contains(
+ "ERROR ApplicationModeMiniCluster - TaskManager #0 failed. Terminating"
+ + " the process with exit code 2.");
+ } finally {
+ stop(process);
+ }
+ }
+
+ @Test
+ void runsJobFromJarsGivenAsLocalUris() throws Exception {
+ final Path jar = tempDir.resolve("job.jar");
+ writeJar(jar, RecordingJob.class);
+
+ final Process process =
+ startProcess(
+ "process",
+ MiniClusterJobEntryPoint.class,
+ List.of(
+ "--configDir",
+ confDir.toString(),
+ "--jars",
+ "local://" + jar.toAbsolutePath(),
+ "--",
+ markerFile.toString()));
+ try {
+ awaitJobState(process, "process", "FINISHED");
+ assertThat(mainInvocations()).isEqualTo(1);
+ } finally {
+ stop(process);
+ }
+ }
+
+ @Test
+ void restartAfterApplicationFinishedWithShutdownOnFinishExitsWithoutRerunningMain()
+ throws Exception {
+ final List<String> arguments =
+ applicationArguments(
+ RecordingJob.class,
+ List.of(
+ dynamicProperty(
+ DeploymentOptions.SHUTDOWN_ON_APPLICATION_FINISH, true)));
+
+ final Process first = startProcess("first", MiniClusterJobEntryPoint.class, arguments);
+ try {
+ assertThat(awaitExit(first, "first")).isZero();
+ } finally {
+ stop(first);
+ }
+
+ final Process second = startProcess("second", MiniClusterJobEntryPoint.class, arguments);
+ try {
+ assertThat(awaitExit(second, "second")).isZero();
+ assertThat(mainInvocations())
+ .as("the restarted process must not run main() again")
+ .isEqualTo(1);
+ } finally {
+ stop(second);
+ }
+ }
+
+ @Test
+ void startsJmxServerOnConfiguredPort() throws Exception {
+ final int jmxPort;
+ try (NetUtils.Port port = NetUtils.getAvailablePort()) {
+ jmxPort = port.getPort();
+ }
+ final Process process =
+ startProcess(
+ "process",
+ MiniClusterJobEntryPoint.class,
+ applicationArguments(
+ RecordingJob.class,
+ List.of(
+ dynamicProperty(
+ JMXServerOptions.JMX_SERVER_PORT, jmxPort))));
+ try {
+ awaitClusterServing(process, "process");
+ final JMXServiceURL url =
+ new JMXServiceURL(
+ "service:jmx:rmi://localhost:"
+ + jmxPort
+ + "/jndi/rmi://localhost:"
+ + jmxPort
+ + "/jmxrmi");
+ try (JMXConnector connector = JMXConnectorFactory.connect(url)) {
+ assertThat(connector.getMBeanServerConnection().getMBeanCount()).isPositive();
+ }
+ } finally {
+ stop(process);
+ }
+ }
+
+ @Test
+ void rpcServiceUsesConfiguredThreadPool() throws Exception {
+ final Process process =
+ startProcess(
+ "process",
+ MiniClusterJobEntryPoint.class,
+ applicationArguments(
+ RecordingJob.class,
+ List.of(
+ dynamicProperty(
+ RpcOptions.FORK_JOIN_EXECUTOR_PARALLELISM_MIN, 16),
+ dynamicProperty(
+ RpcOptions.FORK_JOIN_EXECUTOR_PARALLELISM_MAX,
+ 16))));
+ try {
+ // threads are only started on demand, so this waits for the cluster to need more than
+ // the at most 4 threads of the MiniCluster's default pool
+ final long deadline = System.nanoTime() + TIMEOUT.toNanos();
+ long rpcThreads = 0;
+ while (rpcThreads <= 4) {
+ if (!process.isAlive() || System.nanoTime() > deadline) {
+ printLog("process");
+ fail(
+ "Expected more than 4 RPC threads within %s (last seen: %d).",
+ TIMEOUT, rpcThreads);
+ }
+ Thread.sleep(POLL_INTERVAL.toMillis());
+ rpcThreads =
+ queryRest("/jobmanager/thread-dump")
+ .map(MiniClusterJobEntryPointITCase::rpcThreads)
+ .orElse(0L);
+ }
+ } finally {
+ stop(process);
+ }
+ }
+
+ private static long rpcThreads(JsonNode threadDump) {
+ long count = 0;
+ for (JsonNode thread : threadDump.get("threadInfos")) {
+ if (thread.get("threadName")
+ .asText()
+ .startsWith("flink-pekko.actor.default-dispatcher-")) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ @Test
+ void usesDistributedDefaultsInsteadOfMiniClusterTestDefaults() throws Exception {
+ final Process process = startMiniClusterProcess("process");
+ try {
+ final Map<String, String> configuration = clusterConfiguration(process, "process");
+ assertThat(configuration)
+ .containsEntry(RpcOptions.ASK_TIMEOUT_DURATION.key(), "10 s")
+ .containsEntry(
+ ClusterOptions.CLUSTER_IO_EXECUTOR_POOL_SIZE.key(),
+ String.valueOf(4 * Hardware.getNumberCPUCores()));
+ } finally {
+ stop(process);
+ }
+ }
+
+ @Test
+ void keepsConfiguredAskTimeoutAndIoPoolSize() throws Exception {
+ final Process process =
+ startProcess(
+ "process",
+ MiniClusterJobEntryPoint.class,
+ applicationArguments(
+ RecordingJob.class,
+ List.of(
+ "-Dakka.ask.timeout=42 s",
+ dynamicProperty(
+ ClusterOptions.CLUSTER_IO_EXECUTOR_POOL_SIZE, 7))));
+ try {
+ final Map<String, String> configuration = clusterConfiguration(process, "process");
+ assertThat(configuration)
+ .containsEntry("akka.ask.timeout", "42 s")
+ .doesNotContainKey(RpcOptions.ASK_TIMEOUT_DURATION.key())
+ .containsEntry(ClusterOptions.CLUSTER_IO_EXECUTOR_POOL_SIZE.key(), "7");
+ } finally {
+ stop(process);
+ }
+ }
+
+ private Map<String, String> clusterConfiguration(Process process, String name)
+ throws Exception {
+ final Map<String, String> configuration = new HashMap<>();
+ for (JsonNode entry :
+ awaitRest(
+ process,
+ name,
+ "/jobmanager/config",
+ "the cluster configuration",
+ json -> true)) {
+ configuration.put(entry.get("key").asText(), entry.get("value").asText());
+ }
+ return configuration;
+ }
+
+ @Test
+ void loadsChangelogStorageFromPlugins() throws Exception {
+ final Path pluginsDir = tempDir.resolve("plugins");
+ writePluginJar(
+ Files.createDirectories(pluginsDir.resolve("changelog-storage"))
+ .resolve("changelog-storage.jar"),
+ StateChangelogStorageFactory.class,
+ PluginChangelogStorageFactory.class);
+ final Path storageCreated = tempDir.resolve("plugin-changelog-storage-created");
+
+ final Process process =
+ startProcess(
+ "process",
+ MiniClusterJobEntryPoint.class,
+ applicationArguments(
+ UnboundedJob.class,
+ List.of(
+ dynamicProperty(
+ StateChangelogOptions.STATE_CHANGE_LOG_STORAGE,
+ PluginChangelogStorageFactory.IDENTIFIER),
+ "-D"
+ + PluginChangelogStorageFactory.MARKER_FILE_KEY
+ + "="
+ + storageCreated)),
+ Map.of(ConfigConstants.ENV_FLINK_PLUGINS_DIR, pluginsDir.toString()));
+ try {
+ awaitRest(
+ process,
+ "process",
+ "/jobs/" + jobId,
+ "the job's tasks to be running",
+ MiniClusterJobEntryPointITCase::allTasksRunning);
+ assertThat(storageCreated).as("the changelog storage from the plugin is used").exists();
+ } finally {
+ stop(process);
+ }
+ }
+
+ @Test
+ void labelsFailuresWithConfiguredFailureEnrichers() throws Exception {
+ final Path pluginsDir = tempDir.resolve("plugins");
+ writePluginJar(
+ Files.createDirectories(pluginsDir.resolve("failure-enricher"))
+ .resolve("failure-enricher.jar"),
+ FailureEnricherFactory.class,
+ TestFailureEnricherFactory.class,
+ TestFailureEnricher.class);
+
+ final Process process =
+ startProcess(
+ "process",
+ MiniClusterJobEntryPoint.class,
+ applicationArguments(
+ FailingTaskJob.class,
+ List.of(
+ dynamicProperty(
+ RestartStrategyOptions.RESTART_STRATEGY, "none"),
+ dynamicProperty(
+ JobManagerOptions.FAILURE_ENRICHERS_LIST,
+ TestFailureEnricher.class.getName()))),
+ Map.of(ConfigConstants.ENV_FLINK_PLUGINS_DIR, pluginsDir.toString()));
+ try {
+ awaitJobState(process, "process", "FAILED");
+ final JsonNode failure =
+ awaitRest(
+ process,
+ "process",
+ "/jobs/" + jobId + "/exceptions",
+ "the job's failure",
+ json -> !json.at("/exceptionHistory/entries").isEmpty())
+ .at("/exceptionHistory/entries/0");
+ assertThat(failure.at("/failureLabels/" + TestFailureEnricher.KEY).asText())
+ .as("the failure is labelled by the configured enricher")
+ .isEqualTo(TestFailureEnricher.VALUE);
+ } finally {
+ stop(process);
+ }
+ }
+
+ @Test
+ void providesConfiguredExternalResourcesToTasks() throws Exception {
+ final Path pluginsDir = tempDir.resolve("plugins");
+ writePluginJar(
+ Files.createDirectories(pluginsDir.resolve("external-resource"))
+ .resolve("external-resource.jar"),
+ ExternalResourceDriverFactory.class,
+ TestExternalResourceDriverFactory.class,
+ TestExternalResourceInfo.class);
+ final String resource = TestExternalResourceDriverFactory.RESOURCE_NAME;
+ final Path resourcesSeenByTask = tempDir.resolve("external-resources-seen-by-task");
+
+ final Process process =
+ startProcess(
+ "process",
+ MiniClusterJobEntryPoint.class,
+ List.of(
+ "--configDir",
+ confDir.toString(),
+ dynamicProperty(
+ ExternalResourceOptions.EXTERNAL_RESOURCE_LIST, resource),
+ "-D"
+ + ExternalResourceOptions.getAmountConfigOptionForResource(
+ resource)
+ + "=2",
+ "-D"
+ + ExternalResourceOptions
+ .getExternalResourceDriverFactoryConfigOptionForResource(
+ resource)
+ + "="
+ + TestExternalResourceDriverFactory.class.getName(),
+ "--job-classname",
+ ExternalResourceJob.class.getName(),
+ "--",
+ resourcesSeenByTask.toString()),
+ Map.of(ConfigConstants.ENV_FLINK_PLUGINS_DIR, pluginsDir.toString()));
+ try {
+ awaitJobState(process, "process", "FINISHED");
+ assertThat(Files.readAllLines(resourcesSeenByTask))
+ .as("the task gets the configured external resources")
+ .containsExactly("device-0", "device-1");
+ } finally {
+ stop(process);
+ }
+ }
+
+ private Process startMiniClusterProcess(String name) throws IOException {
+ return startProcess(name, MiniClusterJobEntryPoint.class, applicationArguments());
+ }
+
+ private List<String> applicationArguments() {
+ return applicationArguments(RecordingJob.class, List.of());
+ }
+
+ private List<String> applicationArguments(Class<?> jobClass, List<String> dynamicProperties) {
+ final List<String> arguments = new ArrayList<>(List.of("--configDir", confDir.toString()));
+ arguments.addAll(dynamicProperties);
+ arguments.addAll(
+ List.of("--job-classname", jobClass.getName(), "--", markerFile.toString()));
+ return arguments;
+ }
+
+ private Process startProcess(String name, Class<?> mainClass, List<String> arguments)
+ throws IOException {
+ return startProcess(name, mainClass, arguments, Map.of());
+ }
+
+ private Process startProcess(
+ String name,
+ Class<?> mainClass,
+ List<String> arguments,
+ Map<String, String> environment)
+ throws IOException {
+ final List<String> command = new ArrayList<>();
+ command.add(Path.of(System.getProperty("java.home"), "bin", "java").toString());
+ command.add("-Xmx512m");
+ command.add("-Dlog4j.configurationFile=" + log4jConfig.toUri());
+ command.add("-classpath");
+ command.add(System.getProperty("java.class.path"));
+ // registering the DataStream transformation translators reflects into a final map
+ command.add("--add-opens=java.base/java.util=ALL-UNNAMED");
+ // the JMX server's registry (as in the distribution's default env.java.opts.all)
+ command.add("--add-exports=java.rmi/sun.rmi.registry=ALL-UNNAMED");
+ command.add(mainClass.getName());
+ command.addAll(arguments);
+
+ final ProcessBuilder processBuilder =
+ new ProcessBuilder(command)
+ .redirectErrorStream(true)
+ .redirectOutput(logFile(name).toFile());
+ processBuilder.environment().putAll(environment);
+ return processBuilder.start();
+ }
+
+ private void awaitJobState(Process process, String name, String expectedState)
+ throws Exception {
+ final long deadline = System.nanoTime() + TIMEOUT.toNanos();
+ Optional<String> lastState = Optional.empty();
+ while (System.nanoTime() < deadline) {
+ if (!process.isAlive()) {
+ printLog(name);
+ fail(
+ "The %s MiniCluster process exited with code %d"
+ + " while waiting for job %s to reach %s"
+ + " (last seen: %s).",
+ name, process.exitValue(), jobId, expectedState, lastState.orElse("none"));
+ }
+ lastState = queryJobState();
+ if (lastState.filter(expectedState::equals).isPresent()) {
+ return;
+ }
+ Thread.sleep(POLL_INTERVAL.toMillis());
+ }
+ printLog(name);
+ fail(
+ "Job %s did not reach %s in the %s process within %s (last seen: %s).",
+ jobId, expectedState, name, TIMEOUT, lastState.orElse("none"));
+ }
+
+ private Optional<String> queryJobState() throws InterruptedException {
+ return queryRest("/jobs/" + jobId).map(json -> json.get("state").asText());
+ }
+
+ private JsonNode awaitRest(
+ Process process,
+ String name,
+ String path,
+ String description,
+ Predicate<JsonNode> condition)
+ throws Exception {
+ final Optional<JsonNode> result =
+ pollRest(process, path, condition, System.nanoTime() + TIMEOUT.toNanos());
+ if (result.isEmpty()) {
+ printLog(name);
+ fail(
+ "The %s process exited with code %d while waiting for %s.",
+ name, process.exitValue(), description);
+ }
+ return result.get();
+ }
+
+ /**
+ * Polls {@code path} until {@code condition} holds, returning empty if the process exits first,
+ * and failing if the deadline passes.
+ */
+ private Optional<JsonNode> pollRest(
+ Process process, String path, Predicate<JsonNode> condition, long deadlineNanos)
+ throws Exception {
+ Optional<JsonNode> last = Optional.empty();
+ while (System.nanoTime() < deadlineNanos) {
+ if (!process.isAlive()) {
+ return Optional.empty();
+ }
+ last = queryRest(path);
+ if (last.filter(condition).isPresent()) {
+ return last;
+ }
+ Thread.sleep(POLL_INTERVAL.toMillis());
+ }
+ return fail(
+ "%s did not satisfy the condition in time (last: %s).", path, last.orElse(null));
+ }
+
+ /** Waits until the dispatcher has leadership and serves requests. */
+ private void awaitClusterServing(Process process, String name) throws Exception {
+ awaitRest(process, name, "/overview", "the cluster overview", json -> true);
+ }
+
+ private void assertStaysUp(Process process, String name) throws Exception {
+ final long deadline = System.nanoTime() + STAYS_UP_WINDOW.toNanos();
+ while (System.nanoTime() < deadline) {
+ if (!process.isAlive()) {
+ printLog(name);
+ fail(
+ "The %s process exited with code %d within %s of serving requests.",
+ name, process.exitValue(), STAYS_UP_WINDOW);
+ }
+ Thread.sleep(POLL_INTERVAL.toMillis());
+ }
+ }
+
+ private Optional<JsonNode> queryRest(String path) throws InterruptedException {
+ final HttpRequest request =
+ HttpRequest.newBuilder(URI.create("http://localhost:" + restPort + path))
+ .timeout(REQUEST_TIMEOUT)
+ .GET()
+ .build();
+ try {
+ final HttpResponse<String> response =
+ HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
+ if (response.statusCode() != 200) {
+ return Optional.empty();
+ }
+ return Optional.of(OBJECT_MAPPER.readTree(response.body()));
+ } catch (IOException e) {
+ // REST endpoint not up yet
+ return Optional.empty();
+ }
+ }
+
+ private JsonNode postRest(String path, JsonNode body) throws Exception {
+ final HttpRequest request =
+ HttpRequest.newBuilder(URI.create("http://localhost:" + restPort + path))
+ .timeout(REQUEST_TIMEOUT)
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(body.toString()))
+ .build();
+ final HttpResponse<String> response =
+ HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
+ assertThat(response.statusCode())
+ .as("POST %s returned %s", path, response.body())
+ .isBetween(200, 299);
+ return OBJECT_MAPPER.readTree(response.body());
+ }
+
+ private String checkpointsPath() {
+ return "/jobs/" + jobId + "/checkpoints";
+ }
+
+ private static boolean allTasksRunning(JsonNode job) {
+ final JsonNode vertices = job.get("vertices");
+ if (vertices == null || vertices.isEmpty()) {
+ return false;
+ }
+ for (JsonNode vertex : vertices) {
+ if (!"RUNNING".equals(vertex.get("status").asText())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static void stop(Process process) throws InterruptedException {
+ process.destroy();
+ if (!process.waitFor(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) {
+ process.destroyForcibly().waitFor();
+ }
+ }
+
+ private int awaitExit(Process process, String name) throws Exception {
+ if (!process.waitFor(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) {
+ printLog(name);
+ fail("The %s process did not exit within %s.", name, TIMEOUT);
+ }
+ return process.exitValue();
+ }
+
+ private void awaitFile(Process process, String name, Path file) throws Exception {
+ final long deadline = System.nanoTime() + TIMEOUT.toNanos();
+ while (System.nanoTime() < deadline) {
+ if (Files.exists(file)) {
+ return;
+ }
+ if (!process.isAlive()) {
+ printLog(name);
+ fail(
+ "The %s process exited with code %d while waiting for %s.",
+ name, process.exitValue(), file);
+ }
+ Thread.sleep(POLL_INTERVAL.toMillis());
+ }
+ printLog(name);
+ fail("%s was not created by the %s process within %s.", file, name, TIMEOUT);
+ }
+
+ private boolean zooKeeperNodeExists(String path) throws Exception {
+ return ZOOKEEPER
+ .getCustomExtension()
+ .getZooKeeperClient(new TestingFatalErrorHandler())
+ .usingNamespace(null)
+ .checkExists()
+ .forPath(path)
+ != null;
+ }
+
+ private String executionPlanZooKeeperPath() {
+ return "/flink/" + haClusterId + "/execution-plans/" + jobId;
+ }
+
+ /** Writes a jar holding {@code mainClass}, named as the entry class in its manifest. */
+ private static void writeJar(Path jar, Class<?> mainClass) throws IOException {
+ final Manifest manifest = new Manifest();
+ manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
+ manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass.getName());
+ final String entry = mainClass.getName().replace('.', '/') + ".class";
+ try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar), manifest);
+ InputStream classBytes = mainClass.getClassLoader().getResourceAsStream(entry)) {
+ out.putNextEntry(new JarEntry(entry));
+ classBytes.transferTo(out);
+ out.closeEntry();
+ }
+ }
+
+ private static void writePluginJar(
+ Path jar, Class<?> service, Class<?> implementation, Class<?>... otherClasses)
+ throws IOException {
+ try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
+ for (Class<?> pluginClass :
+ Stream.concat(Stream.of(implementation), Stream.of(otherClasses))
+ .toArray(Class<?>[]::new)) {
+ final String entry = pluginClass.getName().replace('.', '/') + ".class";
+ try (InputStream classBytes =
+ pluginClass.getClassLoader().getResourceAsStream(entry)) {
+ out.putNextEntry(new JarEntry(entry));
+ classBytes.transferTo(out);
+ out.closeEntry();
+ }
+ }
+ out.putNextEntry(new JarEntry("META-INF/services/" + service.getName()));
+ out.write(implementation.getName().getBytes(StandardCharsets.UTF_8));
+ out.closeEntry();
+ }
+ }
+
+ private long mainInvocations() throws IOException {
+ return Files.exists(markerFile) ? Files.readAllLines(markerFile).size() : 0;
+ }
+
+ private Path logFile(String name) {
+ return tempDir.resolve(name + ".log");
+ }
+
+ private void printLog(String name) throws IOException {
+ System.out.println("===== " + name + " process log =====");
+ System.out.println(Files.readString(logFile(name)));
+ }
+
+ private static String dynamicProperty(ConfigOption<?> option, Object value) {
+ return "-D" + option.key() + "=" + value;
+ }
+
+ private static String entry(ConfigOption<?> option, Object value) {
+ return option.key() + ": " + value;
+ }
+
+ /** Creates HA services that fail to clean up their data. */
+ public static final class FailingCleanupHaServicesFactory
+ implements HighAvailabilityServicesFactory {
+
+ static final String FAILURE_MESSAGE = "Could not clean up the HA data.";
+
+ @Override
+ public HighAvailabilityServices createHAServices(
+ Configuration configuration, Executor executor) {
+ return new EmbeddedHaServices(executor) {
+ @Override
+ public void cleanupAllData() throws Exception {
+ throw new IOException(FAILURE_MESSAGE);
+ }
+ };
+ }
+ }
+
+ /**
+ * Creates HA services whose cleanup takes a while, writing marker files to the directory given
+ * by {@link #MARKER_DIR} as it starts and finishes.
+ */
+ public static final class SlowCleanupHaServicesFactory
+ implements HighAvailabilityServicesFactory {
+
+ static final ConfigOption<String> MARKER_DIR =
+ ConfigOptions.key("test.ha-cleanup-marker-dir").stringType().noDefaultValue();
+ static final String STARTED = "ha-cleanup-started";
+ static final String FINISHED = "ha-cleanup-finished";
+
+ /**
+ * Long enough to send SIGTERM during, and short enough that it and the rest of the shutdown
+ * finish well within the shutdown hook's timeout, even on a slow machine.
+ */
+ private static final Duration CLEANUP_DURATION = Duration.ofSeconds(1);
+
+ @Override
+ public HighAvailabilityServices createHAServices(
+ Configuration configuration, Executor executor) {
+ final Path markerDir = Path.of(configuration.get(MARKER_DIR));
+ return new EmbeddedHaServices(executor) {
+ @Override
+ public void cleanupAllData() throws Exception {
+ Files.createFile(markerDir.resolve(STARTED));
+ Thread.sleep(CLEANUP_DURATION.toMillis());
+ super.cleanupAllData();
+ Files.createFile(markerDir.resolve(FINISHED));
+ }
+ };
+ }
+ }
+
+ /** Reports an OOM to an {@link ApplicationModeMiniCluster} that is shutting down. */
+ public static final class OutOfMemoryErrorAfterCloseProgram {
+
+ public static void main(String[] args) throws Exception {
+ final ApplicationModeMiniCluster miniCluster =
+ new ApplicationModeMiniCluster(
+ new MiniClusterConfiguration.Builder().build(),
+ PackagedProgram.newBuilder()
+ .setEntryPointClassName(RecordingJob.class.getName())
+ .build());
+ miniCluster.closeAsync();
+
+ miniCluster
+ .createTaskManagerFatalErrorHandler(0)
+ .onFatalError(new OutOfMemoryError("during shutdown"));
+ }
+ }
+
+ public static final class RecordingJob {
+
+ public static void main(String[] args) throws Exception {
+ Files.writeString(
+ Path.of(args[0]),
+ "main()" + System.lineSeparator(),
+ StandardCharsets.UTF_8,
+ StandardOpenOption.CREATE,
+ StandardOpenOption.APPEND);
+
+ final StreamExecutionEnvironment env =
+ StreamExecutionEnvironment.getExecutionEnvironment();
+ env.fromSequence(1, 10).sinkTo(new DiscardingSink<>());
+ env.execute();
+ }
+ }
+
+ /** Writes the ids of the external resources its task gets to the file given as argument. */
+ public static final class ExternalResourceJob {
+
+ public static void main(String[] args) throws Exception {
+ final StreamExecutionEnvironment env =
+ StreamExecutionEnvironment.getExecutionEnvironment();
+ env.fromSequence(1, 1)
+ .map(new RecordExternalResources(args[0]))
+ .sinkTo(new DiscardingSink<>());
+ env.execute();
+ }
+ }
+
+ private static final class RecordExternalResources extends RichMapFunction<Long, Long> {
+
+ private final String outputFile;
+
+ RecordExternalResources(String outputFile) {
+ this.outputFile = outputFile;
+ }
+
+ @Override
+ public void open(OpenContext openContext) throws IOException {
+ final List<String> ids =
+ getRuntimeContext()
+ .getExternalResourceInfos(
+ TestExternalResourceDriverFactory.RESOURCE_NAME)
+ .stream()
+ .map(info -> info.getProperty("id").orElseThrow())
+ .sorted()
+ .collect(Collectors.toList());
+ Files.write(Path.of(outputFile), ids);
+ }
+
+ @Override
+ public Long map(Long value) {
+ return value;
+ }
+ }
+
+ public static final class FailingTaskJob {
+
+ public static void main(String[] args) throws Exception {
+ final StreamExecutionEnvironment env =
+ StreamExecutionEnvironment.getExecutionEnvironment();
+ env.fromSequence(1, 1).map(FailingTaskJob::fail).sinkTo(new DiscardingSink<>());
+ env.execute();
+ }
+
+ private static long fail(long value) {
+ throw new IllegalStateException("The task fails.");
+ }
+ }
+
+ public static final class FailingJob {
+
+ public static void main(String[] args) throws Exception {
+ Files.writeString(
+ Path.of(args[0]),
+ "main()" + System.lineSeparator(),
+ StandardCharsets.UTF_8,
+ StandardOpenOption.CREATE,
+ StandardOpenOption.APPEND);
+ throw new IllegalStateException("The application fails before submitting a job.");
+ }
+ }
+
+ /**
+ * A job that can't be cancelled: one task ignores interrupts, and another fails once the first
+ * is stuck, so the failover's cancellation times out and the TaskManager hits a fatal error.
+ */
+ public static final class StuckOnCancelJob {
+
+ private static volatile boolean stuck;
+
+ public static void main(String[] args) throws Exception {
+ final StreamExecutionEnvironment env =
+ StreamExecutionEnvironment.getExecutionEnvironment();
+ env.fromSequence(1, Long.MAX_VALUE)
+ .map(StuckOnCancelJob::failOnceStuck)
+ .disableChaining()
+ .map(StuckOnCancelJob::ignoreInterrupts)
+ .disableChaining()
+ .sinkTo(new DiscardingSink<>());
+ env.execute();
+ }
+
+ private static long failOnceStuck(long value) {
+ if (stuck) {
+ throw new IllegalStateException("Failing so that the stuck task is cancelled.");
+ }
+ return value;
+ }
+
+ private static long ignoreInterrupts(long value) {
+ stuck = true;
+ while (true) {
+ try {
+ Thread.sleep(Long.MAX_VALUE);
+ } catch (InterruptedException e) {
+ // ignored, like user code that doesn't respond to cancellation
+ }
+ }
+ }
+ }
+
+ public static final class UnboundedJob {
+
+ public static void main(String[] args) throws Exception {
+ Files.writeString(
+ Path.of(args[0]),
+ "main()" + System.lineSeparator(),
+ StandardCharsets.UTF_8,
+ StandardOpenOption.CREATE,
+ StandardOpenOption.APPEND);
+
+ final StreamExecutionEnvironment env =
+ StreamExecutionEnvironment.getExecutionEnvironment();
+ env.fromSource(
+ new DataGeneratorSource<>(
+ index -> index,
+ Long.MAX_VALUE,
+ RateLimiterStrategy.perSecond(10),
+ Types.LONG),
+ WatermarkStrategy.noWatermarks(),
+ "generator")
+ .sinkTo(new DiscardingSink<>());
+ env.execute();
+ }
+ }
+
+ /**
+ * An in-memory changelog storage under another name, which records that it was created. It's
+ * only registered in a plugin jar, not on the classpath.
+ */
+ public static final class PluginChangelogStorageFactory
+ extends InMemoryStateChangelogStorageFactory {
+
+ static final String IDENTIFIER = "plugin";
+ static final String MARKER_FILE_KEY = "test.plugin-changelog-storage.marker-file";
+
+ @Override
+ public String getIdentifier() {
+ return IDENTIFIER;
+ }
+
+ @Override
+ public StateChangelogStorage<?> createStorage(
+ JobID jobID,
+ Configuration configuration,
+ TaskManagerJobMetricGroup metricGroup,
+ LocalRecoveryConfig localRecoveryConfig) {
+ try {
+ Files.writeString(Path.of(configuration.toMap().get(MARKER_FILE_KEY)), "");
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ return super.createStorage(jobID, configuration, metricGroup, localRecoveryConfig);
+ }
+ }
+
+ /** Creates {@link TestFailureEnricher}. It's only registered in a plugin jar. */
+ public static final class TestFailureEnricherFactory implements FailureEnricherFactory {
+
+ @Override
+ public FailureEnricher createFailureEnricher(Configuration conf) {
+ return new TestFailureEnricher();
+ }
+ }
+
+ /** Labels every failure with the same label. */
+ public static final class TestFailureEnricher implements FailureEnricher {
+
+ static final String KEY = "test-label";
+ static final String VALUE = "labelled";
+
+ @Override
+ public Set<String> getOutputKeys() {
+ return Set.of(KEY);
+ }
+
+ @Override
+ public CompletableFuture<Map<String, String>> processFailure(
+ Throwable cause, Context context) {
+ return CompletableFuture.completedFuture(Map.of(KEY, VALUE));
+ }
+ }
+
+ /** Provides as many devices as requested. It's only registered in a plugin jar. */
+ public static final class TestExternalResourceDriverFactory
+ implements ExternalResourceDriverFactory {
+
+ static final String RESOURCE_NAME = "test-device";
+
+ @Override
+ public ExternalResourceDriver createExternalResourceDriver(Configuration config) {
+ return amount ->
+ LongStream.range(0, amount)
+ .mapToObj(index -> new TestExternalResourceInfo("device-" + index))
+ .collect(Collectors.toSet());
+ }
+ }
+
+ private static final class TestExternalResourceInfo implements ExternalResourceInfo {
+
+ private final String id;
+
+ TestExternalResourceInfo(String id) {
+ this.id = id;
+ }
+
+ @Override
+ public Optional<String> getProperty(String key) {
+ return "id".equals(key) ? Optional.of(id) : Optional.empty();
+ }
+
+ @Override
+ public Collection<String> getKeys() {
+ return List.of("id");
+ }
+ }
+}
diff --git a/flink-container/src/test/java/org/apache/flink/container/entrypoint/MiniClusterJobEntryPointTest.java b/flink-container/src/test/java/org/apache/flink/container/entrypoint/MiniClusterJobEntryPointTest.java
new file mode 100644
index 00000000000..f24af10f289
--- /dev/null
+++ b/flink-container/src/test/java/org/apache/flink/container/entrypoint/MiniClusterJobEntryPointTest.java
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.container.entrypoint;
+
+import org.apache.flink.api.common.JobID;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.DeploymentOptions;
+import org.apache.flink.configuration.GlobalConfiguration;
+import org.apache.flink.configuration.PipelineOptionsInternal;
+import org.apache.flink.runtime.entrypoint.FlinkParseException;
+import org.apache.flink.runtime.entrypoint.parser.CommandLineParser;
+import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Tests for {@link MiniClusterJobEntryPoint}. */
+class MiniClusterJobEntryPointTest {
+
+ private static final CommandLineParser<StandaloneApplicationClusterConfiguration> PARSER =
+ new CommandLineParser<>(new StandaloneApplicationClusterConfigurationParserFactory());
+
+ private String confDirPath;
+
+ @BeforeEach
+ void createFlinkConfiguration(@TempDir Path tempFolder) throws IOException {
+ confDirPath = tempFolder.toFile().getAbsolutePath();
+ new File(tempFolder.toFile(), GlobalConfiguration.FLINK_CONF_FILENAME).createNewFile();
+ }
+
+ @Test
+ void programArgsAfterDoubleDashNotReadAsLauncherFlags() throws FlinkParseException {
+ final StandaloneApplicationClusterConfiguration clusterConfiguration =
+ PARSER.parse(
+ new String[] {
+ "--configDir",
+ confDirPath,
+ "--jars",
+ "local:///opt/flink/usrlib/my-job.jar",
+ "--job-classname",
+ "com.acme.MyJob",
+ "--",
+ "--job-classname",
+ "not-a-flag",
+ "--fromSavepoint",
+ "nor-this"
+ });
+
+ assertThat(clusterConfiguration.getJobClassName()).isEqualTo("com.acme.MyJob");
+ assertThat(clusterConfiguration.getArgs())
+ .containsExactly("--job-classname", "not-a-flag", "--fromSavepoint", "nor-this");
+ assertThat(
+ SavepointRestoreSettings.fromConfiguration(loadFrom(clusterConfiguration))
+ .restoreSavepoint())
+ .isFalse();
+ }
+
+ @Test
+ void explicitJobIdTakesPrecedenceOverConfigFile(@TempDir Path tempFolder)
+ throws IOException, FlinkParseException {
+ final JobID fromConfigFile = JobID.generate();
+ final JobID fromCommandLine = JobID.generate();
+ final String otherConfDir = tempFolder.toFile().getAbsolutePath();
+ Files.writeString(
+ tempFolder.resolve(GlobalConfiguration.FLINK_CONF_FILENAME),
+ PipelineOptionsInternal.PIPELINE_FIXED_JOB_ID.key()
+ + ": "
+ + fromConfigFile.toHexString()
+ + System.lineSeparator());
+
+ final StandaloneApplicationClusterConfiguration otherConfig =
+ PARSER.parse(new String[] {"--configDir", otherConfDir});
+ assertThat(loadFrom(otherConfig).get(PipelineOptionsInternal.PIPELINE_FIXED_JOB_ID))
+ .as("with no flag, the config file's value stands")
+ .isEqualTo(fromConfigFile.toHexString());
+
+ final StandaloneApplicationClusterConfiguration overrideConfig =
+ PARSER.parse(
+ new String[] {
+ "--configDir", otherConfDir, "--job-id", fromCommandLine.toHexString()
+ });
+ assertThat(loadFrom(overrideConfig).get(PipelineOptionsInternal.PIPELINE_FIXED_JOB_ID))
+ .as("an explicit --job-id overrides it")
+ .isEqualTo(fromCommandLine.toHexString());
+ }
+
+ @Test
+ void savepointRestoreFromCommandLine() throws FlinkParseException {
+ final Configuration configuration =
+ loadFrom(
+ PARSER.parse(
+ new String[] {
+ "--configDir",
+ confDirPath,
+ "--fromSavepoint",
+ "/some/savepoint",
+ "--allowNonRestoredState"
+ }));
+
+ final SavepointRestoreSettings settings =
+ SavepointRestoreSettings.fromConfiguration(configuration);
+ assertThat(settings.getRestorePath()).isEqualTo("/some/savepoint");
+ assertThat(settings.allowNonRestoredState()).isTrue();
+ }
+
+ @Test
+ void clusterLeftRunningAfterApplicationFinishesWhenConfigured() throws FlinkParseException {
+ final StandaloneApplicationClusterConfiguration defaultConfig =
+ PARSER.parse(new String[] {"--configDir", confDirPath});
+ assertThat(loadFrom(defaultConfig).get(DeploymentOptions.SHUTDOWN_ON_APPLICATION_FINISH))
+ .as("by default, cluster exits when the job finishes")
+ .isTrue();
+
+ final StandaloneApplicationClusterConfiguration customConfig =
+ PARSER.parse(
+ new String[] {
+ "--configDir",
+ confDirPath,
+ "-D" + DeploymentOptions.SHUTDOWN_ON_APPLICATION_FINISH.key() + "=false"
+ });
+ assertThat(loadFrom(customConfig).get(DeploymentOptions.SHUTDOWN_ON_APPLICATION_FINISH))
+ .as("if requested, cluster remains running when the job finishes")
+ .isFalse();
+ }
+
+ private static Configuration loadFrom(
+ StandaloneApplicationClusterConfiguration clusterConfiguration) {
+ return ApplicationClusterEntryPointUtils.loadConfiguration(clusterConfiguration);
+ }
+}
diff --git a/flink-dist/src/main/flink-bin/bin/flink-console.sh b/flink-dist/src/main/flink-bin/bin/flink-console.sh
index ee2d75912ec..7b3e5a417cf 100755
--- a/flink-dist/src/main/flink-bin/bin/flink-console.sh
+++ b/flink-dist/src/main/flink-bin/bin/flink-console.sh
@@ -19,7 +19,7 @@
# Start a Flink service as a console application. Must be stopped with Ctrl-C
# or with SIGTERM by kill or the controlling process.
-USAGE="Usage: flink-console.sh (taskexecutor|zookeeper|historyserver|standalonesession|standalonejob|kubernetes-session|kubernetes-application|kubernetes-taskmanager|sql-gateway) [args]"
+USAGE="Usage: flink-console.sh (taskexecutor|zookeeper|historyserver|standalonesession|standalonejob|kubernetes-session|kubernetes-application|kubernetes-taskmanager|sql-gateway|minicluster) [args]"
SERVICE=$1
ARGS=("${@:2}") # get remaining arguments as array
@@ -50,6 +50,10 @@ case $SERVICE in
CLASS_TO_RUN=org.apache.flink.container.entrypoint.StandaloneApplicationClusterEntryPoint
;;
+ (minicluster)
+ CLASS_TO_RUN=org.apache.flink.container.entrypoint.MiniClusterJobEntryPoint
+ ;;
+
(kubernetes-session)
CLASS_TO_RUN=org.apache.flink.kubernetes.entrypoint.KubernetesSessionClusterEntrypoint
;;
diff --git a/flink-dist/src/main/flink-bin/bin/minicluster.sh b/flink-dist/src/main/flink-bin/bin/minicluster.sh
new file mode 100644
index 00000000000..85f73a6c199
--- /dev/null
+++ b/flink-dist/src/main/flink-bin/bin/minicluster.sh
@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+################################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+################################################################################
+
+# Start a MiniCluster
+USAGE="Usage: minicluster.sh [--jars <jars>] [--job-classname <job class name>] [--job-id <job id>] [--fromSavepoint <path> [--allowNonRestoredState]] [-Dkey=value ...] [-- <program args>]"
+
+if [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
+ echo $USAGE
+ exit 0
+fi
+
+bin=`dirname "$0"`
+bin=`cd "$bin"; pwd`
+
+. "$bin"/config.sh
+
+export FLINK_ENV_JAVA_OPTS="${FLINK_ENV_JAVA_OPTS} ${FLINK_ENV_JAVA_OPTS_JM}"
+
+ARGS=("--configDir" "${FLINK_CONF_DIR}" "$@")
+
+exec "${FLINK_BIN_DIR}"/flink-console.sh minicluster "${ARGS[@]}"
diff --git a/flink-end-to-end-tests/run-nightly-tests.sh b/flink-end-to-end-tests/run-nightly-tests.sh
index 3b84d479836..22ee3a18b8a 100755
--- a/flink-end-to-end-tests/run-nightly-tests.sh
+++ b/flink-end-to-end-tests/run-nightly-tests.sh
@@ -173,6 +173,8 @@ function run_group_2 {
run_test "Flink streaming examples end-to-end test" "$END_TO_END_DIR/test-scripts/test_streaming_examples.sh"
+ run_test "MiniCluster script end-to-end test" "$END_TO_END_DIR/test-scripts/test_minicluster.sh"
+
run_test "Queryable state (rocksdb) end-to-end test" "$END_TO_END_DIR/test-scripts/test_queryable_state.sh rocksdb"
run_test "Queryable state (rocksdb) with TM restart end-to-end test" "$END_TO_END_DIR/test-scripts/test_queryable_state_restart_tm.sh" "skip_check_exceptions"
diff --git a/flink-end-to-end-tests/test-scripts/test_minicluster.sh b/flink-end-to-end-tests/test-scripts/test_minicluster.sh
new file mode 100755
index 00000000000..c8afbc6637d
--- /dev/null
+++ b/flink-end-to-end-tests/test-scripts/test_minicluster.sh
@@ -0,0 +1,149 @@
+#!/usr/bin/env bash
+################################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+################################################################################
+
+# Tests bin/minicluster.sh from the distribution: to verify that it runs an application,
+# that the arguments & JVM options are passed through, and that exit codes pass through
+# the script to/from the JVM
+
+source "$(dirname "$0")"/common.sh
+
+MINICLUSTER_REST_PORT=8091
+JVM_OPTS_MARKER="-Dminicluster.e2e.marker=true"
+WORDCOUNT_RESULT_HASH="5a9945c9ab08890b2a0f6b31a4437d57"
+# a file, as the cleanup runs outside of the subshell that run_test_with_timeout runs the test in
+MINICLUSTER_PID_FILE="${TEST_DATA_DIR}/minicluster.pid"
+
+function minicluster_cleanup() {
+ if [[ -f "${MINICLUSTER_PID_FILE}" ]]; then
+ kill "$(cat "${MINICLUSTER_PID_FILE}")" 2> /dev/null || true
+ fi
+ kill_all 'MiniClusterJobEntryPoint'
+}
+
+on_exit minicluster_cleanup
+
+function assert_exit_code() {
+ local description=$1
+ local expected=$2
+ local actual=$3
+
+ if [[ "${actual}" != "${expected}" ]]; then
+ echo "FAILURE: ${description}: expected exit code ${expected}, but was ${actual}."
+ exit 1
+ fi
+ echo "${description}: exit code ${actual}, as expected."
+}
+
+function assert_minicluster_log_contains() {
+ local description=$1
+ local text=$2
+ local log_dir=${3:-${FLINK_LOG_DIR}}
+
+ if ! grep -q -F -e "${text}" "${log_dir}"/flink-*-minicluster-*.log*; then
+ echo "FAILURE: ${description}: '${text}' not found in the MiniCluster log in ${log_dir}."
+ exit 1
+ fi
+ echo "${description}: found '${text}' in the MiniCluster log."
+}
+
+function run_bounded_application() {
+ echo "Running a bounded application, which the process exits after."
+ local output_dir="${TEST_DATA_DIR}/out/wordcount"
+
+ "${FLINK_DIR}"/bin/minicluster.sh \
+ --jars "local://${FLINK_DIR}/examples/streaming/WordCount.jar" \
+ -- \
+ --input "${END_TO_END_DIR}/test-scripts/test-data/words" \
+ --output "${output_dir}" \
+ --execution-mode BATCH &
+ local pid=$!
+ echo ${pid} > "${MINICLUSTER_PID_FILE}"
+ wait ${pid}
+ assert_exit_code "Bounded application" 0 $?
+
+ local output_files
+ output_files=$(find "${output_dir}" -type f)
+ check_result_hash "WordCount" "${output_files}" "${WORDCOUNT_RESULT_HASH}"
+}
+
+function run_unbounded_application_and_send_sigterm() {
+ echo "Running an unbounded application, and stopping it with SIGTERM."
+
+ set_config_key "env.java.opts.jobmanager" "${JVM_OPTS_MARKER}"
+
+ "${FLINK_DIR}"/bin/minicluster.sh \
+ --jars "local://${FLINK_DIR}/examples/streaming/TopSpeedWindowing.jar" \
+ -Drest.port=${MINICLUSTER_REST_PORT} &
+ local pid=$!
+ echo ${pid} > "${MINICLUSTER_PID_FILE}"
+
+ wait_rest_endpoint_up "http://localhost:${MINICLUSTER_REST_PORT}/jobs/overview" \
+ "MiniCluster" '"state":"RUNNING"'
+
+ # the configuration is logged too, so check the options the JVM was started with
+ local jvm_environment
+ jvm_environment=$(curl ${CURL_SSL_ARGS} -s "http://localhost:${MINICLUSTER_REST_PORT}/jobmanager/environment")
+ if [[ "${jvm_environment}" != *"\"${JVM_OPTS_MARKER}\""* ]]; then
+ echo "FAILURE: the JVM was not started with '${JVM_OPTS_MARKER}': ${jvm_environment%%,\"classpath\"*}"
+ exit 1
+ fi
+ echo "JVM options: started with '${JVM_OPTS_MARKER}'."
+
+ # the script must exec the JVM, so that a supervisor's signals reach it
+ local command
+ command=$(ps -p ${pid} -o comm=)
+ if [[ "${command}" != *java ]]; then
+ echo "FAILURE: process ${pid} started by minicluster.sh is '${command}', not the JVM."
+ exit 1
+ fi
+
+ kill -TERM ${pid}
+ wait ${pid}
+ assert_exit_code "SIGTERM" 143 $?
+
+ assert_minicluster_log_contains "SIGTERM" "RECEIVED SIGNAL 15: SIGTERM"
+ if jps | grep -q 'MiniClusterJobEntryPoint'; then
+ echo "FAILURE: the MiniCluster process is still running after SIGTERM."
+ exit 1
+ fi
+}
+
+function run_application_that_fails_to_start() {
+ echo "Running an application whose job class does not exist."
+ # the expected exception is logged elsewhere, so that the checks of the test logs don't fail
+ local log_dir="${TEST_DATA_DIR}/startup-failure-log"
+
+ FLINK_LOG_DIR="${log_dir}" "${FLINK_DIR}"/bin/minicluster.sh \
+ --job-classname org.apache.flink.e2e.DoesNotExist &
+ local pid=$!
+ echo ${pid} > "${MINICLUSTER_PID_FILE}"
+ wait ${pid}
+ assert_exit_code "Startup failure" 1 $?
+
+ assert_minicluster_log_contains "Startup failure" \
+ "Could not run the application on a MiniCluster." "${log_dir}"
+}
+
+function run_minicluster_test() {
+ run_bounded_application
+ run_unbounded_application_and_send_sigterm
+ run_application_that_fails_to_start
+}
+
+run_test_with_timeout 600 run_minicluster_test
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/entrypoint/ClusterEntrypoint.java b/flink-runtime/src/main/java/org/apache/flink/runtime/entrypoint/ClusterEntrypoint.java
index dca34f97720..3d3f55a7995 100755
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/entrypoint/ClusterEntrypoint.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/entrypoint/ClusterEntrypoint.java
@@ -119,8 +119,8 @@ public abstract class ClusterEntrypoint implements AutoCloseableAsync, FatalErro
protected static final Logger LOG = LoggerFactory.getLogger(ClusterEntrypoint.class);
- protected static final int STARTUP_FAILURE_RETURN_CODE = 1;
- protected static final int RUNTIME_FAILURE_RETURN_CODE = 2;
+ public static final int STARTUP_FAILURE_RETURN_CODE = 1;
+ public static final int RUNTIME_FAILURE_RETURN_CODE = 2;
private static final Duration INITIALIZATION_SHUTDOWN_TIMEOUT = Duration.ofSeconds(30L);
@@ -706,7 +706,7 @@ public abstract class ClusterEntrypoint implements AutoCloseableAsync, FatalErro
return clusterConfigurationParser.parse(args);
}
- protected static Configuration loadConfiguration(
+ public static Configuration loadConfiguration(
EntrypointClusterConfiguration entrypointClusterConfiguration) {
final Configuration dynamicProperties =
ConfigurationUtils.createConfiguration(
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/minicluster/MiniCluster.java b/flink-runtime/src/main/java/org/apache/flink/runtime/minicluster/MiniCluster.java
index 96cd052698a..3fc64fa2ddd 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/minicluster/MiniCluster.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/minicluster/MiniCluster.java
@@ -37,6 +37,7 @@ import org.apache.flink.configuration.StateRecoveryOptions;
import org.apache.flink.core.execution.CheckpointType;
import org.apache.flink.core.execution.RecoveryClaimMode;
import org.apache.flink.core.execution.SavepointFormatType;
+import org.apache.flink.core.failure.FailureEnricher;
import org.apache.flink.runtime.application.AbstractApplication;
import org.apache.flink.runtime.application.ArchivedApplication;
import org.apache.flink.runtime.application.SingleJobApplication;
@@ -172,9 +173,6 @@ public class MiniCluster implements AutoCloseableAsync {
@GuardedBy("lock")
private final List<TaskExecutor> taskManagers;
- private final TerminatingFatalErrorHandlerFactory
- taskManagerTerminatingFatalErrorHandlerFactory =
- new TerminatingFatalErrorHandlerFactory();
private final Supplier<Reference<RpcSystem>> rpcSystemSupplier;
private CompletableFuture<Void> terminationFuture;
@@ -533,7 +531,7 @@ public class MiniCluster implements AutoCloseableAsync {
delegationTokenManager,
metricRegistry,
metricQueryServiceRetriever,
- new ShutDownFatalErrorHandler()));
+ createJobManagerFatalErrorHandler()));
FutureUtils.completeAll(
dispatcherResourceManagerComponents.stream()
@@ -570,7 +568,7 @@ public class MiniCluster implements AutoCloseableAsync {
metricRegistry,
new MemoryArchivedApplicationStore(),
metricQueryServiceRetriever,
- Collections.emptySet(),
+ createFailureEnrichers(configuration),
fatalErrorHandler);
FutureUtils.assertNoException(
dispatcherResourceManagerComponent
@@ -780,10 +778,9 @@ public class MiniCluster implements AutoCloseableAsync {
metricRegistry,
blobCacheService,
useLocalCommunication(),
- ExternalResourceInfoProvider.NO_EXTERNAL_RESOURCES,
+ createExternalResourceInfoProvider(configuration),
workingDirectory.createSubWorkingDirectory("tm_" + taskManagers.size()),
- taskManagerTerminatingFatalErrorHandlerFactory.create(
- taskManagers.size()),
+ createTaskManagerFatalErrorHandler(taskManagers.size()),
delegationTokenReceiverRepository);
taskExecutor.start();
@@ -791,6 +788,41 @@ public class MiniCluster implements AutoCloseableAsync {
}
}
+ /** Creates {@link FailureEnricher}s for the dispatcher's jobs. By default, none are created. */
+ protected Collection<FailureEnricher> createFailureEnrichers(Configuration configuration) {
+ return Collections.emptySet();
+ }
+
+ /**
+ * Creates {@link ExternalResourceInfoProvider} for the TaskManagers. By default, there are no
+ * external resources.
+ */
+ protected ExternalResourceInfoProvider createExternalResourceInfoProvider(
+ Configuration configuration) {
+ return ExternalResourceInfoProvider.NO_EXTERNAL_RESOURCES;
+ }
+
+ /**
+ * Creates the {@link FatalErrorHandler} for the JobManager components and the high availability
+ * services. By default, a fatal error closes the MiniCluster.
+ */
+ protected FatalErrorHandler createJobManagerFatalErrorHandler() {
+ return new ShutDownFatalErrorHandler();
+ }
+
+ /**
+ * Creates the {@link FatalErrorHandler} for the {@link TaskExecutor} with the given index. By
+ * default, a fatal error closes that TaskManager and leaves the rest of the MiniCluster
+ * running.
+ *
+ * @param index into the {@link #taskManagers} collection to identify the correct {@link
+ * TaskExecutor}.
+ */
+ @GuardedBy("lock")
+ protected FatalErrorHandler createTaskManagerFatalErrorHandler(int index) {
+ return new TerminatingFatalErrorHandler(index);
+ }
+
@VisibleForTesting
protected boolean useLocalCommunication() {
return miniClusterConfiguration.getNumTaskManagers() == 1;
@@ -1577,22 +1609,6 @@ public class MiniCluster implements AutoCloseableAsync {
}
}
- private class TerminatingFatalErrorHandlerFactory {
-
- /**
- * Create a new {@link TerminatingFatalErrorHandler} for the {@link TaskExecutor} with the
- * given index.
- *
- * @param index into the {@link #taskManagers} collection to identify the correct {@link
- * TaskExecutor}.
- * @return {@link TerminatingFatalErrorHandler} for the given index
- */
- @GuardedBy("lock")
- private TerminatingFatalErrorHandler create(int index) {
- return new TerminatingFatalErrorHandler(index);
- }
- }
-
/** HA Services to use. */
public enum HaServices {
/** Uses the configured HA Services in {@link HighAvailabilityOptions#HA_MODE} option. */
@@ -1645,7 +1661,7 @@ public class MiniCluster implements AutoCloseableAsync {
public HighAvailabilityServices createHAServices(
Configuration configuration, Executor executor) throws Exception {
return HighAvailabilityServicesUtils.createAvailableOrEmbeddedServices(
- configuration, executor, new ShutDownFatalErrorHandler());
+ configuration, executor, createJobManagerFatalErrorHandler());
}
}
}