fix(kinesisanalytics): start Flink clusters again when Floci restarts (#9390)

Floci's shutdown removes every application's Flink cluster, and nothing
started them again, so after a restart with persistent storage an
application still reported RUNNING with no cluster and no job behind
it.

At startup, each application that was RUNNING or still STARTING goes
back to STARTING, and its cluster starts in the background. A cluster
that outlived Floci is kept when its JobManager, TaskManager and job
still run. Otherwise what survives of it is removed, under the current
or the old floci- names, and the application gets a new cluster, as
StartApplication starts one, in the application's own account, and the
readiness poller runs its job afresh and reports it RUNNING. An
application whose cluster cannot be started goes back to READY, from
which StartApplication starts it again. An application stopped while
its restore is starting the cluster is STOPPING, as AWS reports a stop
in progress, until the restore has removed that cluster by its
containers' IDs, and READY then. StartApplication and DeleteApplication
refuse it meanwhile, so no second start runs under the cluster's names.
One still STOPPING at the next start has what survives of its cluster
removed before it turns READY. Each removal is confirmed with Docker:
while Docker keeps the cluster, the application stays STOPPING and the
cluster stays named and tracked, for shutdown and the next start.
Records stored under the keys of older builds move onto their current
keys first, so no application is restored twice. A start that shutdown
overtakes removes its containers.

Part of #5664.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-25 06:40:37 -04:00
1 parent 874c3d6123
commit 732001a90f
11 files changed
+1480 -52

No files matched your search

+8
View File
@@ -240,6 +240,14 @@ grep -q '/eks/' "$SHARD_FILE" && [ -n "$K3S_IMAGE" ] && pull "$K3S_IMAGE"
# pinned in application.yml too.
RABBITMQ_IMAGE="$(grep -oE 'default-image: *"rabbitmq:[^"]+"' src/main/resources/application.yml | grep -oE '"[^"]+"' | tr -d '"')"
starts AmazonMqBrokerRestartNightlyIntegrationTest && [ -n "$RABBITMQ_IMAGE" ] && pull "$RABBITMQ_IMAGE"
# The nightly KinesisAnalyticsFlinkRestartNightlyIntegrationTest runs a FLINK-1_20 application, whose image
# KinesisAnalyticsRuntimes maps, and the EFS init image chowns its savepoints volume.
FLINK_IMAGE="$(grep -oE '"FLINK-1_20", *"[^"]+"' "$(find src/main/java -name KinesisAnalyticsRuntimes.java -print -quit)" | grep -oE '"apache/flink:[^"]+"' | tr -d '"')"
EFS_INIT_IMAGE="$(grep -oE '^ +init-image: *[^ #]+' src/main/resources/application.yml | head -n 1 | sed 's/.*init-image: *//')"
if starts KinesisAnalyticsFlinkRestartNightlyIntegrationTest; then
[ -n "$FLINK_IMAGE" ] && pull "$FLINK_IMAGE"
[ -n "$EFS_INIT_IMAGE" ] && pull "$EFS_INIT_IMAGE"
fi
if [ -n "$ECR_PUBLIC_IMAGES" ]; then
{ for image in $ECR_PUBLIC_IMAGES; do pull_and_log "$image"; sleep 1; done; } &
fi
+19
View File
@@ -165,6 +165,25 @@ Pass `ApplicationConfiguration.ApplicationSnapshotConfiguration.SnapshotsEnabled
`UpdateApplication`) to disable snapshots for an application — real AWS defaults this to `true`.
`CreateApplicationSnapshot` rejects the request with `InvalidRequestException` while disabled.
### Restarts
Floci removes every application's Flink cluster when it shuts down. With persistent storage, each
application that was `RUNNING`, or still `STARTING`, goes back to `STARTING` when Floci starts again,
and its cluster starts in the background, so Floci reports itself ready without waiting for it. A
cluster that outlived Floci, as when Floci is killed rather than shut down, is kept when its
JobManager, its TaskManager and its job are still running, so the job carries on with its state.
Otherwise what survives of it is removed, and the application gets a new cluster, as
`StartApplication` starts one: its code is read from S3 again, in the application's account, its
job is submitted afresh rather than restored from a snapshot, and the application turns `RUNNING`
once the job runs. Its snapshots stay in their volume.
An application whose cluster can't be started goes back to `READY`, from which `StartApplication`
starts it again, and a `READY` application stays as it is. An application stopped while Floci is
still bringing its cluster back is `STOPPING` until that cluster is removed, and `READY` then;
`StartApplication` and `DeleteApplication` refuse it while it is `STOPPING`. One still `STOPPING`
when Floci stops has what survives of its cluster removed at the next start, and is `READY` then.
While Docker refuses to remove that cluster, the application stays `STOPPING` and the next start
tries again.
### CloudWatch Logs format
The JobManager and TaskManager are started with a `log4j-console.properties` that makes every log
+6
View File
@@ -676,6 +676,12 @@
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>kinesisanalyticsv2</artifactId>
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>applicationautoscaling</artifactId>
@@ -29,6 +29,7 @@ import io.floci.aws.services.elb.ElbClassicService;
import io.floci.aws.services.elbv2.ElbV2Service;
import io.floci.aws.services.floci.ui.FlociUiManager;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.kinesisanalytics.KinesisAnalyticsV2Service;
import io.floci.aws.services.kinesisanalytics.container.FlinkContainerManager;
import io.floci.aws.services.lambda.DynamoDbStreamsEventSourcePoller;
import io.floci.aws.services.lambda.KinesisEventSourcePoller;
@@ -105,6 +106,7 @@ public class EmulatorLifecycle {
private final RabbitMqManager rabbitMqManager;
private final AmazonMqService amazonMqService;
private final FlinkContainerManager flinkContainerManager;
private final KinesisAnalyticsV2Service kinesisAnalyticsService;
private final SageMakerService sageMakerService;
private final RdsService rdsService;
private final TimestreamInfluxDbService timestreamInfluxDbService;
@@ -154,6 +156,7 @@ public class EmulatorLifecycle {
RabbitMqManager rabbitMqManager,
AmazonMqService amazonMqService,
FlinkContainerManager flinkContainerManager,
KinesisAnalyticsV2Service kinesisAnalyticsService,
SageMakerService sageMakerService,
RdsService rdsService,
TimestreamInfluxDbService timestreamInfluxDbService,
@@ -200,6 +203,7 @@ public class EmulatorLifecycle {
this.rabbitMqManager = rabbitMqManager;
this.amazonMqService = amazonMqService;
this.flinkContainerManager = flinkContainerManager;
this.kinesisAnalyticsService = kinesisAnalyticsService;
this.sageMakerService = sageMakerService;
this.rdsService = rdsService;
this.timestreamInfluxDbService = timestreamInfluxDbService;
@@ -317,6 +321,13 @@ public class EmulatorLifecycle {
return null;
});
}
if (config.services().kinesisAnalytics().enabled()) {
// Starts the applications' Flink clusters in the background, failing the future with the ones it could not.
kinesisAnalyticsService.restorePersistedRuntime().exceptionally(ex -> {
LOG.error("Failed to restore persisted Kinesis Analytics V2 applications at startup", ex);
return null;
});
}
if (config.services().elbv2().enabled()) {
elbV2Service.restorePersistedRuntime();
}
@@ -7,9 +7,12 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.common.StripedLocks;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.AccountAwareStorageBackend.AccountEntry;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.kinesisanalytics.container.FlinkContainerManager;
@@ -30,6 +33,9 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -69,6 +75,19 @@ public class KinesisAnalyticsV2Service implements StoredResourceArns {
private final RegionResolver regionResolver;
private final FlinkContainerManager containerManager;
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
/**
* The applications a restore is bringing back, by {@code account:key}, which the readiness poller leaves alone:
* their records still name the old cluster until the restore keeps it or starts a new one. In memory only, so
* after a crash the record keeps what the next start probes a surviving cluster on.
*/
private final Set<String> restoringApplications = ConcurrentHashMap.newKeySet();
/**
* Monitors over one stored application, by {@code account:key}. The restore reads an application again, and ends
* its restore, under its lock, under which {@code StopApplication} finds whether a restore is starting the
* application's cluster. If one is, the stop leaves the application {@code STOPPING} for the restore to finish,
* so the restore never undoes a stop, and no other start or stop runs on the cluster it is starting.
*/
private final StripedLocks storedApplicationLocks = new StripedLocks(256);
@Inject
public KinesisAnalyticsV2Service(StorageFactory storageFactory, EmulatorConfig config,
@@ -330,13 +349,27 @@ public class KinesisAnalyticsV2Service implements StoredResourceArns {
"Application " + applicationName + " cannot be stopped while in state "
+ app.getApplicationStatus() + "; it must be RUNNING or STARTING", 400);
}
if (!config.services().kinesisAnalytics().mock()) {
containerManager.stopCluster(app);
boolean restoring;
synchronized (storedApplicationLock(regionResolver.getAccountId(), applicationKey(region, applicationName))) {
restoring = restoringApplications.contains(restoringKey(app));
if (restoring) {
// The startup restore is starting its cluster, which it removes once that start is through, and the
// application is READY then. Until then it is STOPPING, as AWS reports a stop in progress, which
// StartApplication and DeleteApplication refuse: no other start begins under the cluster's names.
app.setApplicationStatus(ApplicationStatus.STOPPING);
app.setLastUpdateTimestamp(Instant.now());
putApplication(app);
}
}
if (!restoring) {
if (!config.services().kinesisAnalytics().mock()) {
containerManager.stopCluster(app);
}
// Stopping the JobManager is synchronous, so the application returns to READY directly.
app.setApplicationStatus(ApplicationStatus.READY);
app.setLastUpdateTimestamp(Instant.now());
putApplication(app);
}
// Stopping the JobManager is synchronous, so the application returns to READY directly.
app.setApplicationStatus(ApplicationStatus.READY);
app.setLastUpdateTimestamp(Instant.now());
putApplication(app);
LOG.infov("Stopped Kinesis Analytics V2 application {0}", applicationName);
return app;
}
@@ -721,46 +754,285 @@ public class KinesisAnalyticsV2Service implements StoredResourceArns {
"No application found for ARN: " + resourceArn, 400));
}
private void startReadinessPoller() {
poller.scheduleAtFixedRate(() -> {
try {
if (config.services().kinesisAnalytics().mock()) {
return;
}
for (FlinkApplication app : allApplications()) {
boolean changed = false;
if (app.getApplicationStatus() == ApplicationStatus.STARTING) {
String previousJobId = app.getFlinkJobId();
if (containerManager.advanceToRunning(app)) {
LOG.infov("Kinesis Analytics V2 application {0} is now RUNNING",
app.getApplicationName());
app.setApplicationStatus(ApplicationStatus.RUNNING);
app.setLastUpdateTimestamp(Instant.now());
changed = true;
} else if (!Objects.equals(previousJobId, app.getFlinkJobId())) {
// The Flink job was just submitted (flinkJobId newly assigned) but hasn't
// reached RUNNING yet. Persist now rather than waiting for that: pendingJars
// (an in-process-only cache) is already cleared at this point, so if the
// emulator restarts before the next RUNNING-triggered persist, an unpersisted
// flinkJobId would leave the application stuck — it could never re-fetch the
// JAR to resubmit, nor know a job was already running to poll instead.
changed = true;
}
}
for (Snapshot snapshot : app.getSnapshots().values()) {
if (snapshot.getSnapshotStatus() == SnapshotStatus.CREATING
&& containerManager.advanceSnapshot(app, snapshot)) {
changed = true;
}
}
if (changed) {
putApplication(app);
}
}
} catch (Exception e) {
LOG.error("Error in Kinesis Analytics V2 readiness poller", e);
/**
* Brings the persisted applications back after Floci restarts. Shutdown removes their Flink clusters
* ({@link FlinkContainerManager#stopAll}), so an application stored {@code RUNNING}, or still starting, has no
* cluster and no job. Each goes back to {@code STARTING} at once, and the clusters start in the background, so
* Floci does not wait for them to report itself ready; the poller leaves an application alone while its restore
* runs.
*
* <p>An application whose cluster outlived Floci, as when Floci is killed, keeps that cluster when it still
* serves the application, its job and state included. Otherwise it gets a new cluster, as
* {@code StartApplication} starts one, in its own account, which reads its code from S3 again, and the poller
* runs its job and reports it {@code RUNNING}. Like {@code StartApplication}, the job starts afresh rather than
* from a snapshot; the snapshots stay in their volume. An application whose cluster cannot be started is
* returned to {@code READY}, from which {@code StartApplication} starts it again, and a {@code READY} one is left
* as it is. A surviving cluster not kept is removed before a new one starts. An application stopped during its
* restore is {@code STOPPING} until the restore has removed the cluster it kept or started, and {@code READY} then;
* one still {@code STOPPING} at the next start has what survives of its cluster removed, and is {@code READY}
* then. While Docker keeps a cluster the restore removes, its application stays {@code STOPPING}, for a later
* start to remove it. Every application is tried, and the ones that could not be restored
* fail the returned future together. A shutdown during the restore leaves the applications not started yet
* {@code STARTING}, for the next start.
*/
public CompletableFuture<Void> restorePersistedRuntime() {
if (config.services().kinesisAnalytics().mock()) {
return CompletableFuture.completedFuture(null);
}
List<RestoringApplication> pending = new ArrayList<>();
for (AccountEntry<FlinkApplication> entry : persistedApplications()) {
RestoringApplication restoring = prepareRestore(entry.accountId(), entry.key());
if (restoring != null) {
pending.add(restoring);
}
}, 1, 2, TimeUnit.SECONDS);
}
return CompletableFuture.runAsync(() -> {
RuntimeException failure = null;
for (RestoringApplication restoring : pending) {
if (containerManager.isShuttingDown()) {
// Applications not reached yet stay starting, which the next start restores.
break;
}
FlinkApplication app = restoring.app();
try {
String region = regionResolver.regionOf(app.getApplicationArn());
RequestScopes.runAs(restoring.accountId(), region, () -> restoreApplication(restoring));
} catch (FlinkContainerManager.ShuttingDownException e) {
LOG.debugv("Kinesis Analytics V2 application {0} not restored: {1}", app.getApplicationName(),
e.getMessage());
} catch (RuntimeException e) {
RuntimeException restoreFailure = new IllegalStateException("Could not restore Kinesis "
+ "Analytics V2 application " + app.getApplicationName() + " of account "
+ restoring.accountId(), e);
if (failure == null) {
failure = restoreFailure;
} else {
failure.addSuppressed(restoreFailure);
}
} finally {
endRestore(restoring);
}
}
if (failure != null) {
throw failure;
}
});
}
/** Marks an application the restore brings back, under its lock; null for one it leaves as it is. */
private RestoringApplication prepareRestore(String accountId, String key) {
synchronized (storedApplicationLock(accountId, key)) {
FlinkApplication app = storedApplication(accountId, key).orElse(null);
if (app == null || app.getApplicationStatus() == ApplicationStatus.READY) {
return null;
}
if (app.getAccountId() == null) {
app.setAccountId(accountId);
}
restoringApplications.add(restoringKey(app));
// A STOPPING application was stopped during a restore that Floci did not live to finish: the stop stands,
// and its restore removes what survives of its cluster before it turns READY.
if (app.getApplicationStatus() != ApplicationStatus.STOPPING) {
app.setApplicationStatus(ApplicationStatus.STARTING);
}
putApplication(app);
return new RestoringApplication(accountId, key, app);
}
}
private void restoreApplication(RestoringApplication restoring) {
FlinkApplication app = restoring.app();
Object lock = storedApplicationLock(restoring.accountId(), restoring.key());
ApplicationStatus status;
synchronized (lock) {
status = storedStatus(restoring);
}
if (status != ApplicationStatus.STARTING) {
if (status == ApplicationStatus.STOPPING) {
// Stopped while it waited its turn, or before an earlier Floci finished restoring it: a cluster that
// outlived Floci goes too. Nothing else starts one under its names while the application is STOPPING,
// which it is until its restore ends.
containerManager.removeSurvivingCluster(app);
finishStop(restoring);
}
return;
}
boolean kept;
try {
kept = containerManager.adoptRunningCluster(app);
if (!kept) {
// What survives of a cluster not kept goes first, under either name form, so two jobs never run.
containerManager.removeSurvivingCluster(app);
// The job ran on the cluster shutdown removed; the new cluster runs it again.
app.setFlinkJobId(null);
containerManager.startCluster(app);
}
} catch (FlinkContainerManager.ShuttingDownException e) {
throw e;
} catch (RuntimeException e) {
// READY, from which StartApplication starts it again, once its cluster is gone; STOPPING while Docker keeps
// some of it, naming it for a later start to remove.
ApplicationStatus settled = ApplicationStatus.READY;
try {
containerManager.removeOwnCluster(app);
// A start that failed part way cleaned up after itself without confirming it, and forgot its
// containers: what is left under the cluster's names goes too, confirmed.
containerManager.removeSurvivingCluster(app);
} catch (RuntimeException cleanup) {
e.addSuppressed(cleanup);
settled = ApplicationStatus.STOPPING;
}
synchronized (lock) {
if (storedStatus(restoring) != null) {
restoringApplications.remove(restoringKey(app));
app.setApplicationStatus(settled);
app.setLastUpdateTimestamp(Instant.now());
putApplication(app);
}
}
throw e;
}
synchronized (lock) {
if (storedStatus(restoring) == ApplicationStatus.STARTING) {
// Its restore ends here: from now on a stop stops the cluster itself.
restoringApplications.remove(restoringKey(app));
if (kept) {
app.setApplicationStatus(ApplicationStatus.RUNNING);
app.setLastUpdateTimestamp(Instant.now());
}
putApplication(app);
return;
}
}
// Stopped while its cluster started: the cluster goes before the application turns READY, from which another
// start could begin under the same names. Only this cluster goes, by its containers. While Docker keeps some of
// it, this throws and the application stays STOPPING, for a later start to remove the rest.
containerManager.removeOwnCluster(app);
finishStop(restoring);
}
/** Ends the restore of an application stopped during it, now its cluster is gone: it turns {@code READY}. */
private void finishStop(RestoringApplication restoring) {
FlinkApplication app = restoring.app();
synchronized (storedApplicationLock(restoring.accountId(), restoring.key())) {
restoringApplications.remove(restoringKey(app));
if (storedStatus(restoring) == ApplicationStatus.STOPPING) {
app.setApplicationStatus(ApplicationStatus.READY);
app.setLastUpdateTimestamp(Instant.now());
putApplication(app);
}
}
}
/**
* Ends an application's restore, if it has not ended already: the poller and {@code StopApplication} treat the
* application as any other again. One still {@code STOPPING} here, when Docker kept its cluster or shutdown
* overtook its restore, stays so, for the next start to remove what is left.
*/
private void endRestore(RestoringApplication restoring) {
synchronized (storedApplicationLock(restoring.accountId(), restoring.key())) {
restoringApplications.remove(restoringKey(restoring.app()));
}
}
/** The stored application's status, or null when it is gone or another application was created under its name. */
private ApplicationStatus storedStatus(RestoringApplication restoring) {
return storedApplication(restoring.accountId(), restoring.key())
.filter(current -> Objects.equals(current.getCreateTimestamp(), restoring.app().getCreateTimestamp()))
.map(FlinkApplication::getApplicationStatus)
.orElse(null);
}
/**
* The stored applications, each found as a describe finds it, by its account, Region and name. A record stored
* under an older key moves onto its current one, so the restore writing it back leaves no second record behind
* for the next start to restore again.
*/
private List<AccountEntry<FlinkApplication>> persistedApplications() {
List<AccountEntry<FlinkApplication>> stored;
if (storage instanceof AccountAwareStorageBackend<FlinkApplication> aware) {
stored = aware.scanAllAccountEntries(key -> true);
} else {
stored = storage.scan(key -> true).stream()
.map(app -> new AccountEntry<>(Objects.requireNonNullElse(app.getAccountId(),
regionResolver.getDefaultAccountId()), app.getApplicationName(), app))
.toList();
}
Map<String, AccountEntry<FlinkApplication>> applications = new LinkedHashMap<>();
for (AccountEntry<FlinkApplication> entry : stored) {
String accountId = entry.accountId();
String region = regionResolver.regionOf(entry.value().getApplicationArn());
String name = entry.value().getApplicationName();
String key = applicationKey(region, name);
getStoredApplication(accountId, region, name).ifPresent(app ->
applications.put(accountId + ":" + key, new AccountEntry<>(accountId, key, app)));
}
return List.copyOf(applications.values());
}
private Optional<FlinkApplication> storedApplication(String accountId, String key) {
if (storage instanceof AccountAwareStorageBackend<FlinkApplication> aware) {
return aware.getForAccount(accountId, key);
}
return storage.get(key);
}
private Object storedApplicationLock(String accountId, String key) {
return storedApplicationLocks.lockFor(accountId + ":" + key);
}
/** An application the restore brings back, with the account and key it is stored under. */
private record RestoringApplication(String accountId, String key, FlinkApplication app) {
}
private String restoringKey(FlinkApplication app) {
return app.getAccountId() + ":" + app.getApplicationArn();
}
private void startReadinessPoller() {
poller.scheduleAtFixedRate(this::pollReadiness, 1, 2, TimeUnit.SECONDS);
}
/** One pass of the readiness poller: drives each starting application toward RUNNING, and its snapshots. */
void pollReadiness() {
try {
if (config.services().kinesisAnalytics().mock()) {
return;
}
for (FlinkApplication app : allApplications()) {
boolean changed = false;
if (app.getApplicationStatus() == ApplicationStatus.STARTING
&& !restoringApplications.contains(restoringKey(app))) {
String previousJobId = app.getFlinkJobId();
if (containerManager.advanceToRunning(app)) {
LOG.infov("Kinesis Analytics V2 application {0} is now RUNNING",
app.getApplicationName());
app.setApplicationStatus(ApplicationStatus.RUNNING);
app.setLastUpdateTimestamp(Instant.now());
changed = true;
} else if (!Objects.equals(previousJobId, app.getFlinkJobId())) {
// The Flink job was just submitted (flinkJobId newly assigned) but hasn't
// reached RUNNING yet. Persist now rather than waiting for that: pendingJars
// (an in-process-only cache) is already cleared at this point, so if the
// emulator restarts before the next RUNNING-triggered persist, an unpersisted
// flinkJobId would leave the application stuck — it could never re-fetch the
// JAR to resubmit, nor know a job was already running to poll instead.
changed = true;
}
}
for (Snapshot snapshot : app.getSnapshots().values()) {
if (snapshot.getSnapshotStatus() == SnapshotStatus.CREATING
&& containerManager.advanceSnapshot(app, snapshot)) {
changed = true;
}
}
if (changed) {
putApplication(app);
}
}
} catch (Exception e) {
LOG.error("Error in Kinesis Analytics V2 readiness poller", e);
}
}
private List<FlinkApplication> allApplications() {
@@ -3,6 +3,7 @@ package io.floci.aws.services.kinesisanalytics.container;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.dockerjava.api.model.Container;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
@@ -81,6 +82,16 @@ public class FlinkContainerManager {
private final Map<String, byte[]> pendingJars = new ConcurrentHashMap<>();
// Applications whose job submission hard-failed (e.g. a bad JAR) — not retried by the poller.
private final Set<String> submissionFailed = ConcurrentHashMap.newKeySet();
// Set by stopAll(). A start still running when shutdown removes the containers, as a restore's can be while an
// image pulls, removes its own containers rather than leave them behind after the cleanup.
private boolean shuttingDown;
/** Thrown by a start that shutdown overtook; its containers, if any, are already removed. */
public static final class ShuttingDownException extends IllegalStateException {
public ShuttingDownException(String applicationName) {
super("Floci is shutting down; not starting the Flink cluster of application " + applicationName);
}
}
@Inject
public FlinkContainerManager(ContainerBuilder containerBuilder,
@@ -139,6 +150,9 @@ public class FlinkContainerManager {
* StartApplication fast; the JAR is uploaded/run asynchronously by the readiness poller.
*/
public void startCluster(FlinkApplication app) {
if (isShuttingDown()) {
throw new ShuttingDownException(app.getApplicationName());
}
String image = KinesisAnalyticsRuntimes.resolveImage(
config.services().kinesisAnalytics().defaultImage(), app.getRuntimeEnvironment());
String jmName = containerName(app);
@@ -203,8 +217,14 @@ public class FlinkContainerManager {
lifecycleManager.removeIfExists(jmName);
throw e;
}
synchronized (this) {
if (shuttingDown) {
lifecycleManager.stopAndRemove(jm.containerId(), null);
throw new ShuttingDownException(app.getApplicationName());
}
containerIds.put(runtimeKey(app), jm.containerId());
}
app.setContainerId(jm.containerId());
containerIds.put(runtimeKey(app), jm.containerId());
EndpointInfo rest = jm.getEndpoint(JOBMANAGER_REST_PORT);
app.setRestEndpoint("http://" + rest.host() + ":" + rest.port());
attachLogs(app, jm.containerId());
@@ -234,7 +254,12 @@ public class FlinkContainerManager {
msfStyleLog4j2Config(app), true);
ContainerInfo tm = lifecycleManager.startCreated(tmContainerId, tmSpec);
app.setTaskManagerContainerId(tm.containerId());
taskManagerIds.put(runtimeKey(app), tm.containerId());
synchronized (this) {
if (shuttingDown) {
throw new ShuttingDownException(app.getApplicationName());
}
taskManagerIds.put(runtimeKey(app), tm.containerId());
}
} catch (RuntimeException e) {
// Roll back the whole cluster so a failed start leaves nothing behind.
lifecycleManager.removeIfExists(tmName);
@@ -599,12 +624,79 @@ public class FlinkContainerManager {
return app.getDockerVolumeName();
}
/**
* Removes whatever of {@code app}'s cluster outlived Floci, under the current or the legacy {@code floci-} names:
* for a restore that does not keep that cluster, before it starts a new one, and for an application stopped before
* its restore reached it. Nothing else runs a cluster under these names while a restore holds the application.
* The record forgets that cluster and its job, as {@link #stopCluster} leaves it, so a later start submits the
* code again rather than waiting on the old job. Each removal is confirmed: when Docker cannot remove a container
* this throws, and the record still names the cluster.
*/
public void removeSurvivingCluster(FlinkApplication app) {
String name = containerName(app);
// The TaskManager first, as stopCluster does: it shares the JobManager's network namespace.
removeConfirmed(name + "-tm");
removeConfirmed(name);
forgetCluster(app);
}
/** Removes the container under {@code name} and under its legacy form, failing unless Docker confirms both gone. */
private void removeConfirmed(String name) {
lifecycleManager.removeIfExistsStrict(name);
String legacyName = ContainerStorageHelper.legacyDockerName(config, name);
if (!legacyName.equals(name)) {
lifecycleManager.removeIfExistsStrict(legacyName);
}
}
/**
* Removes the cluster {@code app} itself names, by its containers' IDs, for a restore whose application was
* stopped, deleted or created again while that cluster started. What the application's key tracks is cleared only
* while it still names these containers: an application created again under the same name shares the key, and its
* cluster, pending code and logs are left alone. The record forgets the cluster and its job, as
* {@link #stopCluster} leaves it. Each removal is confirmed: when Docker cannot remove a container this throws,
* and the record still names it and it stays tracked, for shutdown and a later attempt to remove.
*/
public void removeOwnCluster(FlinkApplication app) {
String key = runtimeKey(app);
String tmId = app.getTaskManagerContainerId();
if (tmId != null) {
lifecycleManager.stopAndRemove(tmId, null);
// stopAndRemove only logs a removal Docker refused; this throws for it, before the tracking is cleared.
lifecycleManager.removeIfExistsStrict(tmId);
taskManagerIds.remove(key, tmId);
}
String jmId = app.getContainerId();
if (jmId != null) {
Closeable logHandle = jmId.equals(containerIds.get(key)) ? logStreams.get(key) : null;
lifecycleManager.stopAndRemove(jmId, logHandle);
lifecycleManager.removeIfExistsStrict(jmId);
if (containerIds.remove(key, jmId)) {
if (logHandle != null) {
logStreams.remove(key, logHandle);
}
pendingJars.remove(key);
}
}
forgetCluster(app);
}
private static void forgetCluster(FlinkApplication app) {
app.setContainerId(null);
app.setRestEndpoint(null);
app.setTaskManagerContainerId(null);
app.setFlinkJobId(null);
}
/**
* Stops and removes every running Flink container (JobManagers and TaskManagers). Wired into
* {@code EmulatorLifecycle.onStop()} so containers are torn down on shutdown alongside the other
* container managers.
*/
public void stopAll() {
synchronized (this) {
shuttingDown = true;
}
if (!containerIds.isEmpty()) {
LOG.infov("Stopping {0} Flink cluster(s) on shutdown", containerIds.size());
}
@@ -624,6 +716,54 @@ public class FlinkContainerManager {
}
}
/** Whether shutdown has removed the containers, after which no Flink cluster starts. */
public synchronized boolean isShuttingDown() {
return shuttingDown;
}
/**
* Keeps an application's cluster that outlived Floci, as one does when Floci is killed rather than shut down,
* when it still serves the application: its JobManager, and its TaskManager when it runs code, are running, the
* JobManager answers on the REST endpoint the application's record names, and the job the record names is still
* {@code RUNNING}. Its job and its state carry on. The containers are tracked again, so shutdown removes them,
* and the JobManager's logs are streamed again. Returns whether the cluster was kept.
*/
public boolean adoptRunningCluster(FlinkApplication app) {
String rest = app.getRestEndpoint();
if (rest == null || (app.hasCode() && app.getFlinkJobId() == null)) {
return false;
}
Optional<Container> jobManager = runningContainer(containerName(app));
Optional<Container> taskManager = app.hasCode()
? runningContainer(containerName(app) + "-tm") : Optional.empty();
if (jobManager.isEmpty() || (app.hasCode() && taskManager.isEmpty()) || !flinkRest.isRestUp(rest)
|| (app.hasCode() && !"RUNNING".equals(flinkRest.jobState(rest, app.getFlinkJobId())))) {
return false;
}
synchronized (this) {
if (shuttingDown) {
return false;
}
containerIds.put(runtimeKey(app), jobManager.get().getId());
taskManager.ifPresent(container -> taskManagerIds.put(runtimeKey(app), container.getId()));
}
app.setContainerId(jobManager.get().getId());
app.setTaskManagerContainerId(taskManager.map(Container::getId).orElse(null));
attachLogs(app, jobManager.get().getId());
LOG.infov("Kept the running Flink cluster of application {0}", app.getApplicationName());
return true;
}
/** The running container of the name, or of its name before the floci-aws- prefix. */
private Optional<Container> runningContainer(String name) {
Optional<Container> container = lifecycleManager.findByName(name);
String legacyName = ContainerStorageHelper.legacyDockerName(config, name);
if (container.isEmpty() && !legacyName.equals(name)) {
container = lifecycleManager.findByName(legacyName);
}
return container.filter(running -> "running".equals(running.getState()));
}
private void attachLogs(FlinkApplication app, String containerId) {
String shortId = containerId.length() >= 8 ? containerId.substring(0, 8) : containerId;
String logGroup = "/aws/kinesis-analytics/" + app.getApplicationName();
@@ -10,8 +10,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
* <p>Only the states this emulator transitions through are modelled:
* {@code CreateApplication} lands in {@link #READY}; {@code StartApplication} moves
* {@link #STARTING} → {@link #RUNNING} (the backing Flink container coming up);
* {@code StopApplication} returns to {@link #READY}; {@code DeleteApplication} passes
* through {@link #DELETING}.
* {@code StopApplication} returns to {@link #READY}, through {@link #STOPPING} when the startup
* restore is starting the application's cluster; {@code DeleteApplication} passes through
* {@link #DELETING}.
*/
@RegisterForReflection
public enum ApplicationStatus {
@@ -28,6 +28,7 @@ import io.floci.aws.services.elb.ElbClassicService;
import io.floci.aws.services.elbv2.ElbV2Service;
import io.floci.aws.services.floci.ui.FlociUiManager;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.kinesisanalytics.KinesisAnalyticsV2Service;
import io.floci.aws.services.kinesisanalytics.container.FlinkContainerManager;
import io.floci.aws.services.lambda.DynamoDbStreamsEventSourcePoller;
import io.floci.aws.services.lambda.KinesisEventSourcePoller;
@@ -125,6 +126,8 @@ class EmulatorLifecycleTest {
@Mock private EcsService ecsService;
@Mock private SageMakerService sageMakerService;
@Mock private AmazonMqService amazonMqService;
@Mock private KinesisAnalyticsV2Service kinesisAnalyticsService;
@Mock private EmulatorConfig.KinesisAnalyticsServiceConfig kinesisAnalyticsServiceConfig;
@Mock private EmulatorConfig.AmazonMqServiceConfig amazonMqServiceConfig;
@Mock private EmulatorConfig.SageMakerServiceConfig sageMakerServiceConfig;
@Mock private EksService eksService;
@@ -174,6 +177,8 @@ class EmulatorLifecycleTest {
Mockito.lenient().when(eksServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.codeartifact()).thenReturn(codeArtifactServiceConfig);
Mockito.lenient().when(codeArtifactServiceConfig.enabled()).thenReturn(true);
Mockito.lenient().when(servicesConfig.kinesisAnalytics()).thenReturn(kinesisAnalyticsServiceConfig);
Mockito.lenient().when(kinesisAnalyticsServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.amazonmq()).thenReturn(amazonMqServiceConfig);
Mockito.lenient().when(amazonMqServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.sagemaker()).thenReturn(sageMakerServiceConfig);
@@ -193,7 +198,8 @@ class EmulatorLifecycleTest {
elastiCacheProxyManager, rdsContainerManager, rdsProxyManager,
memoryDbContainerManager, memoryDbProxyManager, memoryDbService,
docDbContainerManager, neptuneContainerManager, neptuneProxyManager,
rabbitMqManager, amazonMqService, flinkContainerManager, sageMakerService, rdsService, timestreamInfluxDbService,
rabbitMqManager, amazonMqService, flinkContainerManager, kinesisAnalyticsService,
sageMakerService, rdsService, timestreamInfluxDbService,
elbV2Service, elbClassicService, ecsService,
initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller,
pipesService, ec2MetadataServer, ecsTaskRoleCredentialsServer, ecrRegistryManager, flociUiManager, initLifecycleState,
@@ -522,6 +528,48 @@ class EmulatorLifecycleTest {
verify(initLifecycleState).markReadyCompleted();
}
@Test
void restoresPersistedFlinkApplicationsAfterStorageLoad() {
stubStorageConfig();
when(kinesisAnalyticsServiceConfig.enabled()).thenReturn(true);
when(kinesisAnalyticsService.restorePersistedRuntime()).thenReturn(CompletableFuture.completedFuture(null));
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
InOrder inOrder = Mockito.inOrder(storageFactory, kinesisAnalyticsService);
inOrder.verify(storageFactory).loadAll();
inOrder.verify(kinesisAnalyticsService).restorePersistedRuntime();
}
@Test
void aFailedFlinkRestoreDoesNotStopTheOtherRestores() {
stubStorageConfig();
when(kinesisAnalyticsServiceConfig.enabled()).thenReturn(true);
when(elbv2ServiceConfig.enabled()).thenReturn(true);
when(kinesisAnalyticsService.restorePersistedRuntime()).thenReturn(CompletableFuture.failedFuture(
new IllegalStateException("Could not restore Kinesis Analytics V2 application demo")));
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
verify(elbV2Service).restorePersistedRuntime();
verify(initLifecycleState).markReadyCompleted();
}
@Test
void leavesFlinkApplicationsUntouchedWhenKinesisAnalyticsIsDisabled() {
stubStorageConfig();
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
verify(kinesisAnalyticsService, never()).restorePersistedRuntime();
}
@Test
void restoresPersistedAmazonMqBrokersAfterStorageLoad() {
stubStorageConfig();
@@ -0,0 +1,129 @@
package io.floci.aws.services.kinesisanalytics;
import com.github.dockerjava.api.DockerClient;
import io.floci.aws.services.kinesisanalytics.model.FlinkApplication;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.DockerAvailability;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kinesisanalyticsv2.KinesisAnalyticsV2Client;
import software.amazon.awssdk.services.kinesisanalyticsv2.model.ApplicationDetail;
import software.amazon.awssdk.services.kinesisanalyticsv2.model.ApplicationStatus;
import software.amazon.awssdk.services.kinesisanalyticsv2.model.RunConfiguration;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* #5664: a Managed Service for Apache Flink application comes back after Floci restarts. Shutdown removes the
* application's Flink cluster; the startup restore starts a new one, so the application is RUNNING again and its
* JobManager answers. Removing the JobManager stands in for the shutdown, and the restore is what startup calls.
*
* <p>A nightly check: it runs a real Flink JobManager, which the shared test configuration mocks.
*/
@QuarkusTest
@TestProfile(KinesisAnalyticsFlinkRestartNightlyIntegrationTest.Profile.class)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
// Bounded waits: the Flink image's pull, then the cluster starting twice.
@Timeout(value = 10, unit = TimeUnit.MINUTES)
class KinesisAnalyticsFlinkRestartNightlyIntegrationTest {
/** Real Flink clusters. */
public static final class Profile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.kinesis-analytics.mock", "false");
}
}
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private static final String ROLE = "arn:aws:iam::000000000000:role/x";
private static final Duration APPLICATION_TIMEOUT = Duration.ofMinutes(4);
private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(5)).build();
@Inject
DockerClient dockerClient;
@Inject
KinesisAnalyticsV2Service kinesisAnalyticsService;
@BeforeEach
void requireDocker() {
Assumptions.assumeTrue(DockerAvailability.answers(dockerClient),
"Docker daemon must be available for the Flink restart check");
}
@Test
void anApplicationIsRunningAgainAfterARestart() throws Exception {
String name = "restart-" + UUID.randomUUID().toString().substring(0, 8);
try (KinesisAnalyticsV2Client client = AwsTestClients.create(
KinesisAnalyticsV2Client.builder(), ACCOUNT, Region.of(REGION))) {
client.createApplication(request -> request.applicationName(name).runtimeEnvironment("FLINK-1_20")
.serviceExecutionRole(ROLE));
try {
client.startApplication(request -> request.applicationName(name)
.runConfiguration(RunConfiguration.builder().build()));
awaitRunning(client, name);
FlinkApplication started = kinesisAnalyticsService.describeApplication(name, REGION);
String jobManager = started.getContainerId();
assertEquals(200, overview(started.getRestEndpoint()));
dockerClient.removeContainerCmd(jobManager).withForce(true).exec();
kinesisAnalyticsService.restorePersistedRuntime().join();
awaitRunning(client, name);
FlinkApplication restored = kinesisAnalyticsService.describeApplication(name, REGION);
assertNotEquals(jobManager, restored.getContainerId());
assertEquals(200, overview(restored.getRestEndpoint()));
} finally {
if (describe(client, name).applicationStatus() != ApplicationStatus.READY) {
client.stopApplication(request -> request.applicationName(name));
}
client.deleteApplication(request -> request.applicationName(name)
.createTimestamp(describe(client, name).createTimestamp()));
}
}
}
private static void awaitRunning(KinesisAnalyticsV2Client client, String name) {
await("application " + name + " running").atMost(APPLICATION_TIMEOUT).pollInterval(Duration.ofSeconds(2))
.until(() -> describe(client, name).applicationStatus(), status -> {
if (status == ApplicationStatus.READY) {
throw new AssertionError("application " + name + " went back to READY");
}
return status == ApplicationStatus.RUNNING;
});
}
private static ApplicationDetail describe(KinesisAnalyticsV2Client client, String name) {
return client.describeApplication(request -> request.applicationName(name)).applicationDetail();
}
/** The status of the JobManager's {@code GET /overview}, which answers once the cluster is up. */
private int overview(String restEndpoint) throws Exception {
HttpRequest request = HttpRequest.newBuilder(URI.create(restEndpoint + "/overview"))
.timeout(Duration.ofSeconds(10)).GET().build();
return http.send(request, HttpResponse.BodyHandlers.discarding()).statusCode();
}
}
@@ -17,16 +17,23 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.ResourceAccessMode;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.mockito.InOrder;
import org.mockito.Mockito;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
@@ -781,6 +788,478 @@ class KinesisAnalyticsV2ServiceTest {
}
}
/**
* #5664: shutdown removes every application's Flink cluster. After a restart an application that was running
* or starting goes back to STARTING and gets a new cluster, its old job cleared, in every account; the poller
* leaves it alone while its restore runs, and a READY application stays as it is.
*/
@Test
void restoringStartsARunningOrStartingApplicationAgain() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
KinesisAnalyticsV2Service[] holder = new KinesisAnalyticsV2Service[1];
Mockito.doAnswer(start -> {
FlinkApplication app = start.getArgument(0);
assertEquals(ApplicationStatus.STARTING, app.getApplicationStatus());
assertNull(app.getFlinkJobId(), "the old job ran on the removed cluster");
holder[0].pollReadiness();
// The poller must not drive an application whose restore is running toward its old cluster.
Mockito.verify(manager, Mockito.never()).advanceToRunning(
Mockito.argThat(probed -> app.getApplicationName().equals(probed.getApplicationName())));
app.setRestEndpoint("http://new-jm:8081");
return null;
}).when(manager).startCluster(Mockito.any());
KinesisAnalyticsV2Service restoring = buildService(false, manager, store);
holder[0] = restoring;
FlinkApplication withoutAccount = storedApplication("running", "111111111111", "us-west-2",
ApplicationStatus.RUNNING);
// A record saved before applications carried their account: the account it is stored under owns it.
withoutAccount.setAccountId(null);
store.putForAccount("111111111111", "us-west-2/running", withoutAccount);
store.putForAccount("000000000000", "us-east-1/starting",
storedApplication("starting", "000000000000", "us-east-1", ApplicationStatus.STARTING));
store.putForAccount("000000000000", "us-east-1/ready",
storedApplication("ready", "000000000000", "us-east-1", ApplicationStatus.READY));
restoring.restorePersistedRuntime().join();
FlinkApplication running = store.getForAccount("111111111111", "us-west-2/running").orElseThrow();
assertEquals(ApplicationStatus.STARTING, running.getApplicationStatus());
assertEquals("111111111111", running.getAccountId());
assertTrue(store.getForAccount("000000000000", "us-west-2/running").isEmpty());
assertEquals("http://new-jm:8081", running.getRestEndpoint());
assertEquals(ApplicationStatus.STARTING,
store.getForAccount("000000000000", "us-east-1/starting").orElseThrow().getApplicationStatus());
assertEquals(ApplicationStatus.READY,
store.getForAccount("000000000000", "us-east-1/ready").orElseThrow().getApplicationStatus());
Mockito.verify(manager, Mockito.times(2)).startCluster(Mockito.any());
Mockito.verify(manager, Mockito.never()).startCluster(
Mockito.argThat(app -> "ready".equals(app.getApplicationName())));
// Once the restore is done, the poller drives the application to RUNNING on its new cluster.
when(manager.advanceToRunning(Mockito.argThat(app -> "running".equals(app.getApplicationName()))))
.thenReturn(true);
restoring.pollReadiness();
assertEquals(ApplicationStatus.RUNNING,
store.getForAccount("111111111111", "us-west-2/running").orElseThrow().getApplicationStatus());
}
/** An application whose cluster outlived Floci keeps it, and with it its running job. */
@Test
void anApplicationWhoseClusterSurvivedKeepsIt() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
when(manager.adoptRunningCluster(Mockito.any())).thenReturn(true);
KinesisAnalyticsV2Service restoring = buildService(false, manager, store);
store.putForAccount("000000000000", "us-east-1/kept",
storedApplication("kept", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
restoring.restorePersistedRuntime().join();
FlinkApplication kept = store.getForAccount("000000000000", "us-east-1/kept").orElseThrow();
assertEquals(ApplicationStatus.RUNNING, kept.getApplicationStatus());
assertEquals("job-1", kept.getFlinkJobId());
Mockito.verify(manager, Mockito.never()).startCluster(Mockito.any());
}
/**
* An application whose cluster cannot be started goes back to READY, from which StartApplication starts it
* again, and leaves the others to restore; its failure fails the future.
*/
@Test
void anApplicationThatCannotBeRestoredGoesBackToReady() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
RuntimeException cause = new IllegalStateException("docker unavailable");
Mockito.doThrow(cause).when(manager).startCluster(
Mockito.argThat(app -> "first".equals(app.getApplicationName())));
KinesisAnalyticsV2Service restoring = buildService(false, manager, store);
store.putForAccount("000000000000", "us-east-1/first",
storedApplication("first", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
store.putForAccount("000000000000", "us-east-1/second",
storedApplication("second", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
CompletionException thrown = assertThrows(CompletionException.class,
() -> restoring.restorePersistedRuntime().join());
assertEquals("Could not restore Kinesis Analytics V2 application first of account 000000000000",
thrown.getCause().getMessage());
assertSame(cause, thrown.getCause().getCause());
assertEquals(ApplicationStatus.READY,
store.getForAccount("000000000000", "us-east-1/first").orElseThrow().getApplicationStatus());
Mockito.verify(manager).removeOwnCluster(Mockito.argThat(app -> "first".equals(app.getApplicationName())));
// What survived Floci goes before the start, and what the failed start left under the cluster's names after
// it, before the application is READY.
Mockito.verify(manager, Mockito.times(2)).removeSurvivingCluster(
Mockito.argThat(app -> "first".equals(app.getApplicationName())));
assertEquals(ApplicationStatus.STARTING,
store.getForAccount("000000000000", "us-east-1/second").orElseThrow().getApplicationStatus());
}
/**
* An application stopped while its new cluster starts is STOPPING until the restore has removed that cluster, as
* AWS reports a stop in progress, so StartApplication and DeleteApplication refuse it until then and no second
* start runs under the cluster's names. It is READY after, and starts again as usual.
*/
@Test
void anApplicationStoppedWhileItsClusterStartsIsStoppingUntilTheClusterIsGone() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
KinesisAnalyticsV2Service[] restoring = new KinesisAnalyticsV2Service[1];
AtomicBoolean restoreStart = new AtomicBoolean(true);
Mockito.doAnswer(start -> {
if (restoreStart.getAndSet(false)) {
FlinkApplication app = start.getArgument(0);
assertEquals(ApplicationStatus.STOPPING,
restoring[0].stopApplication("stopped", "us-east-1").getApplicationStatus());
AwsException restart = assertThrows(AwsException.class,
() -> restoring[0].startApplication("stopped", "us-east-1"));
assertEquals("ResourceInUseException", restart.getErrorCode());
AwsException delete = assertThrows(AwsException.class,
() -> restoring[0].deleteApplication("stopped", app.getCreateTimestamp(), "us-east-1"));
assertEquals("ResourceInUseException", delete.getErrorCode());
}
return null;
}).when(manager).startCluster(Mockito.any());
restoring[0] = buildService(false, manager, store);
store.putForAccount("000000000000", "us-east-1/stopped",
storedApplication("stopped", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
restoring[0].restorePersistedRuntime().join();
// The restore removed the cluster it started, by its containers; the stop itself left the cluster alone.
Mockito.verify(manager).removeOwnCluster(Mockito.argThat(app -> "stopped".equals(app.getApplicationName())));
Mockito.verify(manager, Mockito.never()).stopCluster(Mockito.any());
Mockito.clearInvocations(manager);
assertEquals(ApplicationStatus.READY,
store.getForAccount("000000000000", "us-east-1/stopped").orElseThrow().getApplicationStatus());
restoring[0].startApplication("stopped", "us-east-1");
Mockito.verify(manager).startCluster(Mockito.any());
// Its restore is over: a stop now stops the cluster itself and leaves the application READY at once.
assertEquals(ApplicationStatus.READY,
restoring[0].stopApplication("stopped", "us-east-1").getApplicationStatus());
Mockito.verify(manager).stopCluster(Mockito.argThat(app -> "stopped".equals(app.getApplicationName())));
}
/** Once its restore is through, an application stops as any other: its cluster goes, and it is READY at once. */
@Test
void anApplicationStopsAsUsualOnceItsRestoreIsThrough() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
KinesisAnalyticsV2Service restoring = buildService(false, manager, store);
store.putForAccount("000000000000", "us-east-1/restored",
storedApplication("restored", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
restoring.restorePersistedRuntime().join();
assertEquals(ApplicationStatus.READY,
restoring.stopApplication("restored", "us-east-1").getApplicationStatus());
Mockito.verify(manager).stopCluster(Mockito.argThat(app -> "restored".equals(app.getApplicationName())));
}
/** An application deleted and created again, and started, while its old cluster starts keeps what it has. */
@Test
void anApplicationCreatedAgainWhileItsClusterStartsIsNotOverwritten() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
FlinkApplication again = storedApplication("again", "000000000000", "us-east-1", ApplicationStatus.STARTING);
Mockito.doAnswer(start -> {
FlinkApplication app = start.getArgument(0);
again.setCreateTimestamp(app.getCreateTimestamp().plusSeconds(60));
again.setRestEndpoint("http://new-jm:8081");
store.putForAccount("000000000000", "us-east-1/again", again);
return null;
}).when(manager).startCluster(Mockito.any());
KinesisAnalyticsV2Service restoring = buildService(false, manager, store);
store.putForAccount("000000000000", "us-east-1/again",
storedApplication("again", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
restoring.restorePersistedRuntime().join();
FlinkApplication stored = store.getForAccount("000000000000", "us-east-1/again").orElseThrow();
assertSame(again, stored);
assertEquals("http://new-jm:8081", stored.getRestEndpoint());
// Only the restore's own cluster goes, not what the manager tracks for the application created again.
Mockito.verify(manager).removeOwnCluster(Mockito.argThat(app -> app != again));
Mockito.verify(manager, Mockito.never()).stopCluster(Mockito.any());
}
/**
* An application stopped while the restore starts another one is not started: a cluster that outlived Floci goes,
* and it is READY once its turn comes.
*/
@Test
void anApplicationStoppedWhileItWaitsIsNotStarted() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
KinesisAnalyticsV2Service[] restoring = new KinesisAnalyticsV2Service[1];
List<String> stopped = new ArrayList<>();
Mockito.doAnswer(start -> {
FlinkApplication app = start.getArgument(0);
String waiting = "first".equals(app.getApplicationName()) ? "second" : "first";
assertEquals(ApplicationStatus.STOPPING,
restoring[0].stopApplication(waiting, "us-east-1").getApplicationStatus());
stopped.add(waiting);
return null;
}).when(manager).startCluster(Mockito.any());
restoring[0] = buildService(false, manager, store);
store.putForAccount("000000000000", "us-east-1/first",
storedApplication("first", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
store.putForAccount("000000000000", "us-east-1/second",
storedApplication("second", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
restoring[0].restorePersistedRuntime().join();
Mockito.verify(manager, Mockito.times(1)).startCluster(Mockito.any());
String waiting = stopped.getFirst();
Mockito.verify(manager).removeSurvivingCluster(
Mockito.argThat(app -> waiting.equals(app.getApplicationName())));
assertEquals(ApplicationStatus.READY,
store.getForAccount("000000000000", "us-east-1/" + waiting).orElseThrow().getApplicationStatus());
// Its restore is over: started again and stopped, it is READY at once.
Mockito.doNothing().when(manager).startCluster(Mockito.any());
restoring[0].startApplication(waiting, "us-east-1");
assertEquals(ApplicationStatus.READY,
restoring[0].stopApplication(waiting, "us-east-1").getApplicationStatus());
}
/**
* An application stopped during a restore that Floci did not live to finish is not started at the next start:
* what survives of its cluster is removed, and it is READY then.
*/
@Test
void aStopFlociDidNotLiveToFinishStandsAtTheNextStart() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
store.putForAccount("000000000000", "us-east-1/stopping",
storedApplication("stopping", "000000000000", "us-east-1", ApplicationStatus.STOPPING));
buildService(false, manager, store).restorePersistedRuntime().join();
assertEquals(ApplicationStatus.READY,
store.getForAccount("000000000000", "us-east-1/stopping").orElseThrow().getApplicationStatus());
Mockito.verify(manager).removeSurvivingCluster(
Mockito.argThat(app -> "stopping".equals(app.getApplicationName())));
Mockito.verify(manager, Mockito.never()).startCluster(Mockito.any());
}
/** A surviving cluster the restore does not keep is removed, under either name form, before a new one starts. */
@Test
void aClusterNotKeptIsRemovedBeforeANewOneStarts() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
store.putForAccount("000000000000", "us-east-1/replaced",
storedApplication("replaced", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
buildService(false, manager, store).restorePersistedRuntime().join();
InOrder order = Mockito.inOrder(manager);
order.verify(manager).adoptRunningCluster(Mockito.any());
order.verify(manager).removeSurvivingCluster(
Mockito.argThat(app -> "replaced".equals(app.getApplicationName())));
order.verify(manager).startCluster(Mockito.argThat(app -> "replaced".equals(app.getApplicationName())));
}
/**
* A shutdown overtaking the start of an application stopped meanwhile leaves it STOPPING, and the next start
* removes what survives of its cluster and leaves it READY: the stop stands.
*/
@Test
void aShutdownDuringTheStartOfAStoppedApplicationLeavesTheStopToTheNextStart() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
KinesisAnalyticsV2Service[] restoring = new KinesisAnalyticsV2Service[1];
Mockito.doAnswer(start -> {
restoring[0].stopApplication("overtaken", "us-east-1");
throw new FlinkContainerManager.ShuttingDownException("overtaken");
}).when(manager).startCluster(Mockito.any());
restoring[0] = buildService(false, manager, store);
store.putForAccount("000000000000", "us-east-1/overtaken",
storedApplication("overtaken", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
restoring[0].restorePersistedRuntime().join();
assertEquals(ApplicationStatus.STOPPING,
store.getForAccount("000000000000", "us-east-1/overtaken").orElseThrow().getApplicationStatus());
FlinkContainerManager next = Mockito.mock(FlinkContainerManager.class);
buildService(false, next, store).restorePersistedRuntime().join();
Mockito.verify(next).removeSurvivingCluster(Mockito.any());
assertEquals(ApplicationStatus.READY,
store.getForAccount("000000000000", "us-east-1/overtaken").orElseThrow().getApplicationStatus());
}
/**
* An application stopped during its restore whose cluster Docker will not remove stays STOPPING, naming it, and
* so does it at a start where Docker still keeps it; the start where Docker removes it leaves it READY.
*/
@Test
void aStoppedApplicationWhoseClusterDockerKeepsStaysStopping() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
KinesisAnalyticsV2Service[] restoring = new KinesisAnalyticsV2Service[1];
Mockito.doAnswer(start -> {
restoring[0].stopApplication("kept", "us-east-1");
return null;
}).when(manager).startCluster(Mockito.any());
IllegalStateException refused = new IllegalStateException("Failed to remove stale container jm");
Mockito.doThrow(refused).when(manager).removeOwnCluster(Mockito.any());
restoring[0] = buildService(false, manager, store);
store.putForAccount("000000000000", "us-east-1/kept",
storedApplication("kept", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
CompletionException thrown = assertThrows(CompletionException.class,
() -> restoring[0].restorePersistedRuntime().join());
assertSame(refused, thrown.getCause().getCause());
assertEquals(ApplicationStatus.STOPPING,
store.getForAccount("000000000000", "us-east-1/kept").orElseThrow().getApplicationStatus());
FlinkContainerManager stillKept = Mockito.mock(FlinkContainerManager.class);
Mockito.doThrow(refused).when(stillKept).removeSurvivingCluster(Mockito.any());
assertThrows(CompletionException.class,
() -> buildService(false, stillKept, store).restorePersistedRuntime().join());
assertEquals(ApplicationStatus.STOPPING,
store.getForAccount("000000000000", "us-east-1/kept").orElseThrow().getApplicationStatus());
buildService(false, Mockito.mock(FlinkContainerManager.class), store).restorePersistedRuntime().join();
assertEquals(ApplicationStatus.READY,
store.getForAccount("000000000000", "us-east-1/kept").orElseThrow().getApplicationStatus());
}
/**
* An application whose cluster cannot start, and which Docker will not then remove, is STOPPING rather than
* READY: the start's failure is thrown, the refused removal with it.
*/
@Test
void aFailedStartWhoseClusterDockerKeepsLeavesItStopping() {
assertAFailedStartLeavesItStopping((manager, refused) ->
Mockito.doThrow(refused).when(manager).removeOwnCluster(Mockito.any()));
// A container the failed start left under the cluster's names, and Docker keeps, counts the same; the
// removal before the start went through.
assertAFailedStartLeavesItStopping((manager, refused) ->
Mockito.doNothing().doThrow(refused).when(manager).removeSurvivingCluster(Mockito.any()));
}
private void assertAFailedStartLeavesItStopping(
BiConsumer<FlinkContainerManager, RuntimeException> refusedRemoval) {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
IllegalStateException cause = new IllegalStateException("Docker unavailable");
IllegalStateException refused = new IllegalStateException("Failed to remove stale container jm");
Mockito.doThrow(cause).when(manager).startCluster(Mockito.any());
refusedRemoval.accept(manager, refused);
store.putForAccount("000000000000", "us-east-1/failed",
storedApplication("failed", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
CompletionException thrown = assertThrows(CompletionException.class,
() -> buildService(false, manager, store).restorePersistedRuntime().join());
assertSame(cause, thrown.getCause().getCause());
assertSame(refused, cause.getSuppressed()[0]);
assertEquals(ApplicationStatus.STOPPING,
store.getForAccount("000000000000", "us-east-1/failed").orElseThrow().getApplicationStatus());
}
/** A surviving cluster that cannot be looked for fails the restore like a cluster that cannot start. */
@Test
void aClusterThatCannotBeLookedForFailsTheRestore() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
IllegalStateException cause = new IllegalStateException("Docker unavailable");
when(manager.adoptRunningCluster(Mockito.any())).thenThrow(cause);
store.putForAccount("000000000000", "us-east-1/unknown",
storedApplication("unknown", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
CompletionException thrown = assertThrows(CompletionException.class,
() -> buildService(false, manager, store).restorePersistedRuntime().join());
assertSame(cause, thrown.getCause().getCause());
assertEquals(ApplicationStatus.READY,
store.getForAccount("000000000000", "us-east-1/unknown").orElseThrow().getApplicationStatus());
Mockito.verify(manager, Mockito.never()).startCluster(Mockito.any());
}
/**
* Records stored under the keys of older builds move onto their current keys, so each application is restored
* once and no second record is left for the next start to restore again.
*/
@Test
void aRecordUnderAnOlderKeyIsRestoredOnce() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
KinesisAnalyticsV2Service restoring = buildService(false, manager, store);
store.putForAccount("000000000000", "legacy",
storedApplication("legacy", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
FlinkApplication both = storedApplication("both", "000000000000", "us-east-1", ApplicationStatus.RUNNING);
store.putForAccount("000000000000", "both", both);
store.putForAccount("000000000000", "us-east-1/both", both);
restoring.restorePersistedRuntime().join();
Mockito.verify(manager, Mockito.times(2)).startCluster(Mockito.any());
assertEquals(List.of("us-east-1/both", "us-east-1/legacy"), store.scanAllAccountEntries(key -> true).stream()
.map(entry -> entry.key()).sorted().toList());
assertEquals(ApplicationStatus.STARTING,
store.getForAccount("000000000000", "us-east-1/legacy").orElseThrow().getApplicationStatus());
}
/**
* A shutdown during the restore stops it: applications it has not started yet, and one whose start shutdown
* overtook, stay STARTING for the next start, rather than going back to READY.
*/
@Test
void aShutdownDuringTheRestoreLeavesItsApplicationsStarting() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager stopped = Mockito.mock(FlinkContainerManager.class);
when(stopped.isShuttingDown()).thenReturn(true);
store.putForAccount("000000000000", "us-east-1/waiting",
storedApplication("waiting", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
buildService(false, stopped, store).restorePersistedRuntime().join();
assertEquals(ApplicationStatus.STARTING,
store.getForAccount("000000000000", "us-east-1/waiting").orElseThrow().getApplicationStatus());
Mockito.verify(stopped, Mockito.never()).startCluster(Mockito.any());
FlinkContainerManager overtaken = Mockito.mock(FlinkContainerManager.class);
Mockito.doThrow(new FlinkContainerManager.ShuttingDownException("waiting"))
.when(overtaken).startCluster(Mockito.any());
KinesisAnalyticsV2Service cutShort = buildService(false, overtaken, store);
cutShort.restorePersistedRuntime().join();
assertEquals(ApplicationStatus.STARTING,
store.getForAccount("000000000000", "us-east-1/waiting").orElseThrow().getApplicationStatus());
Mockito.verify(overtaken, Mockito.never()).stopCluster(Mockito.any());
Mockito.verify(overtaken, Mockito.never()).removeOwnCluster(Mockito.any());
// Its restore is over, cut short or not: the poller drives the application as any other.
cutShort.pollReadiness();
Mockito.verify(overtaken).advanceToRunning(Mockito.argThat(app -> "waiting".equals(app.getApplicationName())));
}
@Test
void restoringLeavesMockApplicationsAsTheyAre() {
AccountAwareStorageBackend<FlinkApplication> store = AccountAwareStorageBackend.inMemory("000000000000");
FlinkContainerManager manager = Mockito.mock(FlinkContainerManager.class);
store.putForAccount("000000000000", "us-east-1/mock",
storedApplication("mock", "000000000000", "us-east-1", ApplicationStatus.RUNNING));
buildService(true, manager, store).restorePersistedRuntime().join();
assertEquals(ApplicationStatus.RUNNING,
store.getForAccount("000000000000", "us-east-1/mock").orElseThrow().getApplicationStatus());
Mockito.verifyNoInteractions(manager);
}
/** An application stored in {@code account} and {@code region} whose record names the cluster it ran on. */
private FlinkApplication storedApplication(String name, String account, String region, ApplicationStatus status) {
FlinkApplication app = new FlinkApplication(name,
"arn:aws:kinesisanalytics:" + region + ":" + account + ":application/" + name,
"FLINK-1_18", ROLE, "STREAMING");
app.setAccountId(account);
app.setApplicationStatus(status);
app.setRestEndpoint("http://old-jm:8081");
app.setFlinkJobId("job-1");
return app;
}
private KinesisAnalyticsV2Service mockModeService() {
return buildService(true, Mockito.mock(FlinkContainerManager.class));
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.MountType;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
@@ -33,6 +34,7 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
@@ -57,6 +59,7 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@@ -87,6 +90,8 @@ class FlinkContainerManagerTest {
private ContainerLifecycleManager lifecycleManager;
private LaunchedContainerAwsEnv awsEnv;
private S3Service s3Service;
private FlinkRestClient flinkRest;
private ContainerLogStreamer logStreamer;
private FlinkContainerManager manager;
@BeforeEach
@@ -129,12 +134,13 @@ class FlinkContainerManagerTest {
// every test that gets as far as create() succeeding needs a working docker client for that
// copy to land on by default.
when(lifecycleManager.getDockerClient()).thenReturn(mock(DockerClient.class, RETURNS_DEEP_STUBS));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
logStreamer = mock(ContainerLogStreamer.class);
ContainerDetector containerDetector = mock(ContainerDetector.class);
RegionResolver regionResolver = mock(RegionResolver.class);
s3Service = mock(S3Service.class);
awsEnv = mock(LaunchedContainerAwsEnv.class);
when(awsEnv.sdkBaselineEnv(eq("us-west-2"), eq(Optional.empty()))).thenReturn(AWS_ENV);
flinkRest = mock(FlinkRestClient.class);
manager = new FlinkContainerManager(
containerBuilder,
@@ -145,7 +151,7 @@ class FlinkContainerManagerTest {
regionResolver,
awsEnv,
s3Service,
mock(FlinkRestClient.class),
flinkRest,
MAPPER);
}
@@ -172,6 +178,315 @@ class FlinkContainerManagerTest {
assertEquals(List.of(List.of("rm", "-rf", "/savepoints/savepoint-1")), commands);
}
/**
* #5664: a cluster that outlived Floci, as when Floci is killed, is kept when its JobManager and TaskManager are
* running, the JobManager answers on the recorded REST endpoint and the recorded job still runs; shutdown then
* removes it.
*/
@Test
void aClusterStillRunningItsJobIsKept() {
FlinkApplication app = codeApplication("kept");
survivingContainers("floci-aws-", "running");
when(flinkRest.isRestUp("http://jm:8081")).thenReturn(true);
when(flinkRest.jobState("http://jm:8081", "job-1")).thenReturn("RUNNING");
assertTrue(manager.adoptRunningCluster(app));
assertEquals("jm-survivor", app.getContainerId());
assertEquals("tm-survivor", app.getTaskManagerContainerId());
manager.stopAll();
verify(lifecycleManager).stopAndRemove("tm-survivor", null);
verify(lifecycleManager).stopAndRemove(eq("jm-survivor"), any());
}
/** What survives of a cluster goes under both name forms, the current one and the legacy {@code floci-} one. */
@Test
void removingASurvivingClusterTakesBothNameForms() {
FlinkApplication app = codeApplication("old");
app.setContainerId("jm-old");
app.setTaskManagerContainerId("tm-old");
manager.removeSurvivingCluster(app);
// The record forgets the cluster and its job, so a later start submits the code again.
assertNull(app.getContainerId());
assertNull(app.getTaskManagerContainerId());
assertNull(app.getRestEndpoint());
assertNull(app.getFlinkJobId());
ArgumentCaptor<String> names = ArgumentCaptor.forClass(String.class);
verify(lifecycleManager, times(4)).removeIfExistsStrict(names.capture());
String current = "floci-aws-kinesisanalytics-arn-aws-kinesisanalytics-us-west-2-000000000000-application-old";
String legacy = "floci-kinesisanalytics-arn-aws-kinesisanalytics-us-west-2-000000000000-application-old";
assertEquals(List.of(current + "-tm", legacy + "-tm", current, legacy), names.getAllValues());
}
/** What survives of a cluster that Docker will not remove stays named in the record, for a later attempt. */
@Test
void aSurvivingClusterDockerKeepsStaysNamed() {
FlinkApplication app = codeApplication("kept");
app.setContainerId("jm-old");
Mockito.doThrow(new IllegalStateException("Failed to remove stale container"))
.when(lifecycleManager).removeIfExistsStrict(Mockito.argThat(name -> !name.endsWith("-tm")));
assertThrows(IllegalStateException.class, () -> manager.removeSurvivingCluster(app));
assertEquals("jm-old", app.getContainerId());
assertEquals("job-1", app.getFlinkJobId());
}
/**
* A restore's own cluster that Docker will not remove stays named in the record and tracked, so shutdown still
* removes it; the TaskManager Docker did remove is no longer tracked.
*/
@Test
void aClusterDockerKeepsStaysNamedAndTracked() {
when(flinkRest.isRestUp("http://jm:8081")).thenReturn(true);
when(flinkRest.jobState("http://jm:8081", "job-1")).thenReturn("RUNNING");
survivingContainers("floci-aws-", "running");
FlinkApplication restored = codeApplication("kept");
assertTrue(manager.adoptRunningCluster(restored));
Mockito.doThrow(new IllegalStateException("Failed to remove stale container jm-survivor"))
.when(lifecycleManager).removeIfExistsStrict("jm-survivor");
assertThrows(IllegalStateException.class, () -> manager.removeOwnCluster(restored));
assertEquals("jm-survivor", restored.getContainerId());
assertEquals("job-1", restored.getFlinkJobId());
manager.stopAll();
verify(lifecycleManager, times(2)).stopAndRemove(eq("jm-survivor"), any());
verify(lifecycleManager, times(1)).stopAndRemove("tm-survivor", null);
}
/** A restore's TaskManager that Docker will not remove stays tracked, so shutdown still removes it. */
@Test
void aTaskManagerDockerKeepsStaysTracked() {
when(flinkRest.isRestUp("http://jm:8081")).thenReturn(true);
when(flinkRest.jobState("http://jm:8081", "job-1")).thenReturn("RUNNING");
survivingContainers("floci-aws-", "running");
FlinkApplication restored = codeApplication("kept-taskmanager");
assertTrue(manager.adoptRunningCluster(restored));
Mockito.doThrow(new IllegalStateException("Failed to remove stale container tm-survivor"))
.when(lifecycleManager).removeIfExistsStrict("tm-survivor");
assertThrows(IllegalStateException.class, () -> manager.removeOwnCluster(restored));
assertEquals("tm-survivor", restored.getTaskManagerContainerId());
manager.stopAll();
verify(lifecycleManager, times(2)).stopAndRemove("tm-survivor", null);
}
/**
* A restore removing the cluster it holds, after the application was created again under its name and started:
* only its own containers go, and the replacement's cluster stays tracked, so shutdown still removes it.
*/
@Test
void removingItsOwnClusterLeavesAReplacementAlone() {
Closeable restoredLogs = mock(Closeable.class);
Closeable replacementLogs = mock(Closeable.class);
when(logStreamer.attachPolled(anyString(), anyString(), any(), anyString(), anyString()))
.thenReturn(restoredLogs, replacementLogs);
when(flinkRest.isRestUp("http://jm:8081")).thenReturn(true);
when(flinkRest.jobState("http://jm:8081", "job-1")).thenReturn("RUNNING");
survivingContainers("floci-aws-", "running");
FlinkApplication restored = codeApplication("replaced");
assertTrue(manager.adoptRunningCluster(restored));
Container jobManager = container("jm-new", "running");
Container taskManager = container("tm-new", "running");
when(lifecycleManager.findByName(anyString())).thenAnswer(find ->
Optional.of(((String) find.getArgument(0)).endsWith("-tm") ? taskManager : jobManager));
assertTrue(manager.adoptRunningCluster(codeApplication("replaced")));
manager.removeOwnCluster(restored);
verify(lifecycleManager).stopAndRemove("tm-survivor", null);
verify(lifecycleManager).stopAndRemove("jm-survivor", null);
// The record forgets the kept cluster and its job, so a later start submits the code again.
assertNull(restored.getContainerId());
assertNull(restored.getTaskManagerContainerId());
assertNull(restored.getRestEndpoint());
assertNull(restored.getFlinkJobId());
verify(lifecycleManager, Mockito.never()).stopAndRemove(eq("tm-new"), any());
verify(lifecycleManager, Mockito.never()).stopAndRemove(eq("jm-new"), any());
manager.stopAll();
verify(lifecycleManager).stopAndRemove("tm-new", null);
verify(lifecycleManager).stopAndRemove("jm-new", replacementLogs);
}
/**
* A restore removing the cluster it started, with no other cluster since, leaves nothing of it behind: its logs
* close with it, its code no longer waits to be submitted, and shutdown finds nothing more to remove.
*/
@Test
void removingItsOwnClusterClearsWhatItTracks() throws Exception {
FlinkApplication restored = application("removed");
restored.setCodeS3Bucket("code-bucket");
restored.setCodeS3Key("jobs/demo.jar");
when(s3Service.getObject("code-bucket", "jobs/demo.jar", null))
.thenReturn(new S3Object("code-bucket", "jobs/demo.jar", new byte[]{1}, "application/java-archive"));
when(lifecycleManager.create(any())).thenReturn("jm-id").thenReturn("tm-id");
when(lifecycleManager.startCreated(any(), any()))
.thenReturn(new ContainerInfo("jm-id", Map.of(8081, new EndpointInfo("localhost", 49152))))
.thenReturn(new ContainerInfo("tm-id", Map.of()));
Closeable logs = mock(Closeable.class);
when(logStreamer.attachPolled(anyString(), anyString(), any(), anyString(), anyString())).thenReturn(logs);
manager.startCluster(restored);
manager.removeOwnCluster(restored);
verify(lifecycleManager).stopAndRemove("tm-id", null);
verify(lifecycleManager).stopAndRemove("jm-id", logs);
// Each removal is confirmed with Docker.
verify(lifecycleManager).removeIfExistsStrict("tm-id");
verify(lifecycleManager).removeIfExistsStrict("jm-id");
// A later cluster under the same key, once it answers with slots free, has no code of this one's to submit.
restored.setRestEndpoint("http://jm:8081");
when(flinkRest.isRestUp("http://jm:8081")).thenReturn(true);
when(flinkRest.totalSlots("http://jm:8081")).thenReturn(8);
assertFalse(manager.advanceToRunning(restored));
verify(flinkRest, Mockito.never()).uploadJar(anyString(), any());
// A later cluster under the key, with no logs of its own, is not handed the removed cluster's at shutdown.
when(lifecycleManager.create(any())).thenReturn("jm-2", "tm-2");
when(lifecycleManager.startCreated(any(), any()))
.thenReturn(new ContainerInfo("jm-2", Map.of(8081, new EndpointInfo("localhost", 49153))))
.thenReturn(new ContainerInfo("tm-2", Map.of()));
when(logStreamer.attachPolled(anyString(), anyString(), any(), anyString(), anyString())).thenReturn(null);
manager.startCluster(restored);
manager.stopAll();
verify(lifecycleManager).stopAndRemove("jm-2", null);
verify(lifecycleManager).stopAndRemove("jm-id", logs);
}
/** A cluster that no longer serves the application is not kept. */
@Test
void aClusterThatNoLongerServesTheApplicationIsNotKept() {
when(flinkRest.isRestUp("http://jm:8081")).thenReturn(true);
survivingContainers("floci-aws-", "running");
when(flinkRest.jobState("http://jm:8081", "job-1")).thenReturn("FAILED");
assertFalse(manager.adoptRunningCluster(codeApplication("job-failed")), "its job no longer runs");
when(flinkRest.jobState("http://jm:8081", "job-1")).thenReturn("RUNNING");
FlinkApplication noRest = codeApplication("no-rest");
noRest.setRestEndpoint(null);
FlinkApplication noJob = codeApplication("no-job");
noJob.setFlinkJobId(null);
clearInvocations(lifecycleManager);
assertFalse(manager.adoptRunningCluster(noRest), "no REST endpoint is recorded");
assertFalse(manager.adoptRunningCluster(noJob), "no job is recorded");
// Nothing recorded to probe a cluster on, so Docker is not asked for one.
verify(lifecycleManager, Mockito.never()).findByName(anyString());
survivingContainers("floci-aws-", "exited");
assertFalse(manager.adoptRunningCluster(codeApplication("stopped")), "its containers stopped");
Container jobManager = container("jm-survivor", "running");
when(lifecycleManager.findByName(anyString())).thenAnswer(find ->
((String) find.getArgument(0)).endsWith("-tm") ? Optional.empty() : Optional.of(jobManager));
assertFalse(manager.adoptRunningCluster(codeApplication("lost-taskmanager")), "its TaskManager is gone");
survivingContainers("floci-aws-", "running");
when(flinkRest.isRestUp("http://jm:8081")).thenReturn(false);
assertFalse(manager.adoptRunningCluster(codeApplication("rest-down")), "its JobManager does not answer");
verify(lifecycleManager, Mockito.never()).stopAndRemove(anyString(), any());
}
/** A cluster from before the floci-aws- prefix runs in containers of the old names. */
@Test
void aClusterUnderTheLegacyNamesIsKept() {
survivingContainers("floci-", "running");
when(flinkRest.isRestUp("http://jm:8081")).thenReturn(true);
when(flinkRest.jobState("http://jm:8081", "job-1")).thenReturn("RUNNING");
assertTrue(manager.adoptRunningCluster(codeApplication("legacy")));
}
/** Once shutdown has removed the containers, no cluster starts and none is kept. */
@Test
void noClusterStartsOrIsKeptAfterShutdown() {
survivingContainers("floci-aws-", "running");
when(flinkRest.isRestUp("http://jm:8081")).thenReturn(true);
when(flinkRest.jobState("http://jm:8081", "job-1")).thenReturn("RUNNING");
manager.stopAll();
assertFalse(manager.adoptRunningCluster(codeApplication("late")));
assertThrows(FlinkContainerManager.ShuttingDownException.class,
() -> manager.startCluster(application("late")));
verify(lifecycleManager, Mockito.never()).create(any());
}
/**
* A start still running when shutdown removes the containers, as a restore's can be while its image pulls,
* removes the JobManager it started rather than leave it behind.
*/
@Test
void aJobManagerStartShutdownOvertakesIsRemoved() {
when(lifecycleManager.create(any())).thenReturn("jm-id");
when(lifecycleManager.startCreated(eq("jm-id"), any())).thenAnswer(start -> {
manager.stopAll();
return new ContainerInfo("jm-id", Map.of(8081, new EndpointInfo("localhost", 32768)));
});
assertThrows(FlinkContainerManager.ShuttingDownException.class,
() -> manager.startCluster(application("overtaken")));
verify(lifecycleManager).stopAndRemove("jm-id", null);
manager.stopAll();
verify(lifecycleManager, times(1)).stopAndRemove(anyString(), any());
}
/** A TaskManager start shutdown overtakes rolls the whole cluster back. */
@Test
void aTaskManagerStartShutdownOvertakesRemovesTheCluster() {
FlinkApplication app = application("overtaken-tm");
app.setCodeS3Bucket("code-bucket");
app.setCodeS3Key("jobs/demo.jar");
when(s3Service.getObject("code-bucket", "jobs/demo.jar", null))
.thenReturn(new S3Object("code-bucket", "jobs/demo.jar", new byte[]{1}, "application/java-archive"));
when(lifecycleManager.create(any())).thenReturn("jm-id").thenReturn("tm-id");
when(lifecycleManager.startCreated(eq("jm-id"), any()))
.thenReturn(new ContainerInfo("jm-id", Map.of(8081, new EndpointInfo("localhost", 49152))));
when(lifecycleManager.startCreated(eq("tm-id"), any())).thenAnswer(start -> {
manager.stopAll();
return new ContainerInfo("tm-id", Map.of());
});
assertThrows(FlinkContainerManager.ShuttingDownException.class, () -> manager.startCluster(app));
verify(lifecycleManager).stopAndRemove("tm-id", null);
// Registered before shutdown came, so shutdown removes it as well as the rollback.
verify(lifecycleManager, atLeastOnce()).stopAndRemove(eq("jm-id"), any());
assertNull(app.getContainerId());
}
/** An application with code whose record names the cluster it ran on: its REST endpoint and job. */
private FlinkApplication codeApplication(String name) {
FlinkApplication app = application(name);
app.setCodeS3Bucket("code");
app.setCodeS3Key("app.jar");
app.setRestEndpoint("http://jm:8081");
app.setFlinkJobId("job-1");
return app;
}
/** JobManager and TaskManager containers in the given state, under names that start with {@code prefix}. */
private void survivingContainers(String prefix, String state) {
Container jobManager = container("jm-survivor", state);
Container taskManager = container("tm-survivor", state);
when(lifecycleManager.findByName(anyString())).thenAnswer(find -> {
String name = find.getArgument(0);
if (!name.startsWith(prefix) || (prefix.equals("floci-") && name.startsWith("floci-aws-"))) {
return Optional.empty();
}
return Optional.of(name.endsWith("-tm") ? taskManager : jobManager);
});
}
private static Container container(String id, String state) {
Container container = mock(Container.class);
when(container.getId()).thenReturn(id);
when(container.getState()).thenReturn(state);
return container;
}
private FlinkApplication application(String name) {
return new FlinkApplication(name,
"arn:aws:kinesisanalytics:us-west-2:000000000000:application/" + name,