mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
874c3d6123
commit
732001a90f
11 files changed
+1480
-52
No files matched your search
@@ -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();
|
||||
|
||||
+129
@@ -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();
|
||||
}
|
||||
}
|
||||
+479
@@ -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));
|
||||
}
|
||||
|
||||
+317
-2
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user