fix(mwaa): start environments again when Floci restarts (#9466)

Floci's shutdown removed every MWAA environment's Postgres and Airflow
containers, with their volumes, and nothing started them again, so after
a restart with persistent storage an environment reported AVAILABLE with
nothing behind its webserver URL.

Shutdown now keeps the volumes while the environments are stored to come
back, and Floci keeps the secrets the metadata database was set up with
(its password, the Fernet key and the admin password) in a store of its
own, which GetEnvironment never returns. Shutdown removes containers by
the IDs Floci holds and under the environments' names, so none outlives
it, the ones a restore had not reached yet included. At startup each
environment reports MAINTENANCE, or CREATING while it was being created,
and its containers come back in the background. Containers that outlived
Floci are taken over, their secrets read back from the Airflow
container. Otherwise new ones start on the kept volumes with the kept
secrets, so DAG runs, connections and variables are back, and the
startup script and requirements.txt run as at creation. Containers and
volumes named before the floci-aws- prefix are found too. The web proxy
comes back on the port WebserverUrl names, or on a new one when that
port is taken. The first DAG sync after the restore compares the DAG
volume with S3, so a DAG deleted while Floci was stopped is removed; the
sync reads every page of the S3 listing, so no DAG past the first
thousand reads as deleted. The readiness poller reports the environment
AVAILABLE once Airflow is healthy, or UNAVAILABLE when a container exits
first; one whose containers do not start is UNAVAILABLE, and tried again
at the next start.

An environment stored before Floci kept the secrets gets them back from
a container left under its name, or, with none left, new ones, as its
volumes went at the shutdown then; one whose volumes are still there is
left UNAVAILABLE rather than started on new ones. Secrets found or given
are kept before anything starts. When Docker cannot say which containers
or volumes are left, the environment's restore fails, removing nothing.

A DeleteEnvironment during the restore leaves the environment DELETING
until its containers have started, and the restore then removes it; one
still DELETING at the next start is removed then. A start that shutdown
overtakes removes its containers. A new environment starts on empty
volumes, so it never inherits a database set up with other secrets.

Part of #5664.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-25 17:23:27 -04:00
1 parent b012f4d6bf
commit c829b397ab
12 files changed
+2372 -58

No files matched your search

+17
View File
@@ -94,6 +94,23 @@ opensearch_default_image() {
OPENSEARCH_IMAGE="$(opensearch_default_image)"
starts ContainerBindDirectoryDockerIntegrationTest OpenSearchDomainRestartNightlyIntegrationTest \
&& [ -n "$OPENSEARCH_IMAGE" ] && pull "$OPENSEARCH_IMAGE"
# MwaaEnvironmentRestartDockerNightlyIntegrationTest runs an environment on the default Airflow version, whose image
# pairs it with the Python release MwaaEnvironmentManager.pythonTagFor names, beside its Postgres database.
if starts MwaaEnvironmentRestartDockerNightlyIntegrationTest; then
MWAA_CONFIG="$(sed -n '/^ mwaa:$/,/^ [a-z]/p' src/main/resources/application.yml 2>/dev/null)"
MWAA_VERSION="$(printf '%s\n' "$MWAA_CONFIG" | grep -oE 'default-version: "[0-9.]+"' | cut -d '"' -f 2)"
MWAA_POSTGRES_IMAGE="$(printf '%s\n' "$MWAA_CONFIG" | grep -oE 'default-postgres-image: "[^"]+"' | cut -d '"' -f 2)"
case "$MWAA_VERSION" in
2.[0-9].*|2.10.*) MWAA_PYTHON=python3.11 ;;
*) MWAA_PYTHON=python3.12 ;;
esac
if [ -n "$MWAA_VERSION" ] && [ -n "$MWAA_POSTGRES_IMAGE" ]; then
pull "apache/airflow:$MWAA_VERSION-$MWAA_PYTHON"
pull "$MWAA_POSTGRES_IMAGE"
else
echo "$(date -u +%H:%M:%S) prefetch skipped: MWAA default images not readable" >> "$PREFETCH_LOG"
fi
fi
# EcsImagePullDockerIntegrationTest runs its own registry to move a tag in; the /ecr/ line below
# covers the shards that run the ECR tests.
REGISTRY_IMAGE="$(test_image REGISTRY)"
+8 -1
View File
@@ -105,6 +105,14 @@ Publishing the proxy range, as above, makes each environment's `WebserverUrl` re
Every `dag-sync-interval-seconds`, Floci lists the environment's `DagS3Path` prefix in the bucket referenced by `SourceBucketArn` and copies any changed files into the container's `/opt/airflow/dags`, reusing Floci's existing in-process S3 emulation rather than any new AWS-facing surface. `RequirementsS3Path`, if set, is fetched at creation and installed inside the container after the startup script and before Airflow starts, so a DAG can import its packages from the first parse. If that first install fails, the first DAG-sync pass logs pip's exit code and installs the file again. After that it is installed again whenever its content changes. Every install stops after 15 minutes, and reinstalls run in the background, one at a time per environment, so a slow one never holds up the DAG sync. A broken DAG file or a failing `pip install` is logged but never fails the environment, matching real MWAA behavior.
## Restarts
With persistent storage (any `FLOCI_STORAGE_MODE` other than `memory`), an environment comes back when Floci starts again, with its metadata database as it was: DAG runs, connections, variables and the admin user. Shutdown removes the environment's Postgres and Airflow containers, unless `FLOCI_SERVICES_MWAA_KEEP_RUNNING_ON_SHUTDOWN` keeps them, and keeps their volumes. Floci keeps the secrets the database was set up with (its password, the Fernet key Airflow encrypts connections and variables with, and the admin password) in `mwaa-environment-runtime.json` beside the environments; `GetEnvironment` never returns them.
At startup each environment reports `MAINTENANCE`, or `CREATING` if it was still being created, and its containers come back in the background, without Floci waiting for them to report itself ready. Containers that outlived Floci, kept running or left behind when Floci was killed, are taken over. Otherwise new ones start on the kept volumes with the kept secrets, running the startup script and installing `requirements.txt` as at creation. The web proxy comes back on the port `WebserverUrl` names, or on a new one, which `WebserverUrl` then names, when that port is taken. The environment turns `AVAILABLE` once Airflow reports healthy, as after `CreateEnvironment`. Its first DAG sync then compares the DAG folder with `DagS3Path`, so a DAG deleted from S3 while Floci was stopped is removed. One whose containers do not start, or exit before Airflow is healthy, is `UNAVAILABLE` and is tried again at the next start; one that was still being created is `CREATE_FAILED`. An environment deleted while its containers come back reads `DELETING` and keeps its name until its containers are up and removed with its volumes; one still `DELETING` when Floci stops is removed at the next start. An environment stored by an older Floci, which kept none of those secrets, gets them back from a container left under its name, if one is; with none left, its volumes went at the shutdown then and it starts on empty ones, and one whose volumes are still there is left `UNAVAILABLE` rather than started on new ones. Containers and volumes named before the `floci-aws-` prefix are found too: taken over, removed, or started on. When Docker cannot say which containers or volumes are left, the environment's restore fails and nothing is removed. Web login and CLI tokens do not survive a restart.
In memory mode the environments are gone after a restart, so shutdown removes their volumes too.
## ARN Format
```
@@ -200,4 +208,3 @@ The following are current, known gaps:
- `UpdateEnvironment` supports metadata-only fields (tags, description, logging-config toggles). Changing `AirflowVersion`, `AirflowConfigurationOptions`, or `RequirementsS3Path` requires deleting and recreating the environment — these would require recreating the running container, which is out of scope for an in-place update today.
- No per-component `MWAA_AIRFLOW_COMPONENT` environment variable. Real MWAA runs the startup script separately on webserver, scheduler, and worker; Floci runs the webserver, scheduler and triggerer together in one container, so there's no per-component distinction to expose.
- Docker container and volume names are namespace-aware (via `FLOCI_DOCKER_RESOURCE_NAMESPACE`, same as every other Docker-backed service) but not scoped by AWS account id — two accounts creating an identically-named environment can collide. This is a pre-existing characteristic shared by every Docker-backed Floci service (EKS, RDS, ...), not unique to MWAA.
- Environments loaded from persistent storage on Floci restart are not automatically reconnected to their Docker containers — again, a gap shared by every Docker-backed service today, not specific to MWAA.
@@ -38,6 +38,7 @@ import io.floci.aws.services.lambda.durable.DurableExecutionService;
import io.floci.aws.services.memorydb.MemoryDbService;
import io.floci.aws.services.memorydb.container.MemoryDbContainerManager;
import io.floci.aws.services.memorydb.proxy.MemoryDbProxyManager;
import io.floci.aws.services.mwaa.MwaaService;
import io.floci.aws.services.neptune.container.NeptuneContainerManager;
import io.floci.aws.services.neptune.proxy.NeptuneProxyManager;
import io.floci.aws.services.opensearch.OpenSearchService;
@@ -110,6 +111,7 @@ public class EmulatorLifecycle {
private final FlinkContainerManager flinkContainerManager;
private final KinesisAnalyticsV2Service kinesisAnalyticsService;
private final OpenSearchService openSearchService;
private final MwaaService mwaaService;
private final SageMakerService sageMakerService;
private final RdsService rdsService;
private final TimestreamInfluxDbService timestreamInfluxDbService;
@@ -162,6 +164,7 @@ public class EmulatorLifecycle {
FlinkContainerManager flinkContainerManager,
KinesisAnalyticsV2Service kinesisAnalyticsService,
OpenSearchService openSearchService,
MwaaService mwaaService,
SageMakerService sageMakerService,
RdsService rdsService,
TimestreamInfluxDbService timestreamInfluxDbService,
@@ -211,6 +214,7 @@ public class EmulatorLifecycle {
this.flinkContainerManager = flinkContainerManager;
this.kinesisAnalyticsService = kinesisAnalyticsService;
this.openSearchService = openSearchService;
this.mwaaService = mwaaService;
this.sageMakerService = sageMakerService;
this.rdsService = rdsService;
this.timestreamInfluxDbService = timestreamInfluxDbService;
@@ -344,6 +348,13 @@ public class EmulatorLifecycle {
return null;
});
}
if (config.services().mwaa().enabled()) {
// Starts the environments' containers in the background, failing the future with the ones it could not.
mwaaService.restorePersistedRuntime().exceptionally(ex -> {
LOG.error("Failed to restore persisted MWAA environments at startup", ex);
return null;
});
}
if (config.services().elbv2().enabled()) {
elbV2Service.restorePersistedRuntime();
}
@@ -34,6 +34,8 @@ import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -61,6 +63,7 @@ public class MwaaEnvironmentManager {
private static final int POSTGRES_PORT = 5432;
private static final int AIRFLOW_WEBSERVER_PORT = 8080;
private static final String SQL_ALCHEMY_CONN_PREFIX = "postgresql+psycopg2://airflow:";
private static final String DAGS_MOUNT = "/opt/airflow/dags";
private static final String LOGS_MOUNT = "/opt/airflow/logs";
/** The OS user the stock apache/airflow image runs its process as (uid 50000) — distinct from
@@ -100,6 +103,15 @@ public class MwaaEnvironmentManager {
private final Ec2Service ec2Service;
/** The VPC address each Airflow container holds, returned once the container is gone. */
private final VpcContainerLeases vpcLeases;
/** Set once Floci starts shutting down: nothing starts or is taken over after it; a start it overtakes stops. */
private boolean shuttingDown;
/** A start or a takeover overtaken by Floci shutting down; whatever the start had started is removed. */
public static final class ShuttingDownException extends IllegalStateException {
public ShuttingDownException(String message) {
super(message);
}
}
@Inject
public MwaaEnvironmentManager(ContainerBuilder containerBuilder,
@@ -121,10 +133,12 @@ public class MwaaEnvironmentManager {
}
/**
* Starts the Postgres metadata database, waits for it to accept connections, then starts the
* Airflow container (LocalExecutor) wired to it. Updates {@code environment} with the resolved
* container ids and the Airflow container's Floci-reachable host/port. Throws on failure; the
* caller (MwaaService) is responsible for catching and marking the environment CREATE_FAILED.
* Starts a new environment: the Postgres metadata database, once it accepts connections the Airflow container
* (LocalExecutor) wired to it, both on empty volumes and with secrets of their own, which are kept on
* {@code environment} with the containers' IDs and the Airflow container's Floci-reachable host and port. Whatever
* an earlier environment of this name left behind is removed first: a database set up with other secrets would
* refuse this one's. Throws on failure; the caller (MwaaService) is responsible for catching and marking the
* environment CREATE_FAILED.
*
* @param startupScriptContent the {@code StartupScriptS3Path} object's bytes (already fetched
* from S3 by the caller), or {@code null}/empty if the environment
@@ -134,13 +148,68 @@ public class MwaaEnvironmentManager {
*/
public void startEnvironment(Environment environment, String airflowVersion, byte[] startupScriptContent,
byte[] requirementsContent) {
String name = environment.getName();
String dbPassword = generateSecret(24);
environment.setDbPassword(dbPassword);
requireNotShuttingDown(environment);
newSecrets(environment);
removeSurvivingContainers(environment);
for (String volume : allVolumeNames(environment)) {
lifecycleManager.removeVolumeStrict(volume);
}
launch(environment, currentVolumes(environment), airflowVersion, startupScriptContent, requirementsContent);
}
/**
* Gives an environment stored before Floci kept its secrets new ones, for its database to be set up with when its
* containers start again: with no container left to read them back from, its volumes went with its containers at
* the shutdown then, and it starts on empty ones. One whose volumes are still there is refused, as they hold a
* database set up with secrets Floci does not have, which new ones would not open; so is one Docker cannot list
* the volumes of.
*/
public void giveNewSecrets(Environment environment) {
Set<String> existing = existingVolumes();
List<String> kept = allVolumeNames(environment).stream().filter(existing::contains).toList();
if (!kept.isEmpty()) {
throw new IllegalStateException("MWAA environment " + environment.getName() + " is left as it is: "
+ kept + " hold its metadata database, whose secrets Floci does not have");
}
newSecrets(environment);
}
private static void newSecrets(Environment environment) {
environment.setDbPassword(generateSecret(24));
environment.setFernetKey(generateFernetKey());
environment.setAirflowAdminPassword(generateSecret(24));
}
/**
* Starts an environment's containers again after Floci restarts, as {@link #startEnvironment} does, but on the
* volumes they kept, under either naming scheme, and with the secrets {@code environment} carries, those its
* database was set up with: Airflow finds its metadata as it left it, and decrypts the connections and variables it
* holds. Containers left under its names go first, so none holds the volumes. A Docker that cannot say which
* containers or volumes are left fails the start, with nothing removed.
*/
public void restartEnvironment(Environment environment, String airflowVersion, byte[] startupScriptContent,
byte[] requirementsContent) {
if (!hasSecrets(environment)) {
throw new IllegalStateException("MWAA environment " + environment.getName()
+ " has no saved secrets to start its metadata database with");
}
requireNotShuttingDown(environment);
removeSurvivingContainers(environment);
launch(environment, keptVolumes(environment), airflowVersion, startupScriptContent, requirementsContent);
}
/** Whether the environment carries the secrets its metadata database was set up with. */
static boolean hasSecrets(Environment environment) {
return environment.getDbPassword() != null && environment.getFernetKey() != null
&& environment.getAirflowAdminPassword() != null;
}
private void launch(Environment environment, Volumes volumes, String airflowVersion, byte[] startupScriptContent,
byte[] requirementsContent) {
String name = environment.getName();
String dbPassword = environment.getDbPassword();
String dbContainerName = dbContainerName(environment);
String dbVolume = dbContainerName;
lifecycleManager.removeIfExists(dbContainerName);
String dbVolume = volumes.db();
lifecycleManager.ensureVolume(dbVolume);
ContainerSpec dbSpec = containerBuilder.newContainer(config.services().mwaa().defaultPostgresImage())
@@ -158,8 +227,9 @@ public class MwaaEnvironmentManager {
.build();
String dbContainerId = lifecycleManager.create(dbSpec);
lifecycleManager.startCreated(dbContainerId, dbSpec);
environment.setDbContainerId(dbContainerId);
lifecycleManager.startCreated(dbContainerId, dbSpec);
stopIfOvertaken(environment);
waitForPostgresReady(dbContainerId);
String dbIp = resolveContainerIp(dbContainerId, dbSpec.networkMode());
@@ -167,7 +237,145 @@ public class MwaaEnvironmentManager {
dbContainerId, name, dbIp, String.valueOf(POSTGRES_PORT));
startAirflowContainer(environment, airflowVersion, dbIp, dbPassword, startupScriptContent,
requirementsContent);
requirementsContent, volumes);
stopIfOvertaken(environment);
}
/**
* Takes over the environment's containers when both outlived Floci running, under either naming scheme: kept by
* {@code keep-running-on-shutdown}, or left by a Floci that was killed. The secrets are read back from the Airflow
* container, which was started with them, so an environment stored before Floci kept them is taken over too.
* False, with nothing taken over, when either container is not running or the Airflow container does not name
* them; a Docker that cannot say throws, rather than reading as nothing being left.
*/
public boolean adoptRunningEnvironment(Environment environment) {
requireNotShuttingDown(environment);
Optional<InspectContainerResponse> airflow = runningContainer(airflowContainerName(environment));
Optional<InspectContainerResponse> db = runningContainer(dbContainerName(environment));
if (airflow.isEmpty() || db.isEmpty()) {
return false;
}
Map<String, String> airflowEnv = envVariables(airflow.get());
if (!hasSecrets(airflowEnv)) {
return false;
}
ContainerInfo info = lifecycleManager.adopt(airflow.get().getId(), List.of(AIRFLOW_WEBSERVER_PORT),
containerBuilder.resolveDockerNetwork(config.services().mwaa().dockerNetwork()));
applySecrets(environment, airflowEnv);
environment.setDbContainerId(db.get().getId());
environment.setAirflowContainerId(info.containerId());
applyAirflowEndpoint(environment, info);
LOG.infov("Took over the running containers of MWAA environment {0}", environment.getName());
return true;
}
/**
* Reads back the secrets the environment's metadata database was set up with from a container left under its
* Airflow name, running or not, for an environment stored before Floci kept them. False when none is left or it
* does not name them; a Docker that cannot say throws, rather than reading as none being left.
*/
public boolean recoverSecrets(Environment environment) {
for (String name : namesOf(airflowContainerName(environment))) {
Optional<InspectContainerResponse> airflow = inspectNamed(name);
if (airflow.isPresent() && hasSecrets(envVariables(airflow.get()))) {
applySecrets(environment, envVariables(airflow.get()));
return true;
}
}
return false;
}
private Optional<InspectContainerResponse> runningContainer(String name) {
for (String candidate : namesOf(name)) {
Optional<InspectContainerResponse> container = inspectNamed(candidate).filter(inspect ->
inspect.getState() != null && Boolean.TRUE.equals(inspect.getState().getRunning()));
if (container.isPresent()) {
return container;
}
}
return Optional.empty();
}
/** The container of that name, or empty when Docker has none; a Docker that cannot say throws. */
private Optional<InspectContainerResponse> inspectNamed(String name) {
try {
return Optional.of(lifecycleManager.getDockerClient().inspectContainerCmd(name).exec());
} catch (NotFoundException expected) {
// No container of that name, which is what the caller asks.
return Optional.empty();
}
}
/** A container's name, current and from before the {@code floci-aws-} prefix, which may have left one. */
private List<String> namesOf(String name) {
String legacy = ContainerStorageHelper.legacyDockerName(config, name);
return legacy.equals(name) ? List.of(name) : List.of(name, legacy);
}
private static Map<String, String> envVariables(InspectContainerResponse container) {
Map<String, String> variables = new HashMap<>();
String[] entries = container.getConfig() == null ? null : container.getConfig().getEnv();
for (String entry : entries == null ? new String[0] : entries) {
int equals = entry.indexOf('=');
if (equals > 0) {
variables.put(entry.substring(0, equals), entry.substring(equals + 1));
}
}
return variables;
}
private static boolean hasSecrets(Map<String, String> airflowEnv) {
return dbPasswordOf(airflowEnv.get("AIRFLOW__DATABASE__SQL_ALCHEMY_CONN")) != null
&& airflowEnv.get("AIRFLOW__CORE__FERNET_KEY") != null
&& airflowEnv.get("_AIRFLOW_WWW_USER_PASSWORD") != null;
}
private static void applySecrets(Environment environment, Map<String, String> airflowEnv) {
environment.setDbPassword(dbPasswordOf(airflowEnv.get("AIRFLOW__DATABASE__SQL_ALCHEMY_CONN")));
environment.setFernetKey(airflowEnv.get("AIRFLOW__CORE__FERNET_KEY"));
environment.setAirflowAdminPassword(airflowEnv.get("_AIRFLOW_WWW_USER_PASSWORD"));
}
/** The password of the Postgres URL {@link #startAirflowContainer} gives Airflow, or null for any other. */
static String dbPasswordOf(String sqlAlchemyConn) {
if (sqlAlchemyConn == null || !sqlAlchemyConn.startsWith(SQL_ALCHEMY_CONN_PREFIX)) {
return null;
}
int at = sqlAlchemyConn.lastIndexOf('@');
return at > SQL_ALCHEMY_CONN_PREFIX.length()
? sqlAlchemyConn.substring(SQL_ALCHEMY_CONN_PREFIX.length(), at) : null;
}
/** Stops Floci from starting or taking over environments, so none outlives the shutdown it overtakes. */
public synchronized void markShuttingDown() {
shuttingDown = true;
}
public synchronized boolean isShuttingDown() {
return shuttingDown;
}
private synchronized void requireNotShuttingDown(Environment environment) {
if (shuttingDown) {
throw new ShuttingDownException("Floci is shutting down; MWAA environment " + environment.getName()
+ " was not started");
}
}
/**
* Removes the containers this start started once Floci began shutting down meanwhile: the shutdown stops the
* environments' containers by the IDs they hold, and may have done so before this start recorded its own.
*/
private void stopIfOvertaken(Environment environment) {
boolean overtaken;
synchronized (this) {
overtaken = shuttingDown;
}
if (overtaken) {
stopOwnContainers(environment);
throw new ShuttingDownException("Floci is shutting down; MWAA environment " + environment.getName()
+ " was not started");
}
}
// Package-private (not private) so MwaaEnvironmentManagerTest can exercise container-spec
@@ -175,19 +383,31 @@ public class MwaaEnvironmentManager {
// the exec-based Postgres readiness wait that startEnvironment() performs first.
void startAirflowContainer(Environment environment, String airflowVersion, String dbIp, String dbPassword,
byte[] startupScriptContent, byte[] requirementsContent) {
startAirflowContainer(environment, airflowVersion, dbIp, dbPassword, startupScriptContent, requirementsContent,
currentVolumes(environment));
}
private void startAirflowContainer(Environment environment, String airflowVersion, String dbIp, String dbPassword,
byte[] startupScriptContent, byte[] requirementsContent, Volumes volumes) {
String name = environment.getName();
String airflowContainerName = airflowContainerName(environment);
String dagsVolume = airflowContainerName + "-dags";
String logsVolume = airflowContainerName + "-logs";
String dagsVolume = volumes.dags();
String logsVolume = volumes.logs();
lifecycleManager.removeIfExists(airflowContainerName);
lifecycleManager.ensureVolume(dagsVolume);
lifecycleManager.ensureVolume(logsVolume);
String image = "apache/airflow:%s-%s".formatted(airflowVersion, pythonTagFor(airflowVersion));
String adminPassword = generateSecret(24);
environment.setAirflowAdminPassword(adminPassword);
String sqlAlchemyConn = "postgresql+psycopg2://airflow:" + dbPassword + "@" + dbIp + ":" + POSTGRES_PORT + "/airflow";
// The environment's own, generated the first time it starts.
if (environment.getAirflowAdminPassword() == null) {
environment.setAirflowAdminPassword(generateSecret(24));
}
if (environment.getFernetKey() == null) {
environment.setFernetKey(generateFernetKey());
}
String adminPassword = environment.getAirflowAdminPassword();
String sqlAlchemyConn = SQL_ALCHEMY_CONN_PREFIX + dbPassword + "@" + dbIp + ":" + POSTGRES_PORT + "/airflow";
// Points DAG code's own AWS SDK calls (boto3, botocore) at Floci itself, the same way
// Lambda/ECS containers already do via LaunchedContainerAwsEnv — otherwise a real DAG's
@@ -197,7 +417,7 @@ public class MwaaEnvironmentManager {
"AIRFLOW__CORE__EXECUTOR=LocalExecutor",
"AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=" + sqlAlchemyConn,
"AIRFLOW__CORE__SQL_ALCHEMY_CONN=" + sqlAlchemyConn,
"AIRFLOW__CORE__FERNET_KEY=" + generateFernetKey(),
"AIRFLOW__CORE__FERNET_KEY=" + environment.getFernetKey(),
"AIRFLOW__WEBSERVER__SECRET_KEY=" + generateSecret(32),
"AIRFLOW__CORE__LOAD_EXAMPLES=false",
"_AIRFLOW_WWW_USER_USERNAME=" + AIRFLOW_ADMIN_USER,
@@ -272,7 +492,15 @@ public class MwaaEnvironmentManager {
throw e;
}
environment.setAirflowContainerId(info.containerId());
applyAirflowEndpoint(environment, info);
LOG.infov("Started Airflow container {0} for MWAA environment {1} (image {2}), reachable at {3}:{4}",
info.containerId(), name, image, environment.getAirflowInternalHost(),
String.valueOf(environment.getAirflowInternalPort()));
}
/** Where Floci reaches the Airflow container's webserver, as the container's start or takeover reports it. */
private static void applyAirflowEndpoint(Environment environment, ContainerInfo info) {
ContainerLifecycleManager.EndpointInfo endpoint = info.getEndpoint(AIRFLOW_WEBSERVER_PORT);
if (endpoint != null) {
environment.setAirflowInternalHost(endpoint.host());
@@ -281,10 +509,6 @@ public class MwaaEnvironmentManager {
environment.setAirflowInternalHost("localhost");
environment.setAirflowInternalPort(AIRFLOW_WEBSERVER_PORT);
}
LOG.infov("Started Airflow container {0} for MWAA environment {1} (image {2}), reachable at {3}:{4}",
info.containerId(), name, image, environment.getAirflowInternalHost(),
String.valueOf(environment.getAirflowInternalPort()));
}
/**
@@ -377,9 +601,39 @@ public class MwaaEnvironmentManager {
return healthyIdx >= 0 && (nextSectionCommaIdx < 0 || healthyIdx < nextSectionCommaIdx + 2);
}
/** Stops and removes both containers and all three named volumes for the given environment. */
/**
* Stops and removes both containers and all three named volumes for the given environment, under either naming
* scheme: the containers by the IDs it holds, and any left under its names, which a restart may not have taken
* over. A container Docker will not remove is logged, and the delete goes on, as it always has.
*/
public void stopEnvironment(Environment environment) {
String name = environment.getName();
stopContainers(environment);
for (String volume : allVolumeNames(environment)) {
lifecycleManager.removeVolume(volume);
}
LOG.infov("Stopped MWAA containers for environment {0}", environment.getName());
}
/**
* Stops and removes the environment's containers, by the IDs it holds and under its names, and keeps its
* volumes, so its metadata database and DAGs are there when its containers start again. By name too, since an
* environment the startup restore has not reached yet holds no IDs. A container Docker will not remove is logged.
*/
public void stopContainers(Environment environment) {
stopOwnContainers(environment);
try {
removeSurvivingContainers(environment);
} catch (RuntimeException e) {
LOG.warnv("Could not remove the containers left under MWAA environment {0}''s names: {1}",
environment.getName(), e.getMessage());
}
}
/**
* Stops and removes the containers the environment holds the IDs of, and nothing else: another environment created
* under its name since has containers of the same names.
*/
public void stopOwnContainers(Environment environment) {
if (environment.getAirflowContainerId() != null) {
lifecycleManager.stopAndRemove(environment.getAirflowContainerId(), null);
releaseVpcLeaseIfGone(environment.getAirflowContainerId());
@@ -387,11 +641,66 @@ public class MwaaEnvironmentManager {
if (environment.getDbContainerId() != null) {
lifecycleManager.stopAndRemove(environment.getDbContainerId(), null);
}
}
/**
* Removes the containers under the environment's names, current and from before the {@code floci-aws-} prefix:
* ones a Floci that stopped without removing them left behind. Throws when Docker cannot say which are left or
* will not remove one, so nothing starts beside it on the same volumes.
*/
private void removeSurvivingContainers(Environment environment) {
for (String current : List.of(airflowContainerName(environment), dbContainerName(environment))) {
for (String name : namesOf(current)) {
Optional<InspectContainerResponse> survivor = inspectNamed(name);
if (survivor.isPresent()) {
lifecycleManager.removeIfExistsStrict(survivor.get().getId());
releaseVpcLeaseIfGone(survivor.get().getId());
}
}
}
}
/** The volumes an environment's containers mount: its database, its DAGs and its logs. */
private record Volumes(String db, String dags, String logs) {
List<String> all() {
return List.of(db, dags, logs);
}
}
private Volumes currentVolumes(Environment environment) {
String airflowContainerName = airflowContainerName(environment);
lifecycleManager.removeVolume(dbContainerName(environment));
lifecycleManager.removeVolume(airflowContainerName + "-dags");
lifecycleManager.removeVolume(airflowContainerName + "-logs");
LOG.infov("Stopped MWAA containers for environment {0}", name);
return new Volumes(dbContainerName(environment), airflowContainerName + "-dags",
airflowContainerName + "-logs");
}
/**
* The volumes the environment's data is on: each under its current name, or under its name from before the
* {@code floci-aws-} prefix when only that one is left.
*/
private Volumes keptVolumes(Environment environment) {
Set<String> existing = existingVolumes();
Volumes current = currentVolumes(environment);
return new Volumes(kept(current.db(), existing), kept(current.dags(), existing),
kept(current.logs(), existing));
}
private String kept(String volume, Set<String> existing) {
String legacy = ContainerStorageHelper.legacyDockerName(config, volume);
return !existing.contains(volume) && existing.contains(legacy) ? legacy : volume;
}
/** Every volume name the environment may have, current and from before the {@code floci-aws-} prefix. */
private List<String> allVolumeNames(Environment environment) {
Set<String> names = new LinkedHashSet<>();
for (String volume : currentVolumes(environment).all()) {
names.addAll(namesOf(volume));
}
return List.copyOf(names);
}
private Set<String> existingVolumes() {
return lifecycleManager.tryListVolumeNames().orElseThrow(() -> new IllegalStateException(
"Docker could not list its volumes, so the MWAA environment's data could not be found"));
}
/**
@@ -461,6 +770,30 @@ public class MwaaEnvironmentManager {
copyFileIntoContainer(environment.getAirflowContainerId(), DAGS_MOUNT, relativePath, content);
}
/**
* The files under {@code DAGS_MOUNT} in the Airflow container, relative to it, leaving out the {@code __pycache__}
* Python writes there: what the DAG volume holds, which after a restart may include DAGs removed from S3 while
* Floci was stopped. A listing that fails throws, rather than reading as an empty folder.
*/
public List<String> listDagFiles(Environment environment) {
ContainerExec.Result result;
try {
result = execInContainer(environment.getAirflowContainerId(),
new String[]{"find", DAGS_MOUNT, "-type", "f"});
} catch (Exception e) {
throw new IllegalStateException("Could not list the DAGs of MWAA environment " + environment.getName(), e);
}
if (result.exitCode() != 0) {
throw new IllegalStateException("Could not list the DAGs of MWAA environment " + environment.getName()
+ ": " + result.stderr());
}
return result.stdout().lines()
.filter(line -> line.startsWith(DAGS_MOUNT + "/"))
.map(line -> line.substring(DAGS_MOUNT.length() + 1))
.filter(relative -> !relative.contains("__pycache__/"))
.toList();
}
/** Removes {@code DAGS_MOUNT/relativePath} from the Airflow container (best-effort). */
public void removeDagFile(Environment environment, String relativePath) {
try {
@@ -6,6 +6,8 @@ import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.Base64Url;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.StripedLocks;
import io.floci.aws.core.common.TagHandler;
import io.floci.aws.core.common.docker.PortAllocator;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
@@ -14,6 +16,7 @@ import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.ec2.VpcDependencyProvider;
import io.floci.aws.services.mwaa.model.CreateEnvironmentRequest;
import io.floci.aws.services.mwaa.model.Environment;
import io.floci.aws.services.mwaa.model.EnvironmentRuntime;
import io.floci.aws.services.mwaa.model.EnvironmentStatus;
import io.floci.aws.services.mwaa.model.NetworkConfiguration;
import io.floci.aws.services.mwaa.model.UpdateEnvironmentRequest;
@@ -27,16 +30,21 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.URI;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
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.Executor;
import java.util.concurrent.ExecutorService;
@@ -68,7 +76,13 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
/** Amazon MWAA's web login token "expires after 60 seconds" (Apache Airflow REST API guide). */
static final Duration WEB_LOGIN_TOKEN_LIFETIME = Duration.ofSeconds(60);
/** The states of an environment whose containers the startup restore brings back. */
private static final Set<EnvironmentStatus> RESTORED_STATUSES = Set.of(EnvironmentStatus.CREATING,
EnvironmentStatus.AVAILABLE, EnvironmentStatus.MAINTENANCE, EnvironmentStatus.UNAVAILABLE);
private final StorageBackend<String, Environment> storage;
/** The secrets each environment's metadata database was set up with, for its restart. */
private final AccountAwareStorageBackend<EnvironmentRuntime> runtimeStorage;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final MwaaEnvironmentManager environmentManager;
@@ -100,6 +114,15 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
/** Environments with a reinstall running, so a slow one is never started twice. */
private final Set<String> requirementsInstallsInFlight = ConcurrentHashMap.newKeySet();
/**
* Environments the startup restore is bringing back, by account and storage key: the readiness poller leaves them
* alone, and DeleteEnvironment leaves their removal to the restore.
*/
private final Set<String> restoringEnvironments = ConcurrentHashMap.newKeySet();
/** Orders the restore's reads and writes of an environment with DeleteEnvironment's. */
private final StripedLocks storedEnvironmentLocks = new StripedLocks(256);
@Inject
public MwaaService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
MwaaEnvironmentManager environmentManager, MwaaProxyManager proxyManager,
@@ -120,6 +143,9 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
this.storage = storageFactory.create("mwaa", "mwaa-environments.json",
new TypeReference<Map<String, Environment>>() {
});
this.runtimeStorage = storageFactory.create("mwaa", "mwaa-environment-runtime.json",
new TypeReference<Map<String, EnvironmentRuntime>>() {
});
this.config = config;
this.regionResolver = regionResolver;
this.environmentManager = environmentManager;
@@ -182,14 +208,380 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
if (requirementsInstaller instanceof ExecutorService installer) {
installer.shutdownNow();
}
if (!config.services().mwaa().mock() && !config.services().mwaa().keepRunningOnShutdown()) {
for (Environment environment : allEnvironments()) {
proxyManager.stopProxy(environmentIdentity(environment));
if (config.services().mwaa().mock()) {
return;
}
// First, so a restore still starting containers stops, and a start it overtakes removes its own.
environmentManager.markShuttingDown();
if (config.services().mwaa().keepRunningOnShutdown()) {
return;
}
boolean keepVolumes = keepsEnvironmentsAcrossRestarts();
for (Environment environment : allEnvironments()) {
proxyManager.stopProxy(environmentIdentity(environment));
if (keepVolumes) {
// The next start brings the environment back on them, with its DAG runs, connections and variables.
// By name too: an environment the startup restore has not reached yet holds no container IDs.
environmentManager.stopContainers(environment);
} else {
environmentManager.stopEnvironment(environment);
}
}
}
/** Whether the environments are stored to come back after Floci restarts, rather than kept in memory alone. */
private boolean keepsEnvironmentsAcrossRestarts() {
return !"memory".equals(config.storage().mode());
}
/**
* Brings the persisted environments' containers back after Floci restarts. Shutdown removes them, unless
* {@code keep-running-on-shutdown} keeps them, so an environment read back from storage reported itself AVAILABLE
* with nothing behind its webserver URL. Each environment reports {@code MAINTENANCE} at once, one still being
* created {@code CREATING}, and its containers come back in the background, so Floci does not wait for them to
* report itself ready; the readiness poller leaves an environment alone while its restore runs, and reports it
* AVAILABLE once Airflow answers.
*
* <p>Containers that outlived Floci, kept running or left by a Floci that was killed, are taken over. Otherwise the
* environment gets new ones on the volumes shutdown kept, with the secrets its metadata database was set up with,
* so its DAG runs, connections and variables are back. One stored before Floci kept those secrets gets them back
* from a container left under its name; with none left, its volumes went at shutdown and it gets new ones and
* starts on empty volumes, or, when they are still there, is left as it is, unable to open its database. When
* Docker cannot say which containers or volumes are left, the environment's restore fails, removing nothing. Its
* web proxy comes back on the port its webserver URL names while that port is free. One whose containers do not
* start is {@code UNAVAILABLE}, or {@code CREATE_FAILED} while it was being created, keeping its volumes; an
* {@code UNAVAILABLE} one is tried again at the next start.
* One deleted during its restore is {@code DELETING} until its containers have started and been removed, and is
* gone then; one still {@code DELETING} at the next start is removed then. Every environment is tried, and the
* ones that could not be restored fail the returned future together. A shutdown during the restore leaves the
* environments not started yet as they are, for the next start.
*/
public CompletableFuture<Void> restorePersistedRuntime() {
if (config.services().mwaa().mock() || !(storage instanceof AccountAwareStorageBackend<Environment> aware)) {
return CompletableFuture.completedFuture(null);
}
List<RestoringEnvironment> pending = new ArrayList<>();
for (StoredEnvironment stored : storedEnvironments(aware)) {
RestoringEnvironment restoring = prepareRestore(stored);
if (restoring != null) {
pending.add(restoring);
}
}
return CompletableFuture.runAsync(() -> {
RuntimeException failure = null;
for (RestoringEnvironment restoring : pending) {
if (environmentManager.isShuttingDown()) {
// Environments not reached yet stay as they are, which the next start restores.
break;
}
Environment environment = restoring.environment();
try {
// Its startup script and requirements are read from its own account's S3.
RequestScopes.runAs(restoring.accountId(), restoring.region(), () -> restoreEnvironment(restoring));
} catch (MwaaEnvironmentManager.ShuttingDownException e) {
LOG.debugv("MWAA environment {0} not restored: {1}", environment.getName(), e.getMessage());
} catch (RuntimeException e) {
RuntimeException restoreFailure = new IllegalStateException("Could not restore MWAA environment "
+ environment.getName() + " of account " + restoring.accountId(), e);
if (failure == null) {
failure = restoreFailure;
} else {
failure.addSuppressed(restoreFailure);
}
} finally {
endRestore(restoring);
}
}
if (failure != null) {
throw failure;
}
});
}
/** Every stored environment once, by the account, Region and name it belongs to, legacy keys included. */
private Set<StoredEnvironment> storedEnvironments(AccountAwareStorageBackend<Environment> aware) {
Set<StoredEnvironment> stored = new LinkedHashSet<>();
for (Environment environment : aware.scanAllAccounts()) {
stored.add(new StoredEnvironment(environmentAccount(environment), environmentRegion(environment),
environment.getName()));
}
return stored;
}
/**
* Marks an environment the restore brings back, under its lock, and holds its proxy port for it; null for one it
* leaves as it is.
*/
private RestoringEnvironment prepareRestore(StoredEnvironment stored) {
String key = environmentKey(stored.region(), stored.name());
synchronized (storedEnvironmentLock(stored.accountId(), key)) {
// Read as DescribeEnvironment reads it, which moves a record stored under a legacy key onto its key.
Environment environment = getStoredEnvironment(stored.accountId(), stored.region(), stored.name())
.orElse(null);
if (environment == null) {
return null;
}
EnvironmentStatus status = environment.getStatus();
boolean deleting = status == EnvironmentStatus.DELETING;
if (!deleting && !RESTORED_STATUSES.contains(status)) {
return null;
}
environment.setAccountId(stored.accountId());
RestoringEnvironment restoring = new RestoringEnvironment(stored.accountId(), key, stored.region(),
environment, status == EnvironmentStatus.CREATING);
restoringEnvironments.add(restoring.lockKey());
// One still DELETING was deleted during a restore Floci did not live to finish, or during its shutdown:
// the delete stands.
if (!deleting) {
runtimeStorage.getForAccount(stored.accountId(), key)
.filter(runtime -> Objects.equals(runtime.getEnvironmentCreatedAt(),
environment.getCreatedAt()))
.ifPresent(runtime -> {
environment.setDbPassword(runtime.getDbPassword());
environment.setFernetKey(runtime.getFernetKey());
environment.setAirflowAdminPassword(runtime.getAirflowAdminPassword());
});
int proxyPort = recordedProxyPort(environment);
if (proxyPort > 0) {
// Held from now on, so an environment created during the restore does not take it.
portAllocator.markReserved(proxyPort);
}
environment.setProxyPort(proxyPort);
if (!restoring.creating()) {
environment.setStatus(EnvironmentStatus.MAINTENANCE);
}
// Its first DAG sync once it is back compares the DAG volume with S3, as for a new environment.
dagSyncState.remove(environmentIdentity(environment));
putEnvironment(environment);
}
return restoring;
}
}
/** The proxy port the environment's webserver URL names, or 0 for a URL that names none of the proxy range. */
private int recordedProxyPort(Environment environment) {
if (environment.getWebserverUrl() == null) {
return 0;
}
int port;
try {
port = URI.create(environment.getWebserverUrl()).getPort();
} catch (IllegalArgumentException e) {
return 0;
}
return port >= config.services().mwaa().proxyBasePort() && port <= config.services().mwaa().proxyMaxPort()
? port : 0;
}
private void restoreEnvironment(RestoringEnvironment restoring) {
Environment environment = restoring.environment();
Object lock = storedEnvironmentLock(restoring.accountId(), restoring.key());
EnvironmentStatus stored;
synchronized (lock) {
stored = storedStatus(restoring);
}
if (stored == null) {
portAllocator.release(environment.getProxyPort());
return;
}
if (stored == EnvironmentStatus.DELETING) {
finishDelete(restoring);
return;
}
try {
startContainers(restoring);
} catch (MwaaEnvironmentManager.ShuttingDownException e) {
throw e;
} catch (RuntimeException e) {
failRestore(restoring);
throw e;
}
RuntimeException proxyFailure = null;
EnvironmentStatus storedNow;
synchronized (lock) {
storedNow = storedStatus(restoring);
if (storedNow != null && storedNow != EnvironmentStatus.DELETING) {
try {
startRestoredProxy(environment);
// Its restore ends here: from now on the poller reports it AVAILABLE, and a delete removes it.
restoringEnvironments.remove(restoring.lockKey());
putEnvironment(environment);
return;
} catch (RuntimeException e) {
proxyFailure = e;
}
}
}
if (proxyFailure != null) {
failRestore(restoring);
throw proxyFailure;
}
if (storedNow == null) {
// Its record went, or another environment took its name, with no delete of its own: only the containers
// this restore kept or started go, by their IDs, leaving the name and the volumes to whoever has them.
environmentManager.stopOwnContainers(environment);
portAllocator.release(environment.getProxyPort());
return;
}
// Deleted while its containers started: the delete finishes now they are there to remove.
finishDelete(restoring);
}
/**
* Takes over the environment's running containers, or starts new ones on the volumes and with the secrets it kept,
* as CreateEnvironment starts them: the startup script runs and requirements.txt is installed before Airflow.
*/
private void startContainers(RestoringEnvironment restoring) {
Environment environment = restoring.environment();
if (environmentManager.adoptRunningEnvironment(environment)) {
keepSecrets(restoring);
return;
}
if (!MwaaEnvironmentManager.hasSecrets(environment)) {
// Stored before Floci kept the secrets: a container left under its name has them, and with none left
// its volumes went at the shutdown then, so it gets new ones. Either way they are kept before anything
// starts, so a start that fails part way, with that container gone, is tried again with them.
if (!environmentManager.recoverSecrets(environment)) {
environmentManager.giveNewSecrets(environment);
}
keepSecrets(restoring);
}
byte[] startupScriptContent = fetchStartupScript(environment);
S3Object requirements = fetchRequirements(environment);
if (requirements != null) {
requirementsEtagByEnvironment.put(environmentIdentity(environment), requirements.getETag());
bootstrapInstallsToCheck.add(environmentIdentity(environment));
}
byte[] requirementsContent = requirements != null ? requirements.getData() : null;
environmentManager.restartEnvironment(environment, environment.getAirflowVersion(), startupScriptContent,
requirementsContent);
}
/** Keeps the secrets the restore found or gave the environment, while its record is still the one it restores. */
private void keepSecrets(RestoringEnvironment restoring) {
synchronized (storedEnvironmentLock(restoring.accountId(), restoring.key())) {
if (storedStatus(restoring) != null) {
putRuntime(restoring.environment());
}
}
}
/**
* Starts the restored environment's web proxy on the port its webserver URL names, or, when that port is taken or
* the URL names none, on a new one its URL then names.
*/
private void startRestoredProxy(Environment environment) {
int recorded = environment.getProxyPort();
if (recorded > 0) {
try {
environment.setWebserverUrl(buildWebserverUrl(recorded));
startWebProxy(environment);
return;
} catch (RuntimeException e) {
LOG.warnv("MWAA environment {0} gets a new webserver URL: its web proxy cannot listen on port {1} "
+ "again: {2}", environment.getName(), String.valueOf(recorded), e.getMessage());
portAllocator.release(recorded);
environment.setProxyPort(0);
}
}
int proxyPort = portAllocator.allocateForInProcessListener(
config.services().mwaa().proxyBasePort(), config.services().mwaa().proxyMaxPort());
environment.setProxyPort(proxyPort);
environment.setWebserverUrl(buildWebserverUrl(proxyPort));
try {
startWebProxy(environment);
} catch (RuntimeException e) {
portAllocator.release(proxyPort);
environment.setProxyPort(0);
throw e;
}
}
/**
* Ends a restore whose containers did not start: the ones that did go, the volumes stay, and the environment is
* {@code UNAVAILABLE}, for the next start to try again, or {@code CREATE_FAILED} while it was being created. One
* deleted meanwhile is removed.
*/
private void failRestore(RestoringEnvironment restoring) {
Environment environment = restoring.environment();
environmentManager.stopOwnContainers(environment);
EnvironmentStatus storedNow;
synchronized (storedEnvironmentLock(restoring.accountId(), restoring.key())) {
storedNow = storedStatus(restoring);
if (storedNow != null && storedNow != EnvironmentStatus.DELETING) {
restoringEnvironments.remove(restoring.lockKey());
environment.setStatus(restoring.creating()
? EnvironmentStatus.CREATE_FAILED : EnvironmentStatus.UNAVAILABLE);
putEnvironment(environment);
}
}
if (storedNow == EnvironmentStatus.DELETING) {
finishDelete(restoring);
}
}
/** Finishes the delete of an environment deleted during its restore, or before it: as DeleteEnvironment does. */
private void finishDelete(RestoringEnvironment restoring) {
Environment environment = restoring.environment();
removeRuntime(environment);
synchronized (storedEnvironmentLock(restoring.accountId(), restoring.key())) {
restoringEnvironments.remove(restoring.lockKey());
if (storedStatus(restoring) == EnvironmentStatus.DELETING) {
deleteEnvironment(environment);
}
}
LOG.infov("Deleted MWAA environment {0}", environment.getName());
}
/**
* Ends an environment's restore, if it has not ended already: the poller and DeleteEnvironment treat the
* environment as any other again.
*/
private void endRestore(RestoringEnvironment restoring) {
synchronized (storedEnvironmentLock(restoring.accountId(), restoring.key())) {
restoringEnvironments.remove(restoring.lockKey());
}
}
/** The stored environment's status, or null when it is gone or another environment was created under its name. */
private EnvironmentStatus storedStatus(RestoringEnvironment restoring) {
return storage instanceof AccountAwareStorageBackend<Environment> aware
? aware.getForAccount(restoring.accountId(), restoring.key())
.filter(current -> Objects.equals(current.getCreatedAt(),
restoring.environment().getCreatedAt()))
.map(Environment::getStatus)
.orElse(null)
: null;
}
private Object storedEnvironmentLock(String accountId, String key) {
return storedEnvironmentLocks.lockFor(restoringKey(accountId, key));
}
private String restoringKey(Environment environment) {
return restoringKey(environmentAccount(environment),
environmentKey(environmentRegion(environment), environment.getName()));
}
private static String restoringKey(String accountId, String key) {
return accountId + "/" + key;
}
/** A stored environment, by the account, Region and name it belongs to. */
private record StoredEnvironment(String accountId, String region, String name) {
}
/**
* An environment the restore brings back, with the account, storage key and Region it is stored under, and
* whether it was still being created.
*/
private record RestoringEnvironment(String accountId, String key, String region, Environment environment,
boolean creating) {
String lockKey() {
return restoringKey(accountId, key);
}
}
public Environment createEnvironment(String name, CreateEnvironmentRequest request) {
if (name == null || name.isBlank()) {
throw new AwsException("ValidationException", "Environment name is required", 400);
@@ -260,19 +652,8 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
config.services().mwaa().proxyBasePort(), config.services().mwaa().proxyMaxPort());
environment.setProxyPort(proxyPort);
environment.setWebserverUrl(buildWebserverUrl(proxyPort));
String airflowContainerId = environment.getAirflowContainerId();
// The proxy reads this environment's own token map, not whatever the name maps to later: a token
// issued while an earlier environment of this name was being deleted lands in that one's map, not
// in this.
Map<String, Instant> webTokens = new ConcurrentHashMap<>();
webTokensByEnvironment.put(environmentIdentity(environment), webTokens);
proxyManager.startProxy(environmentIdentity(environment), proxyPort,
environment.getAirflowInternalHost(), environment.getAirflowInternalPort(),
this::isValidCliToken,
cliCommand -> environmentManager.runAirflowCli(airflowContainerId, version, cliCommand),
(proxyIdentity, token) -> isUnexpired(webTokens, token),
new MwaaWebProxy.AirflowAccount(MwaaEnvironmentManager.AIRFLOW_ADMIN_USER,
environment.getAirflowAdminPassword()));
startWebProxy(environment);
putRuntime(environment);
provisioned = true;
} catch (Exception e) {
LOG.errorv(e, "Failed to start MWAA environment {0}", name);
@@ -288,6 +669,24 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
return environment;
}
/** Starts the web proxy that serves the environment's webserver URL, on the port the environment holds. */
private void startWebProxy(Environment environment) {
String airflowContainerId = environment.getAirflowContainerId();
String version = environment.getAirflowVersion();
// The proxy reads this environment's own token map, not whatever the name maps to later: a token
// issued while an earlier environment of this name was being deleted lands in that one's map, not
// in this.
Map<String, Instant> webTokens = new ConcurrentHashMap<>();
webTokensByEnvironment.put(environmentIdentity(environment), webTokens);
proxyManager.startProxy(environmentIdentity(environment), environment.getProxyPort(),
environment.getAirflowInternalHost(), environment.getAirflowInternalPort(),
this::isValidCliToken,
cliCommand -> environmentManager.runAirflowCli(airflowContainerId, version, cliCommand),
(proxyIdentity, token) -> isUnexpired(webTokens, token),
new MwaaWebProxy.AirflowAccount(MwaaEnvironmentManager.AIRFLOW_ADMIN_USER,
environment.getAirflowAdminPassword()));
}
/**
* Best-effort teardown for a create that didn't fully provision — stops the proxy (a no-op if it
* never started, since {@link MwaaProxyManager#stopProxy} just finds nothing registered),
@@ -411,7 +810,26 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
public Environment deleteEnvironment(String name) {
Environment environment = getEnvironment(name);
environment.setStatus(EnvironmentStatus.DELETING);
String accountId = regionResolver.getAccountId();
String key = environmentKey(regionResolver.getRegion(), name);
synchronized (storedEnvironmentLock(accountId, key)) {
environment.setStatus(EnvironmentStatus.DELETING);
if (restoringEnvironments.contains(restoringKey(accountId, key))) {
// The startup restore is starting its containers, and finishes the delete once that start is through.
// Until then the environment reads DELETING, as AWS reports one being deleted, and its name stays
// taken.
putEnvironment(environment);
LOG.infov("Deleting MWAA environment {0} once its restore is through", name);
return environment;
}
}
removeRuntime(environment);
deleteEnvironment(environment);
return environment;
}
/** Removes what runs for the environment: its web proxy, containers and volumes, and what Floci holds for them. */
private void removeRuntime(Environment environment) {
if (!config.services().mwaa().mock()) {
proxyManager.stopProxy(environmentIdentity(environment));
environmentManager.stopEnvironment(environment);
@@ -426,8 +844,6 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
dagSyncState.remove(environmentIdentity);
requirementsEtagByEnvironment.remove(environmentIdentity);
bootstrapInstallsToCheck.remove(environmentIdentity);
deleteEnvironment(environment);
return environment;
}
public Map<String, Object> createWebLoginToken(String name) {
@@ -617,7 +1033,9 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
// Package-private (not private) so MwaaServiceTest can exercise a single poll pass directly,
// without waiting on the scheduled executor.
void checkReadiness(Environment environment) {
if (environment.getStatus() != EnvironmentStatus.CREATING) {
EnvironmentStatus status = environment.getStatus();
if (status != EnvironmentStatus.CREATING && status != EnvironmentStatus.MAINTENANCE
|| restoringEnvironments.contains(restoringKey(environment))) {
return;
}
boolean ready = environmentManager.isReady(environment);
@@ -628,7 +1046,7 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
// before tearing down its containers) to have moved this environment past CREATING in the
// meantime. Re-checking right before writing avoids resurrecting a just-deleted environment
// into storage with a status decided from stale, pre-delete information.
if (environment.getStatus() != EnvironmentStatus.CREATING) {
if (environment.getStatus() != status) {
return;
}
if (ready) {
@@ -639,10 +1057,13 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
// docker start returns as soon as a container's entrypoint launches, so its Postgres or
// Airflow container dying partway through never surfaces here on its own; without this
// check the environment would poll dead containers and report CREATING forever instead
// of the CREATE_FAILED a real failure should be.
// of the CREATE_FAILED a real failure should be. One whose containers came back after a
// restart is UNAVAILABLE, as AWS reports an environment that did not return to its state.
EnvironmentStatus failed = status == EnvironmentStatus.CREATING
? EnvironmentStatus.CREATE_FAILED : EnvironmentStatus.UNAVAILABLE;
LOG.errorv("MWAA environment {0}''s Postgres or Airflow container exited before "
+ "becoming ready; marking CREATE_FAILED", environment.getName());
environment.setStatus(EnvironmentStatus.CREATE_FAILED);
+ "becoming ready; marking {1}", environment.getName(), failed);
environment.setStatus(failed);
putEnvironment(environment);
}
}
@@ -679,7 +1100,7 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
String prefix = environment.getDagS3Path().endsWith("/")
? environment.getDagS3Path() : environment.getDagS3Path() + "/";
List<S3Object> objects = s3Service.listObjects(bucket, prefix, null, 1000);
List<S3Object> objects = listDagObjects(bucket, prefix);
Map<String, String> currentByKey = new HashMap<>();
for (S3Object obj : objects) {
String relative = obj.getKey().substring(prefix.length());
@@ -690,7 +1111,18 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
}
String environmentIdentity = environmentIdentity(environment);
Map<String, String> previous = dagSyncState.computeIfAbsent(environmentIdentity, k -> new HashMap<>());
Map<String, String> previous = dagSyncState.get(environmentIdentity);
if (previous == null) {
// The first pass since the environment's containers started, or came back after a restart on a DAG volume
// that may hold files the S3 prefix no longer has, which no earlier pass of this Floci recorded. Each file
// there counts as synced with an ETag S3 never gives, so one S3 still has is copied again and one it has
// not is removed.
previous = new HashMap<>();
for (String relative : environmentManager.listDagFiles(environment)) {
previous.put(relative, "");
}
dagSyncState.put(environmentIdentity, previous);
}
for (Map.Entry<String, String> entry : currentByKey.entrySet()) {
String relative = entry.getKey();
String etag = entry.getValue();
@@ -715,6 +1147,22 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
syncRequirementsIfNeeded(environment, bucket);
}
/**
* Every object under the DAG prefix, page by page: the sync removes from the container what this does not name,
* so a DAG past the first page must not read as gone.
*/
private List<S3Object> listDagObjects(String bucket, String prefix) {
List<S3Object> objects = new ArrayList<>();
String continuationToken = null;
do {
S3Service.ListObjectsResult page = s3Service.listObjectsWithPrefixes(bucket, prefix, null, 1000,
continuationToken, null);
objects.addAll(page.objects());
continuationToken = page.isTruncated() ? page.nextContinuationToken() : null;
} while (continuationToken != null);
return objects;
}
// installRequirements re-checks on every DAG-sync pass (rather than only at CreateEnvironment
// time) so that updating requirements.txt in S3 after creation takes effect automatically,
// matching how DAG file changes are already picked up. The install itself runs on
@@ -835,6 +1283,13 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
} else {
storage.delete(key);
}
runtimeStorage.deleteForAccount(accountId, key);
}
private void putRuntime(Environment environment) {
runtimeStorage.putForAccount(environmentAccount(environment),
environmentKey(environmentRegion(environment), environment.getName()),
EnvironmentRuntime.of(environment));
}
private Optional<Environment> getStoredEnvironment(String accountId, String region, String name) {
@@ -106,6 +106,9 @@ public class Environment {
@JsonIgnore
private String airflowAdminPassword;
@JsonIgnore
private String fernetKey;
public Environment() {}
public String getName() { return name; }
@@ -198,6 +201,9 @@ public class Environment {
public String getAirflowAdminPassword() { return airflowAdminPassword; }
public void setAirflowAdminPassword(String airflowAdminPassword) { this.airflowAdminPassword = airflowAdminPassword; }
public String getFernetKey() { return fernetKey; }
public void setFernetKey(String fernetKey) { this.fernetKey = fernetKey; }
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class LastUpdate {
@@ -0,0 +1,48 @@
package io.floci.aws.services.mwaa.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/**
* Floci's own record of the secrets an environment's metadata database was set up with, never sent on the wire.
* Floci starts the containers again with them after a restart, on the volumes they kept, so the database accepts its
* password, the connections and variables Airflow encrypted still decrypt, and the admin still signs in. Stored beside
* the environment, under its key, for the environment created at {@link #getEnvironmentCreatedAt()}.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class EnvironmentRuntime {
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
private Instant environmentCreatedAt;
private String dbPassword;
private String fernetKey;
private String airflowAdminPassword;
public EnvironmentRuntime() {}
/** The secrets the environment's containers run with now. */
public static EnvironmentRuntime of(Environment environment) {
EnvironmentRuntime runtime = new EnvironmentRuntime();
runtime.setEnvironmentCreatedAt(environment.getCreatedAt());
runtime.setDbPassword(environment.getDbPassword());
runtime.setFernetKey(environment.getFernetKey());
runtime.setAirflowAdminPassword(environment.getAirflowAdminPassword());
return runtime;
}
public Instant getEnvironmentCreatedAt() { return environmentCreatedAt; }
public void setEnvironmentCreatedAt(Instant environmentCreatedAt) { this.environmentCreatedAt = environmentCreatedAt; }
public String getDbPassword() { return dbPassword; }
public void setDbPassword(String dbPassword) { this.dbPassword = dbPassword; }
public String getFernetKey() { return fernetKey; }
public void setFernetKey(String fernetKey) { this.fernetKey = fernetKey; }
public String getAirflowAdminPassword() { return airflowAdminPassword; }
public void setAirflowAdminPassword(String airflowAdminPassword) { this.airflowAdminPassword = airflowAdminPassword; }
}
@@ -4,5 +4,5 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public enum EnvironmentStatus {
CREATING, AVAILABLE, UPDATING, DELETING, DELETED, CREATE_FAILED, UPDATE_FAILED, UNAVAILABLE
CREATING, AVAILABLE, UPDATING, DELETING, DELETED, CREATE_FAILED, UPDATE_FAILED, UNAVAILABLE, MAINTENANCE
}
@@ -37,6 +37,7 @@ import io.floci.aws.services.lambda.durable.DurableExecutionService;
import io.floci.aws.services.memorydb.MemoryDbService;
import io.floci.aws.services.memorydb.container.MemoryDbContainerManager;
import io.floci.aws.services.memorydb.proxy.MemoryDbProxyManager;
import io.floci.aws.services.mwaa.MwaaService;
import io.floci.aws.services.neptune.container.NeptuneContainerManager;
import io.floci.aws.services.neptune.proxy.NeptuneProxyManager;
import io.floci.aws.services.opensearch.OpenSearchService;
@@ -132,6 +133,8 @@ class EmulatorLifecycleTest {
@Mock private EmulatorConfig.KinesisAnalyticsServiceConfig kinesisAnalyticsServiceConfig;
@Mock private OpenSearchService openSearchService;
@Mock private EmulatorConfig.OpenSearchServiceConfig openSearchServiceConfig;
@Mock private MwaaService mwaaService;
@Mock private EmulatorConfig.MwaaServiceConfig mwaaServiceConfig;
@Mock private EmulatorConfig.AmazonMqServiceConfig amazonMqServiceConfig;
@Mock private EmulatorConfig.SageMakerServiceConfig sageMakerServiceConfig;
@Mock private EksService eksService;
@@ -186,6 +189,8 @@ class EmulatorLifecycleTest {
Mockito.lenient().when(kinesisAnalyticsServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.opensearch()).thenReturn(openSearchServiceConfig);
Mockito.lenient().when(openSearchServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.mwaa()).thenReturn(mwaaServiceConfig);
Mockito.lenient().when(mwaaServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.amazonmq()).thenReturn(amazonMqServiceConfig);
Mockito.lenient().when(amazonMqServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.sagemaker()).thenReturn(sageMakerServiceConfig);
@@ -206,7 +211,7 @@ class EmulatorLifecycleTest {
memoryDbContainerManager, memoryDbProxyManager, memoryDbService,
docDbContainerManager, neptuneContainerManager, neptuneProxyManager,
rabbitMqManager, amazonMqService, flinkContainerManager, kinesisAnalyticsService,
openSearchService,
openSearchService, mwaaService,
sageMakerService, rdsService, timestreamInfluxDbService,
elbV2Service, elbClassicService, ecsService,
initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller,
@@ -620,6 +625,48 @@ class EmulatorLifecycleTest {
verify(openSearchService, never()).restorePersistedRuntime();
}
@Test
void restoresPersistedMwaaEnvironmentsAfterStorageLoad() {
stubStorageConfig();
when(mwaaServiceConfig.enabled()).thenReturn(true);
when(mwaaService.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, mwaaService);
inOrder.verify(storageFactory).loadAll();
inOrder.verify(mwaaService).restorePersistedRuntime();
}
@Test
void aFailedMwaaRestoreDoesNotStopTheOtherRestores() {
stubStorageConfig();
when(mwaaServiceConfig.enabled()).thenReturn(true);
when(elbv2ServiceConfig.enabled()).thenReturn(true);
when(mwaaService.restorePersistedRuntime()).thenReturn(CompletableFuture.failedFuture(
new IllegalStateException("Could not restore MWAA environment 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 leavesMwaaEnvironmentsUntouchedWhenMwaaIsDisabled() {
stubStorageConfig();
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
verify(mwaaService, never()).restorePersistedRuntime();
}
@Test
void restoresPersistedAmazonMqBrokersAfterStorageLoad() {
stubStorageConfig();
@@ -19,6 +19,7 @@ import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.core.common.docker.DockerHostResolver;
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
import io.floci.aws.services.ec2.Ec2Service;
@@ -38,6 +39,7 @@ import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -1003,4 +1005,476 @@ class MwaaEnvironmentManagerTest {
assertEquals(List.of(), commands);
}
}
@Nested
class Restart {
private static final String[] SECRETS = {
"AIRFLOW__DATABASE__SQL_ALCHEMY_CONN="
+ "postgresql+psycopg2://airflow:running-db-pw@172.18.0.9:5432/airflow",
"AIRFLOW__CORE__FERNET_KEY=running-fernet-key",
"_AIRFLOW_WWW_USER_PASSWORD=running-admin-pw"};
private Environment environment;
private DockerClient docker;
@BeforeEach
void anEnvironment() {
environment = new Environment();
environment.setName("my-env");
docker = Mockito.mock(DockerClient.class);
when(lifecycleManager.getDockerClient()).thenReturn(docker);
// Docker has no container of any name a test does not give one.
when(docker.inspectContainerCmd(anyString())).thenAnswer(invocation -> Mockito.mock(
InspectContainerCmd.class, missing -> {
throw new NotFoundException("No such container: " + invocation.getArgument(0));
}));
when(lifecycleManager.tryListVolumeNames()).thenReturn(Optional.of(Set.of()));
}
private void withSavedSecrets() {
environment.setDbPassword("saved-db-pw");
environment.setFernetKey("saved-fernet-key");
environment.setAirflowAdminPassword("saved-admin-pw");
}
/** A container Docker has under {@code name}, started with {@code env}. */
private void survivor(String name, String id, boolean running, String... env) {
InspectContainerResponse response = Mockito.mock(InspectContainerResponse.class, Mockito.RETURNS_DEEP_STUBS);
when(response.getId()).thenReturn(id);
when(response.getState().getRunning()).thenReturn(running);
when(response.getConfig().getEnv()).thenReturn(env);
InspectContainerCmd inspect = Mockito.mock(InspectContainerCmd.class);
when(inspect.exec()).thenReturn(response);
Mockito.doReturn(inspect).when(docker).inspectContainerCmd(name);
}
/** Docker answers no inspect of any container. */
private void dockerCannotSay() {
when(docker.inspectContainerCmd(anyString())).thenThrow(new IllegalStateException("daemon unreachable"));
}
private String legacy(String name) {
return ContainerStorageHelper.legacyDockerName(config, name);
}
private String airflowName() {
return manager.airflowContainerName(environment);
}
private String dbName() {
return manager.dbContainerName(environment);
}
private ContainerSpec createdSpec() {
ArgumentCaptor<ContainerSpec> spec = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(spec.capture());
return spec.getValue();
}
@Test
void aRestartedAirflowGetsTheSecretsItsDatabaseWasSetUpWith() {
withSavedSecrets();
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(lifecycleManager.create(any())).thenReturn("airflow-container-id");
when(lifecycleManager.startCreated(eq("airflow-container-id"), any())).thenReturn(new ContainerInfo(
"airflow-container-id", Map.of(8080, new EndpointInfo("172.18.0.5", 8080))));
manager.startAirflowContainer(environment, "2.10.5", "172.18.0.9", "saved-db-pw", null, null);
ContainerSpec spec = createdSpec();
assertTrue(spec.env().contains("AIRFLOW__CORE__FERNET_KEY=saved-fernet-key"));
assertTrue(spec.env().contains("_AIRFLOW_WWW_USER_PASSWORD=saved-admin-pw"));
assertEquals("saved-fernet-key", environment.getFernetKey());
assertEquals("saved-admin-pw", environment.getAirflowAdminPassword());
}
@Test
void aNewEnvironmentStartsOnEmptyVolumesWithSecretsOfItsOwn() {
withSavedSecrets();
when(lifecycleManager.create(any())).thenThrow(new IllegalStateException("stop here"));
assertThrows(IllegalStateException.class,
() -> manager.startEnvironment(environment, "2.10.5", null, null));
InOrder inOrder = Mockito.inOrder(lifecycleManager);
for (String volume : List.of(dbName(), airflowName() + "-dags", airflowName() + "-logs")) {
inOrder.verify(lifecycleManager).removeVolumeStrict(volume);
inOrder.verify(lifecycleManager).removeVolumeStrict(legacy(volume));
}
inOrder.verify(lifecycleManager).ensureVolume(dbName());
assertNotEquals("saved-db-pw", environment.getDbPassword());
assertNotEquals("saved-fernet-key", environment.getFernetKey());
assertNotEquals("saved-admin-pw", environment.getAirflowAdminPassword());
}
@Test
void aRestartKeepsTheVolumesAndTheSecretsTheDatabaseWasSetUpWith() {
withSavedSecrets();
Set<String> volumes = Set.of(dbName());
when(lifecycleManager.tryListVolumeNames()).thenReturn(Optional.of(volumes));
when(lifecycleManager.create(any())).thenThrow(new IllegalStateException("stop here"));
assertThrows(IllegalStateException.class,
() -> manager.restartEnvironment(environment, "2.10.5", null, null));
ContainerSpec spec = createdSpec();
assertTrue(spec.env().contains("POSTGRES_PASSWORD=saved-db-pw"));
assertEquals(List.of(dbName()), spec.mounts().stream().map(Mount::getSource).toList());
verify(lifecycleManager).ensureVolume(dbName());
verify(lifecycleManager, never()).removeVolumeStrict(anyString());
verify(lifecycleManager, never()).removeVolume(anyString());
assertEquals("saved-fernet-key", environment.getFernetKey());
}
@Test
void aRestartUsesTheVolumeAnOlderFlociLeftWhenOnlyThatOneIsThere() {
withSavedSecrets();
Set<String> volumes = Set.of(legacy(dbName()));
when(lifecycleManager.tryListVolumeNames()).thenReturn(Optional.of(volumes));
when(lifecycleManager.create(any())).thenThrow(new IllegalStateException("stop here"));
assertThrows(IllegalStateException.class,
() -> manager.restartEnvironment(environment, "2.10.5", null, null));
assertEquals(List.of(legacy(dbName())), createdSpec().mounts().stream().map(Mount::getSource).toList());
verify(lifecycleManager).ensureVolume(legacy(dbName()));
}
@Test
void aRestartDockerCannotListTheVolumesOfIsRefused() {
withSavedSecrets();
when(lifecycleManager.tryListVolumeNames()).thenReturn(Optional.empty());
assertThrows(IllegalStateException.class,
() -> manager.restartEnvironment(environment, "2.10.5", null, null));
verify(lifecycleManager, never()).ensureVolume(anyString());
verify(lifecycleManager, never()).create(any());
}
@Test
void aRestartWithoutTheSavedSecretsIsRefused() {
assertThrows(IllegalStateException.class,
() -> manager.restartEnvironment(environment, "2.10.5", null, null));
verify(lifecycleManager, never()).create(any());
}
@Test
void containersLeftUnderEitherNameGoBeforeARestart() {
withSavedSecrets();
survivor(airflowName(), "old-airflow", true);
survivor(legacy(dbName()), "old-legacy-db", false);
when(lifecycleManager.create(any())).thenThrow(new IllegalStateException("stop here"));
assertThrows(IllegalStateException.class,
() -> manager.restartEnvironment(environment, "2.10.5", null, null));
InOrder inOrder = Mockito.inOrder(lifecycleManager);
inOrder.verify(lifecycleManager).removeIfExistsStrict("old-airflow");
inOrder.verify(lifecycleManager).removeIfExistsStrict("old-legacy-db");
inOrder.verify(lifecycleManager).create(any());
}
@Test
void aRestartDoesNotStartBesideAContainerDockerWillNotRemove() {
withSavedSecrets();
survivor(legacy(dbName()), "stuck-db", true);
Mockito.doThrow(new IllegalStateException("Failed to remove stale container stuck-db"))
.when(lifecycleManager).removeIfExistsStrict("stuck-db");
assertThrows(IllegalStateException.class,
() -> manager.restartEnvironment(environment, "2.10.5", null, null));
verify(lifecycleManager, never()).create(any());
}
@Test
void aRestartDoesNotStartWhenDockerCannotSayWhatIsLeft() {
withSavedSecrets();
dockerCannotSay();
assertThrows(IllegalStateException.class,
() -> manager.restartEnvironment(environment, "2.10.5", null, null));
verify(lifecycleManager, never()).create(any());
}
@Test
void stoppingTheContainersRemovesThemByIdAndByNameAndKeepsTheVolumes() {
environment.setAirflowContainerId("airflow-container-id");
environment.setDbContainerId("db-container-id");
survivor(legacy(airflowName()), "unreached-airflow", true);
manager.stopContainers(environment);
verify(lifecycleManager).stopAndRemove("airflow-container-id", null);
verify(lifecycleManager).stopAndRemove("db-container-id", null);
verify(lifecycleManager).removeIfExistsStrict("unreached-airflow");
verify(lifecycleManager, never()).removeVolume(anyString());
}
@Test
void stoppingOnlyItsOwnContainersLeavesItsNamesAlone() {
environment.setAirflowContainerId("airflow-container-id");
environment.setDbContainerId("db-container-id");
survivor(airflowName(), "recreated-airflow", true);
manager.stopOwnContainers(environment);
verify(lifecycleManager).stopAndRemove("airflow-container-id", null);
verify(lifecycleManager).stopAndRemove("db-container-id", null);
verify(lifecycleManager, never()).removeIfExistsStrict(anyString());
verify(lifecycleManager, never()).removeVolume(anyString());
}
@Test
void stoppingTheEnvironmentRemovesWhatIsLeftUnderItsNamesInEitherScheme() {
survivor(airflowName(), "survivor-airflow", true);
manager.stopEnvironment(environment);
verify(lifecycleManager).removeIfExistsStrict("survivor-airflow");
for (String volume : List.of(dbName(), airflowName() + "-dags", airflowName() + "-logs")) {
verify(lifecycleManager).removeVolume(volume);
verify(lifecycleManager).removeVolume(legacy(volume));
}
}
@Test
void aDockerThatCannotSayWhatIsLeftDoesNotStopTheDelete() {
dockerCannotSay();
manager.stopEnvironment(environment);
verify(lifecycleManager).removeVolume(dbName());
}
@Test
void runningContainersAreTakenOverWithTheSecretsTheyRunWith() {
survivor(airflowName(), "running-airflow", true, SECRETS);
survivor(dbName(), "running-db", true);
when(lifecycleManager.adopt(eq("running-airflow"), eq(List.of(8080)), any())).thenReturn(new ContainerInfo(
"running-airflow", Map.of(8080, new EndpointInfo("localhost", 32768))));
assertTrue(manager.adoptRunningEnvironment(environment));
assertEquals("running-airflow", environment.getAirflowContainerId());
assertEquals("running-db", environment.getDbContainerId());
assertEquals("running-db-pw", environment.getDbPassword());
assertEquals("running-fernet-key", environment.getFernetKey());
assertEquals("running-admin-pw", environment.getAirflowAdminPassword());
assertEquals("localhost", environment.getAirflowInternalHost());
assertEquals(32768, environment.getAirflowInternalPort());
}
@Test
void runningContainersAnOlderFlociNamedAreTakenOver() {
survivor(legacy(airflowName()), "legacy-airflow", true, SECRETS);
survivor(legacy(dbName()), "legacy-db", true);
when(lifecycleManager.adopt(eq("legacy-airflow"), eq(List.of(8080)), any())).thenReturn(new ContainerInfo(
"legacy-airflow", Map.of(8080, new EndpointInfo("localhost", 32769))));
assertTrue(manager.adoptRunningEnvironment(environment));
assertEquals("legacy-airflow", environment.getAirflowContainerId());
assertEquals("legacy-db", environment.getDbContainerId());
assertEquals("running-db-pw", environment.getDbPassword());
}
@Test
void containersAreNotTakenOverUnlessBothRun() {
survivor(airflowName(), "running-airflow", true, SECRETS);
survivor(dbName(), "exited-db", false);
assertFalse(manager.adoptRunningEnvironment(environment));
verify(lifecycleManager, never()).adopt(anyString(), any(), any());
assertNull(environment.getAirflowContainerId());
}
@Test
void containersAreNotTakenOverWithoutTheSecretsTheyRunWith() {
survivor(airflowName(), "running-airflow", true, SECRETS[0], SECRETS[2]);
survivor(dbName(), "running-db", true);
assertFalse(manager.adoptRunningEnvironment(environment));
verify(lifecycleManager, never()).adopt(anyString(), any(), any());
}
@Test
void aDockerThatCannotSayFailsTheTakeoverRatherThanReadingAsNothingLeft() {
dockerCannotSay();
assertThrows(IllegalStateException.class, () -> manager.adoptRunningEnvironment(environment));
verify(lifecycleManager, never()).adopt(anyString(), any(), any());
}
@Test
void theSecretsAreRecoveredFromAStoppedContainerAnOlderFlociLeft() {
survivor(legacy(airflowName()), "stopped-airflow", false, SECRETS);
assertTrue(manager.recoverSecrets(environment));
assertEquals("running-db-pw", environment.getDbPassword());
assertEquals("running-fernet-key", environment.getFernetKey());
assertEquals("running-admin-pw", environment.getAirflowAdminPassword());
}
@Test
void noSecretsAreRecoveredFromAContainerThatDoesNotNameThem() {
survivor(airflowName(), "foreign-airflow", false, SECRETS[1]);
assertFalse(manager.recoverSecrets(environment));
assertNull(environment.getFernetKey());
}
@Test
void noSecretsAreRecoveredWithNoContainerLeft() {
assertFalse(manager.recoverSecrets(environment));
assertNull(environment.getDbPassword());
}
@Test
void aDockerThatCannotSayFailsTheRecovery() {
dockerCannotSay();
assertThrows(IllegalStateException.class, () -> manager.recoverSecrets(environment));
}
@Test
void anEnvironmentWithoutSecretsGetsNoNewOnesWhileItsDatabaseVolumesAreLeft() {
Set<String> volumes = Set.of(legacy(dbName()));
when(lifecycleManager.tryListVolumeNames()).thenReturn(Optional.of(volumes));
IllegalStateException refused = assertThrows(IllegalStateException.class,
() -> manager.giveNewSecrets(environment));
assertTrue(refused.getMessage().contains(legacy(dbName())), refused.getMessage());
assertNull(environment.getDbPassword());
verify(lifecycleManager, never()).removeVolumeStrict(anyString());
}
@Test
void anEnvironmentWithoutSecretsAndNothingLeftGetsNewOnes() {
manager.giveNewSecrets(environment);
assertTrue(MwaaEnvironmentManager.hasSecrets(environment));
verify(lifecycleManager, never()).create(any());
}
@Test
void anEnvironmentWithoutSecretsGetsNoNewOnesWhenDockerCannotListTheVolumes() {
when(lifecycleManager.tryListVolumeNames()).thenReturn(Optional.empty());
assertThrows(IllegalStateException.class, () -> manager.giveNewSecrets(environment));
assertNull(environment.getDbPassword());
}
@Test
void theDagFilesAreReadFromTheContainerWithoutPythonsCaches() {
environment.setAirflowContainerId("airflow-container-id");
ContainerExecStubs.completeEveryExec(docker, "airflow-container-id", 0, "/opt/airflow/dags/a.py\n"
+ "/opt/airflow/dags/sub/b.py\n/opt/airflow/dags/__pycache__/a.cpython-311.pyc\n", "");
assertEquals(List.of("a.py", "sub/b.py"), manager.listDagFiles(environment));
}
@Test
void aDagListingThatFailsIsNotReadAsAnEmptyFolder() {
environment.setAirflowContainerId("airflow-container-id");
ContainerExecStubs.completeEveryExec(docker, "airflow-container-id", 1, "", "find: permission denied");
assertThrows(IllegalStateException.class, () -> manager.listDagFiles(environment));
}
@Test
void theDatabasePasswordIsReadFromTheUrlAirflowWasGiven() {
assertEquals("pw-with_chars", MwaaEnvironmentManager.dbPasswordOf(
"postgresql+psycopg2://airflow:pw-with_chars@10.0.0.2:5432/airflow"));
assertNull(MwaaEnvironmentManager.dbPasswordOf("sqlite:////tmp/airflow.db"));
assertNull(MwaaEnvironmentManager.dbPasswordOf("mysql+mysqldb://someone:password@db.example:3306/airflow"));
assertNull(MwaaEnvironmentManager.dbPasswordOf("postgresql+psycopg2://airflow:@10.0.0.2:5432/airflow"));
assertNull(MwaaEnvironmentManager.dbPasswordOf(null));
}
@Test
void nothingStartsOrIsTakenOverOnceFlociIsShuttingDown() {
withSavedSecrets();
manager.markShuttingDown();
assertThrows(MwaaEnvironmentManager.ShuttingDownException.class,
() -> manager.startEnvironment(environment, "2.10.5", null, null));
assertThrows(MwaaEnvironmentManager.ShuttingDownException.class,
() -> manager.restartEnvironment(environment, "2.10.5", null, null));
assertThrows(MwaaEnvironmentManager.ShuttingDownException.class,
() -> manager.adoptRunningEnvironment(environment));
assertTrue(manager.isShuttingDown());
verify(lifecycleManager, never()).create(any());
verify(docker, never()).inspectContainerCmd(anyString());
assertEquals("saved-db-pw", environment.getDbPassword());
}
@Test
void aDatabaseContainerThatDoesNotStartIsRecordedForItsCleanup() {
withSavedSecrets();
when(lifecycleManager.create(any())).thenReturn("db-container-id");
when(lifecycleManager.startCreated(eq("db-container-id"), any()))
.thenThrow(new IllegalStateException("port taken"));
assertThrows(IllegalStateException.class,
() -> manager.restartEnvironment(environment, "2.10.5", null, null));
assertEquals("db-container-id", environment.getDbContainerId());
}
@Test
void aShutdownDuringTheAirflowStartRemovesBothContainers() {
withSavedSecrets();
ContainerExecStubs.completeEveryExec(docker, "db-container-id", 0, "", "");
InspectContainerCmd inspect = Mockito.mock(InspectContainerCmd.class);
InspectContainerResponse response = Mockito.mock(InspectContainerResponse.class);
NetworkSettings settings = Mockito.mock(NetworkSettings.class);
ContainerNetwork network = Mockito.mock(ContainerNetwork.class);
Mockito.doReturn(inspect).when(docker).inspectContainerCmd("db-container-id");
when(inspect.exec()).thenReturn(response);
when(response.getNetworkSettings()).thenReturn(settings);
when(settings.getNetworks()).thenReturn(Map.of("bridge", network));
when(network.getIpAddress()).thenReturn("172.18.0.9");
when(lifecycleManager.create(any())).thenReturn("db-container-id", "airflow-container-id");
when(lifecycleManager.startCreated(eq("db-container-id"), any()))
.thenReturn(new ContainerInfo("db-container-id", Map.of()));
when(lifecycleManager.startCreated(eq("airflow-container-id"), any())).thenAnswer(invocation -> {
manager.markShuttingDown();
return new ContainerInfo("airflow-container-id", Map.of(8080, new EndpointInfo("172.18.0.5", 8080)));
});
assertThrows(MwaaEnvironmentManager.ShuttingDownException.class,
() -> manager.restartEnvironment(environment, "2.10.5", null, null));
verify(lifecycleManager).stopAndRemove("airflow-container-id", null);
verify(lifecycleManager).stopAndRemove("db-container-id", null);
}
@Test
void aStartOvertakenByTheShutdownRemovesWhatItStarted() {
withSavedSecrets();
when(lifecycleManager.create(any())).thenReturn("db-container-id");
when(lifecycleManager.startCreated(eq("db-container-id"), any())).thenAnswer(invocation -> {
manager.markShuttingDown();
return new ContainerInfo("db-container-id", Map.of());
});
assertThrows(MwaaEnvironmentManager.ShuttingDownException.class,
() -> manager.restartEnvironment(environment, "2.10.5", null, null));
verify(lifecycleManager).stopAndRemove("db-container-id", null);
verify(lifecycleManager, times(1)).create(any());
}
}
}
@@ -0,0 +1,175 @@
package io.floci.aws.services.mwaa;
import com.fasterxml.jackson.core.type.TypeReference;
import com.github.dockerjava.api.DockerClient;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.mwaa.model.Environment;
import io.floci.aws.services.mwaa.model.EnvironmentRuntime;
import io.floci.aws.services.mwaa.proxy.MwaaProxyManager;
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 io.restassured.path.json.JsonPath;
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 java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* #5664: an MWAA environment comes back after Floci restarts with what its metadata database holds. Shutdown removes
* the environment's containers and keeps their volumes; the startup restore starts new ones on them with the secrets
* the database was set up with, so an Airflow variable set before, which Airflow stores encrypted with the
* environment's Fernet key, still reads back, through the same webserver URL. Stopping the web proxy and the
* containers, as shutdown does, stands in for the shutdown, reloading the records from disk for what a restart reads
* back, and the restore is what startup calls.
*
* <p>A Docker end-to-end check: it runs real Postgres and Airflow containers, which the shared test configuration
* mocks, with the environment records on disk, which it keeps in memory.
*/
@QuarkusTest
@TestProfile(MwaaEnvironmentRestartDockerNightlyIntegrationTest.Profile.class)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
// Bounded waits: the Airflow image's pull, then the environment starting twice.
@Timeout(value = 10, unit = TimeUnit.MINUTES)
class MwaaEnvironmentRestartDockerNightlyIntegrationTest {
/** Real Airflow environments, their records on disk. */
public static final class Profile implements QuarkusTestProfile {
// Its own directory, so the restore finds no environment records but this test's.
private static final String DATA = "./target/test-data/mwaa-restart-" + UUID.randomUUID();
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.mwaa.mock", "false",
"floci.storage.mode", "persistent",
"floci.storage.persistent-path", DATA);
}
}
private static final String JSON = "application/json";
private static final String VARIABLE = "restart_check";
private static final Duration ENVIRONMENT_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
MwaaService mwaaService;
@Inject
MwaaEnvironmentManager environmentManager;
@Inject
MwaaProxyManager proxyManager;
@Inject
StorageFactory storageFactory;
@BeforeEach
void requireDocker() {
Assumptions.assumeTrue(DockerAvailability.answers(dockerClient),
"Docker daemon must be available for the MWAA restart check");
}
@Test
void anEnvironmentKeepsItsMetadataAcrossARestart() throws Exception {
String name = "restart-" + UUID.randomUUID().toString().substring(0, 8);
given().contentType(JSON)
.body("""
{"ExecutionRoleArn": "arn:aws:iam::000000000000:role/mwaa-execution-role",
"SourceBucketArn": "arn:aws:s3:::%s", "DagS3Path": "dags"}
""".formatted(name))
.when().put("/environments/" + name)
.then().statusCode(200);
try {
String webserverUrl = awaitAvailable(name);
CliResult set = cli(name, "variables set " + VARIABLE + " kept");
assertEquals(200, set.status(), set.toString());
Environment running = mwaaService.getEnvironment(name);
String airflowContainer = running.getAirflowContainerId();
proxyManager.stopProxy(mwaaService.environmentIdentity(running));
environmentManager.stopContainers(running);
// What a restart reads back: the records on disk, not the ones in memory.
storageFactory.create("mwaa", "mwaa-environments.json",
new TypeReference<Map<String, Environment>>() {}).load();
storageFactory.create("mwaa", "mwaa-environment-runtime.json",
new TypeReference<Map<String, EnvironmentRuntime>>() {}).load();
assertNotSame(running, mwaaService.getEnvironment(name));
mwaaService.restorePersistedRuntime().join();
assertEquals(webserverUrl, awaitAvailable(name));
assertNotEquals(airflowContainer, mwaaService.getEnvironment(name).getAirflowContainerId());
CliResult get = cli(name, "variables get " + VARIABLE);
assertEquals(200, get.status(), get.toString());
assertTrue(get.stdout().contains("kept"), get.toString());
} finally {
given().when().delete("/environments/" + name);
}
}
/** Waits for the environment to be AVAILABLE and returns its webserver URL. */
private static String awaitAvailable(String name) {
await("environment " + name + " available").atMost(ENVIRONMENT_TIMEOUT).pollInterval(Duration.ofSeconds(3))
.until(() -> given().when().get("/environments/" + name)
.then().statusCode(200).extract().<String>path("Environment.Status"), status -> {
if ("CREATE_FAILED".equals(status) || "UNAVAILABLE".equals(status)) {
throw new AssertionError("environment " + name + " is " + status);
}
return "AVAILABLE".equals(status);
});
return given().when().get("/environments/" + name)
.then().statusCode(200).extract().path("Environment.WebserverUrl");
}
/** The HTTP status of a CLI call and the command's output. */
private record CliResult(int status, String stdout, String stderr) {
}
/** Runs an Airflow CLI command through the environment's web server, as an Amazon MWAA CLI token allows. */
private CliResult cli(String name, String command) throws Exception {
JsonPath token = given().contentType(JSON).when().post("/clitoken/" + name)
.then().statusCode(200).extract().jsonPath();
HttpRequest request = HttpRequest.newBuilder(
URI.create("http://" + token.getString("WebServerHostname") + "/aws_mwaa/cli"))
.header("Authorization", "Bearer " + token.getString("CliToken"))
.header("Content-Type", "text/plain")
.POST(HttpRequest.BodyPublishers.ofString(command))
.timeout(Duration.ofSeconds(60))
.build();
HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
return new CliResult(response.statusCode(), "", response.body());
}
JsonPath body = new JsonPath(response.body());
return new CliResult(response.statusCode(), decode(body.getString("stdout")), decode(body.getString("stderr")));
}
private static String decode(String base64) {
return base64 == null ? "" : new String(Base64.getDecoder().decode(base64), StandardCharsets.UTF_8);
}
}
@@ -1,6 +1,7 @@
package io.floci.aws.services.mwaa;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
@@ -11,6 +12,7 @@ import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.mwaa.model.CreateEnvironmentRequest;
import io.floci.aws.services.mwaa.model.Environment;
import io.floci.aws.services.mwaa.model.EnvironmentRuntime;
import io.floci.aws.services.mwaa.model.EnvironmentStatus;
import io.floci.aws.services.mwaa.model.NetworkConfiguration;
import io.floci.aws.services.mwaa.model.UpdateEnvironmentRequest;
@@ -23,6 +25,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;
import java.lang.reflect.InvocationHandler;
@@ -31,10 +34,15 @@ import java.lang.reflect.Proxy;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -44,6 +52,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -61,6 +71,9 @@ class MwaaServiceTest {
@Override
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
if (!"mwaa-environments.json".equals(fileName)) {
return AccountAwareStorageBackend.inMemory("000000000000");
}
environmentStorage = AccountAwareStorageBackend.<Environment>inMemory("000000000000");
return (AccountAwareStorageBackend<V>) (AccountAwareStorageBackend<?>) environmentStorage;
}
@@ -627,14 +640,26 @@ class MwaaServiceTest {
private S3Service s3Service;
private final List<Runnable> queuedInstalls = new ArrayList<>();
private boolean keepRunningOnShutdown;
private String storageMode = "memory";
private AccountAwareStorageBackend<Environment> environmentStore;
private AccountAwareStorageBackend<EnvironmentRuntime> runtimeStore;
@BeforeEach
@SuppressWarnings("unchecked")
void setUpRealMode() {
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return AccountAwareStorageBackend.inMemory("000000000000");
AccountAwareStorageBackend<V> store = AccountAwareStorageBackend.inMemory("000000000000");
if ("mwaa-environments.json".equals(fileName)) {
// A spy, so a test can tell a write to storage from a change to the instance it holds.
store = Mockito.spy(store);
environmentStore = (AccountAwareStorageBackend<Environment>) store;
} else {
runtimeStore = (AccountAwareStorageBackend<EnvironmentRuntime>) store;
}
return store;
}
};
@@ -658,12 +683,15 @@ class MwaaServiceTest {
});
EmulatorConfig.TlsConfig tlsConfig = proxy(EmulatorConfig.TlsConfig.class,
(proxy, method, args) -> defaultValue(method));
EmulatorConfig.StorageConfig storageConfig = proxy(EmulatorConfig.StorageConfig.class,
(proxy, method, args) -> "mode".equals(method.getName()) ? storageMode : defaultValue(method));
EmulatorConfig config = proxy(EmulatorConfig.class, (proxy, method, args) -> switch (method.getName()) {
case "services" -> servicesConfig;
case "tls" -> tlsConfig;
case "storage" -> storageConfig;
case "defaultRegion" -> "us-east-1";
case "defaultAccountId" -> "000000000000";
case "hostname" -> Optional.empty();
case "hostname" -> Optional.of("floci.test");
default -> defaultValue(method);
});
@@ -673,6 +701,8 @@ class MwaaServiceTest {
proxyManager = Mockito.mock(MwaaProxyManager.class);
portAllocator = Mockito.mock(PortAllocator.class);
when(portAllocator.allocateForInProcessListener(8700, 8799)).thenReturn(8701);
when(s3Service.listObjectsWithPrefixes(any(), any(), any(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
realModeService = new MwaaService(storageFactory, config, regionResolver,
environmentManager, proxyManager, portAllocator, s3Service, queuedInstalls::add, Clock.systemUTC());
@@ -935,5 +965,716 @@ class MwaaServiceTest {
assertEquals(EnvironmentStatus.DELETING, environment.getStatus());
}
@Test
void createKeepsTheSecretsOfTheEnvironmentsDatabaseForARestartAndDeleteDropsThem() {
Mockito.doAnswer(invocation -> {
Environment started = invocation.getArgument(0, Environment.class);
started.setDbPassword("db-pw");
started.setFernetKey("fernet-key");
started.setAirflowAdminPassword("admin-pw");
return null;
}).when(environmentManager).startEnvironment(any(), any(), any(), any());
Environment environment = realModeService.createEnvironment("secret-env",
createRequest("arn:aws:s3:::my-bucket", "dags"));
EnvironmentRuntime runtime = runtimeStore.getForAccount("000000000000", "us-east-1/secret-env")
.orElseThrow();
assertEquals(environment.getCreatedAt(), runtime.getEnvironmentCreatedAt());
assertEquals("db-pw", runtime.getDbPassword());
assertEquals("fernet-key", runtime.getFernetKey());
assertEquals("admin-pw", runtime.getAirflowAdminPassword());
realModeService.deleteEnvironment("secret-env");
assertTrue(runtimeStore.getForAccount("000000000000", "us-east-1/secret-env").isEmpty());
}
@Test
void shutdownKeepsTheVolumesOfEnvironmentsStoredForTheNextStart() {
storageMode = "persistent";
Environment environment = realModeService.createEnvironment("persisted-env",
createRequest("arn:aws:s3:::my-bucket", "dags"));
realModeService.shutdown();
InOrder inOrder = Mockito.inOrder(environmentManager);
inOrder.verify(environmentManager).markShuttingDown();
inOrder.verify(environmentManager).stopContainers(environment);
verify(environmentManager, Mockito.never()).stopEnvironment(any());
verify(proxyManager).stopProxy(realModeService.environmentIdentity(environment));
}
@Test
void shutdownRemovesTheVolumesOfEnvironmentsKeptInMemoryOnly() {
Environment environment = realModeService.createEnvironment("memory-env",
createRequest("arn:aws:s3:::my-bucket", "dags"));
realModeService.shutdown();
verify(environmentManager).stopEnvironment(environment);
verify(environmentManager, Mockito.never()).stopContainers(any());
}
@Test
void shutdownStopsRestoresEvenWhenTheContainersAreKeptRunning() {
keepRunningOnShutdown = true;
storageMode = "persistent";
realModeService.createEnvironment("kept-running-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
realModeService.shutdown();
verify(environmentManager).markShuttingDown();
verify(environmentManager, Mockito.never()).stopContainers(any());
}
@Test
void restoreStartsAnAvailableEnvironmentsContainersAgainWithTheSecretsItKept() {
Environment stored = storedEnvironment("kept-env", EnvironmentStatus.AVAILABLE);
storedSecrets(stored);
Mockito.doAnswer(invocation -> {
Environment environment = invocation.getArgument(0, Environment.class);
assertEquals("saved-db-pw", environment.getDbPassword());
assertEquals("saved-fernet-key", environment.getFernetKey());
return null;
}).when(environmentManager).restartEnvironment(any(), any(), any(), any());
realModeService.restorePersistedRuntime().join();
verify(environmentManager).restartEnvironment(any(), eq("2.10.5"), isNull(), isNull());
verify(environmentManager, Mockito.never()).startEnvironment(any(), any(), any(), any());
verify(environmentManager, Mockito.never()).recoverSecrets(any());
verify(environmentManager, Mockito.never()).giveNewSecrets(any());
verify(portAllocator).markReserved(8705);
ArgumentCaptor<MwaaWebProxy.AirflowAccount> account = ArgumentCaptor.forClass(MwaaWebProxy.AirflowAccount.class);
verify(proxyManager).startProxy(eq("000000000000/us-east-1/kept-env"), eq(8705), any(), anyInt(), any(),
any(), any(), account.capture());
assertEquals(new MwaaWebProxy.AirflowAccount("admin", "saved-admin-pw"), account.getValue());
Environment restored = stored("kept-env");
assertEquals(EnvironmentStatus.MAINTENANCE, restored.getStatus());
assertEquals("http://floci.test:8705", restored.getWebserverUrl());
assertEquals("saved-db-pw", runtimeStore.getForAccount("000000000000", "us-east-1/kept-env")
.orElseThrow().getDbPassword());
}
@Test
void restoreInstallsTheRequirementsInTheNewContainerAsCreateDoesAndTheFirstSyncDoesNotAgain() {
byte[] requirements = "boto3==1.35.0\n".getBytes(StandardCharsets.UTF_8);
when(s3Service.getObject("my-bucket", "requirements.txt"))
.thenReturn(new S3Object("my-bucket", "requirements.txt", requirements, "text/plain"));
when(environmentManager.lastRequirementsInstallExitCode(any())).thenReturn(0);
Environment stored = storedEnvironment("req-restore-env", EnvironmentStatus.AVAILABLE);
stored.setRequirementsS3Path("requirements.txt");
storedSecrets(stored);
realModeService.restorePersistedRuntime().join();
stored.setStatus(EnvironmentStatus.AVAILABLE);
realModeService.syncDags(stored);
verify(environmentManager).restartEnvironment(any(), eq("2.10.5"), isNull(), eq(requirements));
assertTrue(queuedInstalls.isEmpty());
}
@Test
void theFirstSyncAfterARestoreRemovesDagsTheBucketNoLongerHasFromTheVolumeItKept() {
Environment stored = storedEnvironment("pruned-env", EnvironmentStatus.AVAILABLE);
storedSecrets(stored);
byte[] kept = "kept".getBytes(StandardCharsets.UTF_8);
S3Object keptDag = new S3Object("my-bucket", "dags/kept.py", kept, "text/x-python");
when(s3Service.listObjectsWithPrefixes("my-bucket", "dags/", null, 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(List.of(keptDag), List.of(), false, null));
when(s3Service.getObject("my-bucket", "dags/kept.py")).thenReturn(keptDag);
when(environmentManager.listDagFiles(stored)).thenReturn(List.of("kept.py", "deleted.py"));
realModeService.restorePersistedRuntime().join();
stored.setStatus(EnvironmentStatus.AVAILABLE);
realModeService.syncDags(stored);
realModeService.syncDags(stored);
verify(environmentManager).removeDagFile(stored, "deleted.py");
verify(environmentManager).copyDagFile(stored, "kept.py", kept);
verify(environmentManager).listDagFiles(stored);
}
@Test
void aDagPastTheFirstPageOfTheBucketListingIsNotRemoved() {
Environment environment = realModeService.createEnvironment("paged-env",
createRequest("arn:aws:s3:::my-bucket", "dags"));
environment.setStatus(EnvironmentStatus.AVAILABLE);
S3Object first = new S3Object("my-bucket", "dags/a.py", "a".getBytes(StandardCharsets.UTF_8), "text/plain");
S3Object second = new S3Object("my-bucket", "dags/b.py", "b".getBytes(StandardCharsets.UTF_8), "text/plain");
when(s3Service.listObjectsWithPrefixes("my-bucket", "dags/", null, 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(List.of(first), List.of(), true, "dags/a.py"));
when(s3Service.listObjectsWithPrefixes("my-bucket", "dags/", null, 1000, "dags/a.py", null))
.thenReturn(new S3Service.ListObjectsResult(List.of(second), List.of(), false, null));
when(s3Service.getObject("my-bucket", "dags/a.py")).thenReturn(first);
when(s3Service.getObject("my-bucket", "dags/b.py")).thenReturn(second);
when(environmentManager.listDagFiles(environment)).thenReturn(List.of("a.py", "b.py"));
realModeService.syncDags(environment);
verify(environmentManager, Mockito.never()).removeDagFile(any(), any());
verify(environmentManager).copyDagFile(environment, "b.py", second.getData());
}
@Test
void aRestoreForgetsTheDagsSyncedBeforeItSoItsFirstSyncReadsTheVolumeAgain() {
Environment environment = realModeService.createEnvironment("resynced-env",
createRequest("arn:aws:s3:::my-bucket", "dags"));
environment.setStatus(EnvironmentStatus.AVAILABLE);
realModeService.syncDags(environment);
realModeService.restorePersistedRuntime().join();
environment.setStatus(EnvironmentStatus.AVAILABLE);
realModeService.syncDags(environment);
verify(environmentManager, Mockito.times(2)).listDagFiles(environment);
}
@Test
void anEnvironmentIsUnderMaintenanceAndLeftToItsRestoreUntilItsContainersAreBack() throws Exception {
Environment stored = storedEnvironment("maintained-env", EnvironmentStatus.AVAILABLE);
storedSecrets(stored);
CountDownLatch started = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
Mockito.doAnswer(invocation -> {
started.countDown();
assertTrue(release.await(10, TimeUnit.SECONDS));
return null;
}).when(environmentManager).restartEnvironment(any(), any(), any(), any());
CompletableFuture<Void> restore = realModeService.restorePersistedRuntime();
assertEquals(EnvironmentStatus.MAINTENANCE, stored("maintained-env").getStatus());
assertTrue(started.await(10, TimeUnit.SECONDS));
realModeService.checkReadiness(stored);
verify(environmentManager, Mockito.never()).isReady(any());
release.countDown();
restore.get(10, TimeUnit.SECONDS);
when(environmentManager.isReady(stored)).thenReturn(true);
realModeService.checkReadiness(stored);
assertEquals(EnvironmentStatus.AVAILABLE, stored("maintained-env").getStatus());
}
@Test
void checkReadinessMarksARestoredEnvironmentUnavailableWhenAContainerHasExited() {
Environment environment = realModeService.createEnvironment("restored-crash-env",
createRequest("arn:aws:s3:::my-bucket", "dags"));
environment.setStatus(EnvironmentStatus.MAINTENANCE);
when(environmentManager.isReady(environment)).thenReturn(false);
when(environmentManager.hasAnyContainerExited(environment)).thenReturn(true);
realModeService.checkReadiness(environment);
assertEquals(EnvironmentStatus.UNAVAILABLE, environment.getStatus());
}
@Test
void restoreTakesOverContainersThatOutlivedFloci() {
Environment stored = storedEnvironment("survivor-env", EnvironmentStatus.AVAILABLE);
when(environmentManager.adoptRunningEnvironment(any())).thenAnswer(invocation -> {
invocation.getArgument(0, Environment.class).setAirflowAdminPassword("running-admin-pw");
return true;
});
realModeService.restorePersistedRuntime().join();
verify(environmentManager, Mockito.never()).restartEnvironment(any(), any(), any(), any());
verify(environmentManager, Mockito.never()).startEnvironment(any(), any(), any(), any());
Mockito.verifyNoInteractions(s3Service);
verify(proxyManager).startProxy(eq("000000000000/us-east-1/survivor-env"), eq(8705), any(), anyInt(),
any(), any(), any(), eq(new MwaaWebProxy.AirflowAccount("admin", "running-admin-pw")));
assertEquals(EnvironmentStatus.MAINTENANCE, stored.getStatus());
}
@Test
void anEnvironmentStoredBeforeFlociKeptItsSecretsStartsAnewAndKeepsItsNewOnes() {
storedEnvironment("legacy-secrets-env", EnvironmentStatus.AVAILABLE);
Mockito.doAnswer(invocation -> {
Environment started = invocation.getArgument(0, Environment.class);
started.setDbPassword("new-db-pw");
started.setFernetKey("new-fernet-key");
started.setAirflowAdminPassword("new-admin-pw");
return null;
}).when(environmentManager).giveNewSecrets(any());
realModeService.restorePersistedRuntime().join();
InOrder inOrder = Mockito.inOrder(environmentManager);
inOrder.verify(environmentManager).giveNewSecrets(any());
inOrder.verify(environmentManager).restartEnvironment(any(), eq("2.10.5"), isNull(), isNull());
EnvironmentRuntime runtime = runtimeStore.getForAccount("000000000000", "us-east-1/legacy-secrets-env")
.orElseThrow();
assertEquals("new-db-pw", runtime.getDbPassword());
assertEquals("new-fernet-key", runtime.getFernetKey());
}
@Test
void anEnvironmentStoredBeforeFlociKeptItsSecretsGetsThemBackFromAContainerLeftUnderItsName() {
storedEnvironment("recovered-env", EnvironmentStatus.AVAILABLE);
when(environmentManager.recoverSecrets(any())).thenAnswer(invocation -> {
Environment environment = invocation.getArgument(0, Environment.class);
environment.setDbPassword("left-db-pw");
environment.setFernetKey("left-fernet-key");
environment.setAirflowAdminPassword("left-admin-pw");
return true;
});
realModeService.restorePersistedRuntime().join();
verify(environmentManager).restartEnvironment(any(), eq("2.10.5"), isNull(), isNull());
verify(environmentManager, Mockito.never()).giveNewSecrets(any());
assertEquals("left-fernet-key", runtimeStore.getForAccount("000000000000", "us-east-1/recovered-env")
.orElseThrow().getFernetKey());
}
@Test
void aDockerThatCannotSayWhatIsLeftLeavesTheEnvironmentUnavailableWithNothingRemoved() {
Environment stored = storedEnvironment("unanswered-env", EnvironmentStatus.AVAILABLE);
when(environmentManager.adoptRunningEnvironment(any()))
.thenThrow(new IllegalStateException("daemon unreachable"));
assertThrows(CompletionException.class, () -> realModeService.restorePersistedRuntime().join());
assertEquals(EnvironmentStatus.UNAVAILABLE, stored("unanswered-env").getStatus());
verify(environmentManager, Mockito.never()).giveNewSecrets(any());
verify(environmentManager, Mockito.never()).restartEnvironment(any(), any(), any(), any());
verify(environmentManager, Mockito.never()).startEnvironment(any(), any(), any(), any());
verify(environmentManager, Mockito.never()).stopEnvironment(any());
}
@Test
void secretsFoundOrGivenAreKeptBeforeTheStartSoAStartThatFailsIsTriedAgainWithThem() {
storedEnvironment("retried-with-new-env", EnvironmentStatus.AVAILABLE);
Mockito.doAnswer(invocation -> {
Environment environment = invocation.getArgument(0, Environment.class);
environment.setDbPassword("new-db-pw");
environment.setFernetKey("new-fernet-key");
environment.setAirflowAdminPassword("new-admin-pw");
return null;
}).when(environmentManager).giveNewSecrets(any());
Mockito.doThrow(new IllegalStateException("Postgres did not start"))
.when(environmentManager).restartEnvironment(any(), any(), any(), any());
assertThrows(CompletionException.class, () -> realModeService.restorePersistedRuntime().join());
assertEquals(EnvironmentStatus.UNAVAILABLE, stored("retried-with-new-env").getStatus());
assertEquals("new-db-pw", runtimeStore.getForAccount("000000000000", "us-east-1/retried-with-new-env")
.orElseThrow().getDbPassword());
}
@Test
void secretsFoundForAnEnvironmentWhoseRecordWentMeanwhileAreNotKept() {
storedEnvironment("went-while-recovering-env", EnvironmentStatus.AVAILABLE);
when(environmentManager.recoverSecrets(any())).thenAnswer(invocation -> {
environmentStore.deleteForAccount("000000000000", "us-east-1/went-while-recovering-env");
invocation.getArgument(0, Environment.class).setDbPassword("left-db-pw");
return true;
});
realModeService.restorePersistedRuntime().join();
assertTrue(runtimeStore.getForAccount("000000000000", "us-east-1/went-while-recovering-env").isEmpty());
}
@Test
void theSecretsOfContainersTakenOverAreKeptEvenWhenTheRestoreThenFails() {
storedEnvironment("taken-over-env", EnvironmentStatus.AVAILABLE);
when(environmentManager.adoptRunningEnvironment(any())).thenAnswer(invocation -> {
Environment environment = invocation.getArgument(0, Environment.class);
environment.setDbPassword("running-db-pw");
environment.setFernetKey("running-fernet-key");
environment.setAirflowAdminPassword("running-admin-pw");
return true;
});
Mockito.doThrow(new RuntimeException("Address already in use"))
.when(proxyManager).startProxy(any(), anyInt(), any(), anyInt(), any(), any(), any(), any());
assertThrows(CompletionException.class, () -> realModeService.restorePersistedRuntime().join());
assertEquals(EnvironmentStatus.UNAVAILABLE, stored("taken-over-env").getStatus());
assertEquals("running-fernet-key", runtimeStore.getForAccount("000000000000", "us-east-1/taken-over-env")
.orElseThrow().getFernetKey());
}
@Test
void anEnvironmentGoneBeforeItsRestoreIsLeftAloneAndOneCreatedAfterIsTreatedAsAnyOther() throws Exception {
storedSecrets(storedEnvironment("gone-early-env", EnvironmentStatus.AVAILABLE));
CountDownLatch reached = new CountDownLatch(1);
CountDownLatch proceed = new CountDownLatch(1);
when(environmentManager.isShuttingDown()).thenAnswer(invocation -> {
reached.countDown();
assertTrue(proceed.await(10, TimeUnit.SECONDS));
return false;
});
CompletableFuture<Void> restore = realModeService.restorePersistedRuntime();
assertTrue(reached.await(10, TimeUnit.SECONDS));
environmentStore.deleteForAccount("000000000000", "us-east-1/gone-early-env");
proceed.countDown();
restore.get(10, TimeUnit.SECONDS);
verify(environmentManager, Mockito.never()).adoptRunningEnvironment(any());
verify(environmentManager, Mockito.never()).restartEnvironment(any(), any(), any(), any());
verify(portAllocator).release(8705);
Environment recreated = storedEnvironment("gone-early-env", EnvironmentStatus.CREATING);
recreated.setCreatedAt(Instant.parse("2026-11-20T00:00:00Z"));
realModeService.checkReadiness(recreated);
verify(environmentManager).isReady(recreated);
}
@Test
void anEnvironmentDeletedDuringARestoreThatFailsIsRemoved() throws Exception {
Environment stored = storedEnvironment("deleted-failing-env", EnvironmentStatus.AVAILABLE);
storedSecrets(stored);
CountDownLatch started = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
Mockito.doAnswer(invocation -> {
started.countDown();
assertTrue(release.await(10, TimeUnit.SECONDS));
throw new IllegalStateException("Airflow did not start");
}).when(environmentManager).restartEnvironment(any(), any(), any(), any());
CompletableFuture<Void> restore = realModeService.restorePersistedRuntime();
assertTrue(started.await(10, TimeUnit.SECONDS));
realModeService.deleteEnvironment("deleted-failing-env");
release.countDown();
assertThrows(CompletionException.class, restore::join);
verify(environmentManager).stopEnvironment(stored);
assertTrue(environmentStore.getForAccount("000000000000", "us-east-1/deleted-failing-env").isEmpty());
assertTrue(runtimeStore.getForAccount("000000000000", "us-east-1/deleted-failing-env").isEmpty());
}
@Test
void theSecretsOfAnEarlierEnvironmentOfTheSameNameAreNotUsed() {
Environment stored = storedEnvironment("renewed-env", EnvironmentStatus.AVAILABLE);
storedSecrets(stored);
runtimeStore.getForAccount("000000000000", "us-east-1/renewed-env").orElseThrow()
.setEnvironmentCreatedAt(Instant.parse("2026-10-01T00:00:00Z"));
realModeService.restorePersistedRuntime().join();
verify(environmentManager).recoverSecrets(any());
verify(environmentManager).giveNewSecrets(any());
}
@Test
void anEnvironmentStoredUnderALegacyKeyIsRestoredUnderItsKey() {
Environment legacy = storedEnvironment("legacy-key-env", EnvironmentStatus.AVAILABLE);
environmentStore.deleteForAccount("000000000000", "us-east-1/legacy-key-env");
environmentStore.putForAccount("000000000000", "legacy-key-env", legacy);
realModeService.restorePersistedRuntime().join();
assertEquals(EnvironmentStatus.MAINTENANCE, stored("legacy-key-env").getStatus());
assertTrue(environmentStore.getForAccount("000000000000", "legacy-key-env").isEmpty());
verify(environmentManager).giveNewSecrets(any());
}
@Test
void anEnvironmentWhoseContainersDoNotStartIsUnavailableAndKeepsItsVolumes() {
Environment stored = storedEnvironment("unstartable-env", EnvironmentStatus.AVAILABLE);
storedSecrets(stored);
Mockito.doThrow(new IllegalStateException("Postgres did not start"))
.when(environmentManager).restartEnvironment(any(), any(), any(), any());
CompletionException failure = assertThrows(CompletionException.class,
() -> realModeService.restorePersistedRuntime().join());
assertTrue(failure.getCause().getMessage().contains("unstartable-env"), failure.getCause().getMessage());
assertEquals(EnvironmentStatus.UNAVAILABLE, stored("unstartable-env").getStatus());
verify(environmentManager).stopOwnContainers(stored);
verify(environmentManager, Mockito.never()).stopEnvironment(any());
verify(proxyManager, Mockito.never()).startProxy(any(), anyInt(), any(), anyInt(), any(), any(), any(),
any());
}
@Test
void everyEnvironmentIsTriedAndTheFailuresAreReportedTogether() {
storedSecrets(storedEnvironment("first-failing-env", EnvironmentStatus.AVAILABLE));
storedSecrets(storedEnvironment("second-failing-env", EnvironmentStatus.AVAILABLE));
Mockito.doThrow(new IllegalStateException("no Docker"))
.when(environmentManager).restartEnvironment(any(), any(), any(), any());
CompletionException failure = assertThrows(CompletionException.class,
() -> realModeService.restorePersistedRuntime().join());
verify(environmentManager, Mockito.times(2)).restartEnvironment(any(), any(), any(), any());
assertEquals(1, failure.getCause().getSuppressed().length);
}
@Test
void anUnavailableEnvironmentIsTriedAgain() {
storedSecrets(storedEnvironment("retried-env", EnvironmentStatus.UNAVAILABLE));
realModeService.restorePersistedRuntime().join();
verify(environmentManager).restartEnvironment(any(), any(), any(), any());
assertEquals(EnvironmentStatus.MAINTENANCE, stored("retried-env").getStatus());
}
@Test
void anEnvironmentStillBeingCreatedStaysCreatingAndFailsAsACreate() {
storedSecrets(storedEnvironment("creating-env", EnvironmentStatus.CREATING));
CountDownLatch started = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
Mockito.doAnswer(invocation -> {
started.countDown();
assertTrue(release.await(10, TimeUnit.SECONDS));
throw new IllegalStateException("Airflow did not start");
}).when(environmentManager).restartEnvironment(any(), any(), any(), any());
CompletableFuture<Void> restore = realModeService.restorePersistedRuntime();
assertEquals(EnvironmentStatus.CREATING, stored("creating-env").getStatus());
release.countDown();
assertThrows(CompletionException.class, restore::join);
assertEquals(EnvironmentStatus.CREATE_FAILED, stored("creating-env").getStatus());
}
@Test
void anEnvironmentThatFailedToCreateIsLeftAsItIs() {
storedSecrets(storedEnvironment("create-failed-env", EnvironmentStatus.CREATE_FAILED));
realModeService.restorePersistedRuntime().join();
verify(environmentManager, Mockito.never()).adoptRunningEnvironment(any());
verify(environmentManager, Mockito.never()).restartEnvironment(any(), any(), any(), any());
verify(portAllocator, Mockito.never()).markReserved(anyInt());
assertEquals(EnvironmentStatus.CREATE_FAILED, stored("create-failed-env").getStatus());
}
@Test
void anEnvironmentStillDeletingAtStartIsRemoved() {
Environment stored = storedEnvironment("still-deleting-env", EnvironmentStatus.DELETING);
storedSecrets(stored);
realModeService.restorePersistedRuntime().join();
verify(environmentManager).stopEnvironment(stored);
verify(environmentManager, Mockito.never()).adoptRunningEnvironment(any());
verify(environmentManager, Mockito.never()).restartEnvironment(any(), any(), any(), any());
assertTrue(environmentStore.getForAccount("000000000000", "us-east-1/still-deleting-env").isEmpty());
assertTrue(runtimeStore.getForAccount("000000000000", "us-east-1/still-deleting-env").isEmpty());
}
@Test
void anEnvironmentDeletedDuringItsRestoreIsDeletingUntilItsContainersHaveStartedAndBeenRemoved()
throws Exception {
Environment stored = storedEnvironment("deleted-mid-restore-env", EnvironmentStatus.AVAILABLE);
storedSecrets(stored);
CountDownLatch started = new CountDownLatch(1);
CountDownLatch release = blockRestart(started);
CompletableFuture<Void> restore = realModeService.restorePersistedRuntime();
assertTrue(started.await(10, TimeUnit.SECONDS));
long writesBefore = writesOf("deleted-mid-restore-env");
Environment deleting = realModeService.deleteEnvironment("deleted-mid-restore-env");
assertEquals(writesBefore + 1, writesOf("deleted-mid-restore-env"));
assertEquals(EnvironmentStatus.DELETING, deleting.getStatus());
assertEquals(EnvironmentStatus.DELETING, stored("deleted-mid-restore-env").getStatus());
verify(environmentManager, Mockito.never()).stopEnvironment(any());
release.countDown();
restore.get(10, TimeUnit.SECONDS);
verify(environmentManager).stopEnvironment(stored);
verify(proxyManager, Mockito.never()).startProxy(any(), anyInt(), any(), anyInt(), any(), any(), any(),
any());
assertTrue(environmentStore.getForAccount("000000000000", "us-east-1/deleted-mid-restore-env").isEmpty());
assertTrue(runtimeStore.getForAccount("000000000000", "us-east-1/deleted-mid-restore-env").isEmpty());
}
@Test
void aDeleteBeforeTheRestoreReachesTheEnvironmentIsFinishedWithoutStartingIt() throws Exception {
Environment stored = storedEnvironment("deleted-early-env", EnvironmentStatus.AVAILABLE);
storedSecrets(stored);
CountDownLatch reached = new CountDownLatch(1);
CountDownLatch proceed = new CountDownLatch(1);
when(environmentManager.isShuttingDown()).thenAnswer(invocation -> {
reached.countDown();
assertTrue(proceed.await(10, TimeUnit.SECONDS));
return false;
});
CompletableFuture<Void> restore = realModeService.restorePersistedRuntime();
assertTrue(reached.await(10, TimeUnit.SECONDS));
realModeService.deleteEnvironment("deleted-early-env");
proceed.countDown();
restore.get(10, TimeUnit.SECONDS);
verify(environmentManager, Mockito.never()).adoptRunningEnvironment(any());
verify(environmentManager, Mockito.never()).restartEnvironment(any(), any(), any(), any());
verify(environmentManager).stopEnvironment(stored);
assertTrue(environmentStore.getForAccount("000000000000", "us-east-1/deleted-early-env").isEmpty());
}
@Test
void aDeleteAfterTheRestoreRemovesTheEnvironmentAtOnce() {
storedSecrets(storedEnvironment("deleted-after-restore-env", EnvironmentStatus.AVAILABLE));
realModeService.restorePersistedRuntime().join();
realModeService.deleteEnvironment("deleted-after-restore-env");
verify(environmentManager).stopEnvironment(any());
assertTrue(environmentStore.getForAccount("000000000000", "us-east-1/deleted-after-restore-env")
.isEmpty());
}
@Test
void anEnvironmentWhoseRecordWentDuringItsRestoreIsNotBroughtBack() throws Exception {
Environment stored = storedEnvironment("wiped-env", EnvironmentStatus.AVAILABLE);
storedSecrets(stored);
CountDownLatch started = new CountDownLatch(1);
CountDownLatch release = blockRestart(started);
CompletableFuture<Void> restore = realModeService.restorePersistedRuntime();
assertTrue(started.await(10, TimeUnit.SECONDS));
environmentStore.deleteForAccount("000000000000", "us-east-1/wiped-env");
release.countDown();
restore.get(10, TimeUnit.SECONDS);
assertTrue(environmentStore.getForAccount("000000000000", "us-east-1/wiped-env").isEmpty());
verify(environmentManager).stopOwnContainers(stored);
verify(environmentManager, Mockito.never()).stopEnvironment(any());
verify(portAllocator).release(8705);
verify(proxyManager, Mockito.never()).startProxy(any(), anyInt(), any(), anyInt(), any(), any(), any(),
any());
}
@Test
void anEnvironmentCreatedAgainDuringTheRestoreKeepsItsOwnRecord() throws Exception {
Environment stored = storedEnvironment("renamed-env", EnvironmentStatus.AVAILABLE);
storedSecrets(stored);
CountDownLatch started = new CountDownLatch(1);
CountDownLatch release = blockRestart(started);
CompletableFuture<Void> restore = realModeService.restorePersistedRuntime();
assertTrue(started.await(10, TimeUnit.SECONDS));
Environment recreated = storedEnvironment("renamed-env", EnvironmentStatus.CREATING);
recreated.setCreatedAt(Instant.parse("2026-11-20T00:00:00Z"));
release.countDown();
restore.get(10, TimeUnit.SECONDS);
assertEquals(EnvironmentStatus.CREATING, stored("renamed-env").getStatus());
assertEquals(Instant.parse("2026-11-20T00:00:00Z"), stored("renamed-env").getCreatedAt());
verify(environmentManager).stopOwnContainers(stored);
verify(environmentManager, Mockito.never()).stopEnvironment(any());
}
@Test
void aShutdownDuringTheRestoreLeavesTheRemainingEnvironmentsForTheNextStart() {
storedSecrets(storedEnvironment("overtaken-env", EnvironmentStatus.AVAILABLE));
storedSecrets(storedEnvironment("not-reached-env", EnvironmentStatus.AVAILABLE));
when(environmentManager.isShuttingDown()).thenReturn(false, true);
Mockito.doThrow(new MwaaEnvironmentManager.ShuttingDownException("Floci is shutting down"))
.when(environmentManager).restartEnvironment(any(), any(), any(), any());
realModeService.restorePersistedRuntime().join();
verify(environmentManager).restartEnvironment(any(), any(), any(), any());
assertEquals(EnvironmentStatus.MAINTENANCE, stored("overtaken-env").getStatus());
assertEquals(EnvironmentStatus.MAINTENANCE, stored("not-reached-env").getStatus());
verify(environmentManager, Mockito.never()).stopOwnContainers(any());
}
@Test
void aRestoredEnvironmentWhosePortIsTakenGetsANewWebserverUrl() {
storedSecrets(storedEnvironment("moved-env", EnvironmentStatus.AVAILABLE));
Mockito.doThrow(new RuntimeException("Address already in use"))
.when(proxyManager).startProxy(any(), eq(8705), any(), anyInt(), any(), any(), any(), any());
realModeService.restorePersistedRuntime().join();
verify(portAllocator).release(8705);
verify(proxyManager).startProxy(any(), eq(8701), any(), anyInt(), any(), any(), any(), any());
assertEquals("http://floci.test:8701", stored("moved-env").getWebserverUrl());
}
@Test
void aRestoredEnvironmentWithNoProxyIsUnavailable() {
Environment stored = storedEnvironment("no-proxy-env", EnvironmentStatus.AVAILABLE);
storedSecrets(stored);
Mockito.doThrow(new RuntimeException("Address already in use"))
.when(proxyManager).startProxy(any(), anyInt(), any(), anyInt(), any(), any(), any(), any());
assertThrows(CompletionException.class, () -> realModeService.restorePersistedRuntime().join());
verify(portAllocator).release(8701);
assertEquals(EnvironmentStatus.UNAVAILABLE, stored("no-proxy-env").getStatus());
verify(environmentManager).stopOwnContainers(stored);
}
/** Holds the restore's restart, once it has begun, until the returned latch is released. */
private CountDownLatch blockRestart(CountDownLatch started) {
CountDownLatch release = new CountDownLatch(1);
Mockito.doAnswer(invocation -> {
started.countDown();
assertTrue(release.await(10, TimeUnit.SECONDS));
return null;
}).when(environmentManager).restartEnvironment(any(), any(), any(), any());
return release;
}
/** An environment as Floci reads it back after a restart: what storage keeps, none of what it holds in memory. */
private Environment storedEnvironment(String name, EnvironmentStatus status) {
Environment environment = new Environment();
environment.setName(name);
environment.setArn("arn:aws:airflow:us-east-1:000000000000:environment/" + name);
environment.setCreatedAt(Instant.parse("2026-11-01T00:00:00Z"));
environment.setStatus(status);
environment.setAirflowVersion("2.10.5");
environment.setSourceBucketArn("arn:aws:s3:::my-bucket");
environment.setDagS3Path("dags");
environment.setWebserverUrl("http://floci.test:8705");
environmentStore.putForAccount("000000000000", "us-east-1/" + name, environment);
return environment;
}
private void storedSecrets(Environment environment) {
EnvironmentRuntime runtime = new EnvironmentRuntime();
runtime.setEnvironmentCreatedAt(environment.getCreatedAt());
runtime.setDbPassword("saved-db-pw");
runtime.setFernetKey("saved-fernet-key");
runtime.setAirflowAdminPassword("saved-admin-pw");
runtimeStore.putForAccount("000000000000", "us-east-1/" + environment.getName(), runtime);
}
/** How many times the environment's record has been written to storage. */
private long writesOf(String name) {
return Mockito.mockingDetails(environmentStore).getInvocations().stream()
.filter(invocation -> "putForAccount".equals(invocation.getMethod().getName())
&& ("us-east-1/" + name).equals(invocation.getArgument(1)))
.count();
}
private Environment stored(String name) {
return environmentStore.getForAccount("000000000000", "us-east-1/" + name).orElseThrow();
}
}
@Test
void restoreLeavesMockEnvironmentsAlone() {
mwaaService.createEnvironment("mock-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
assertTrue(mwaaService.restorePersistedRuntime().isDone());
assertEquals(EnvironmentStatus.AVAILABLE, mwaaService.getEnvironment("mock-env").getStatus());
}
@Test
void theSecretsAnEnvironmentRunsWithAreNeverInTheEnvironmentAsReturned() throws Exception {
Environment environment = new Environment();
environment.setName("secret-env");
environment.setDbPassword("db-secret");
environment.setFernetKey("fernet-secret");
environment.setAirflowAdminPassword("admin-secret");
String json = new ObjectMapper().writeValueAsString(environment);
assertFalse(json.contains("db-secret"), json);
assertFalse(json.contains("fernet-secret"), json);
assertFalse(json.contains("admin-secret"), json);
}
}