diff --git a/docs/services/mwaa.md b/docs/services/mwaa.md index 34171fa5e8..9d6a58461d 100644 --- a/docs/services/mwaa.md +++ b/docs/services/mwaa.md @@ -38,7 +38,7 @@ Floci starts two containers per environment: Legacy environments retain the region recorded in their ARN. A request in another region does not adopt that environment; recreate it in the requested region instead. -Once Airflow's unauthenticated `/health` endpoint reports both `metadatabase` and `scheduler` as `"healthy"`, the environment transitions to `AVAILABLE`. If the Postgres or Airflow container instead exits before that (a startup script or `airflow db migrate` failing partway through, or Postgres itself dying), the same poller detects the stopped container and transitions the environment to `CREATE_FAILED` rather than polling dead containers forever. +Once Airflow's unauthenticated `/health` endpoint reports `metadatabase`, `scheduler` and `triggerer` as `"healthy"`, the environment transitions to `AVAILABLE`. If the Postgres or Airflow container instead exits before that (a startup script or `airflow db migrate` failing partway through, or Postgres itself dying), the same poller detects the stopped container and transitions the environment to `CREATE_FAILED` rather than polling dead containers forever. ### Web/CLI proxy @@ -46,7 +46,7 @@ Floci runs its own HTTP proxy per environment (published on a host port from the ### Startup scripts (`StartupScriptS3Path`) -If configured, the script is fetched from S3 at environment-creation time and injected into the Airflow container before it starts (before `airflow db migrate`/scheduler/webserver), matching real MWAA's ordering. Two behaviors worth knowing about since they're not obvious from the API surface: +If configured, the script is fetched from S3 at environment-creation time and injected into the Airflow container before it starts. It runs first, then `requirements.txt` is installed, then `airflow db migrate` and the triggerer, scheduler and webserver start, matching real MWAA's ordering. Variables the script exports (a private index URL for `pip`, for example) are still set when `requirements.txt` installs, at creation and on every later reinstall. Two behaviors worth knowing about since they're not obvious from the API surface: - The `airflow` OS user is granted passwordless `sudo` inside the container specifically so scripts using `sudo apt-get ...`-style commands (the pattern shown in AWS's own startup-script documentation) work — the stock `apache/airflow` image ships `sudo` but requires a password by default, so without this grant any `sudo` line would hang. - A fixed set of Floci-managed environment variables (the Fernet key, the database connection string, the executor setting, and the AWS-SDK-redirection variables described below) are snapshotted before the script runs and restored immediately after, so a script that touches one of these — intentionally or not — can't break the environment. This mirrors real MWAA's "reserved environment variables" behavior. @@ -86,11 +86,11 @@ services: | `FLOCI_SERVICES_MWAA_DOCKER_NETWORK` | *(unset)* | Docker network for the Postgres/Airflow containers (falls back to the global `FLOCI_SERVICES_DOCKER_NETWORK`, then Floci's own network) | | `FLOCI_SERVICES_MWAA_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave Postgres/Airflow containers running after Floci stops | | `FLOCI_SERVICES_MWAA_DAG_SYNC_INTERVAL_SECONDS` | `30` | How often to poll S3 for DAG and `requirements.txt` changes | -| `FLOCI_SERVICES_MWAA_INSTALL_REQUIREMENTS` | `true` | Install `RequirementsS3Path` (via `pip install -r`) when it changes | +| `FLOCI_SERVICES_MWAA_INSTALL_REQUIREMENTS` | `true` | Install `RequirementsS3Path` (via `pip install -r`) before Airflow starts, and again when it changes | ## DAG and requirements sync -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 and `pip install -r`'d the same way whenever its content changes. A broken DAG file or a failing `pip install` is logged but never fails the environment, matching real MWAA behavior. +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. ## ARN Format @@ -186,7 +186,6 @@ The following are current, known gaps: - `PluginsS3Path` is accepted and stored on the environment but not fetched or applied — real MWAA's `plugins.zip` mechanism for shipping custom binaries has no equivalent here yet. - `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. - `CreateWebLoginToken` returns a stubbed token rather than performing a real Airflow FAB/JWT SSO handshake. -- No per-component `MWAA_AIRFLOW_COMPONENT` environment variable — real MWAA runs the startup script separately on webserver, scheduler, and worker; Floci runs webserver and scheduler together in one container, so there's no per-component distinction to expose. -- No `triggerer` process — DAGs using deferrable operators will log warnings, since only the scheduler and webserver run. +- 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. diff --git a/src/main/java/io/floci/aws/services/mwaa/MwaaEnvironmentManager.java b/src/main/java/io/floci/aws/services/mwaa/MwaaEnvironmentManager.java index da25d5ddf1..0f5561122a 100644 --- a/src/main/java/io/floci/aws/services/mwaa/MwaaEnvironmentManager.java +++ b/src/main/java/io/floci/aws/services/mwaa/MwaaEnvironmentManager.java @@ -61,6 +61,15 @@ public class MwaaEnvironmentManager { /** The OS user the stock apache/airflow image runs its process as (uid 50000) — distinct from * the Airflow web-UI admin login username configured via {@code _AIRFLOW_WWW_USER_USERNAME}. */ private static final String CONTAINER_OS_USER = "airflow"; + private static final String REQUIREMENTS_DIR = "/tmp"; + private static final String REQUIREMENTS_FILE = "mwaa-requirements.txt"; + private static final String REQUIREMENTS_PATH = REQUIREMENTS_DIR + "/" + REQUIREMENTS_FILE; + private static final String INSTALL_SCRIPT_FILE = "mwaa-install-requirements.sh"; + private static final String INSTALL_SCRIPT_PATH = REQUIREMENTS_DIR + "/" + INSTALL_SCRIPT_FILE; + private static final String INSTALL_EXIT_CODE_PATH = REQUIREMENTS_DIR + "/mwaa-requirements.exit"; + private static final String STARTUP_ENV_PATH = REQUIREMENTS_DIR + "/mwaa-startup.env"; + /** A first {@code pip install} of a real requirements file can take minutes. */ + private static final int REQUIREMENTS_INSTALL_TIMEOUT_SECONDS = 900; private static final Set MWAA_CLI_COMMANDS = Set.of("cheat-sheet", "version"); private static final Map> MWAA_CLI_SUBCOMMANDS = Map.of( "connections", Set.of("add", "delete"), @@ -103,8 +112,11 @@ public class MwaaEnvironmentManager { * @param startupScriptContent the {@code StartupScriptS3Path} object's bytes (already fetched * from S3 by the caller), or {@code null}/empty if the environment * has none configured + * @param requirementsContent the {@code RequirementsS3Path} object's bytes, installed after the + * startup script and before Airflow starts, or {@code null}/empty */ - public void startEnvironment(Environment environment, String airflowVersion, byte[] startupScriptContent) { + public void startEnvironment(Environment environment, String airflowVersion, byte[] startupScriptContent, + byte[] requirementsContent) { String name = environment.getName(); String dbPassword = generateSecret(24); environment.setDbPassword(dbPassword); @@ -137,14 +149,15 @@ public class MwaaEnvironmentManager { LOG.infov("MWAA Postgres container {0} ready for environment {1} at {2}:{3}", dbContainerId, name, dbIp, String.valueOf(POSTGRES_PORT)); - startAirflowContainer(environment, airflowVersion, dbIp, dbPassword, startupScriptContent); + startAirflowContainer(environment, airflowVersion, dbIp, dbPassword, startupScriptContent, + requirementsContent); } // Package-private (not private) so MwaaEnvironmentManagerTest can exercise container-spec // construction directly with a mocked ContainerLifecycleManager, without needing to also mock // the exec-based Postgres readiness wait that startEnvironment() performs first. void startAirflowContainer(Environment environment, String airflowVersion, String dbIp, String dbPassword, - byte[] startupScriptContent) { + byte[] startupScriptContent, byte[] requirementsContent) { String name = environment.getName(); String airflowContainerName = airflowContainerName(config, environment); String dagsVolume = airflowContainerName + "-dags"; @@ -180,8 +193,8 @@ public class MwaaEnvironmentManager { // Overrides the stock apache/airflow entrypoint, which is designed to run a single // role per container. This runs migrations, the admin bootstrap (using the stock // _AIRFLOW_WWW_USER_* var names, since the stock entrypoint's own auto-creation - // logic is bypassed along with the rest of it), then backgrounds the scheduler and - // execs the webserver as PID 1 so container signals reach it directly. + // logic is bypassed along with the rest of it), then backgrounds the triggerer and the + // scheduler and execs the webserver as PID 1 so container signals reach it directly. .withEntrypoint(List.of("sh", "-c")) .withCmd(List.of(airflowBootstrapScript())) .withNamedVolume(dagsVolume, DAGS_MOUNT) @@ -198,8 +211,8 @@ public class MwaaEnvironmentManager { } ContainerSpec spec = specBuilder.build(); - // create -> inject startup.sh (if configured) + the sudoers grant -> start, so both exist - // before the entrypoint runs — same sequencing EksClusterManager uses to inject + // create -> inject startup.sh and requirements.txt (if configured) + the sudoers grant -> start, + // so they exist before the entrypoint runs: the same sequencing EksClusterManager uses to inject // registries.yaml/the webhook kubeconfig before the k3s container's entrypoint boots. String containerId = lifecycleManager.create(spec); ContainerInfo info; @@ -227,6 +240,12 @@ public class MwaaEnvironmentManager { + containerId + " for environment " + environment.getName()); } } + if (requirementsContent != null && requirementsContent.length > 0 + && !copyRequirementsIntoContainer(containerId, requirementsContent)) { + throw new IllegalStateException( + "Could not inject the configured requirements.txt into MWAA container " + + containerId + " for environment " + environment.getName()); + } info = lifecycleManager.startCreated(containerId, spec); } catch (Exception e) { lifecycleManager.removeIfExists(containerId); @@ -249,8 +268,8 @@ public class MwaaEnvironmentManager { } /** - * Polls the Airflow container's unauthenticated {@code /health} endpoint and requires both - * {@code metadatabase.status} and {@code scheduler.status} to be {@code "healthy"}. + * Polls the Airflow container's unauthenticated {@code /health} endpoint until + * {@link #isHealthy} accepts it. */ public boolean isReady(Environment environment) { String host = environment.getAirflowInternalHost(); @@ -270,13 +289,22 @@ public class MwaaEnvironmentManager { try (InputStream in = conn.getInputStream()) { body = new String(in.readAllBytes(), StandardCharsets.UTF_8); } - return body.contains("\"metadatabase\"") && body.contains("\"scheduler\"") - && healthySection(body, "metadatabase") && healthySection(body, "scheduler"); + return isHealthy(body); } catch (Exception e) { return false; } } + /** + * Requires {@code metadatabase}, {@code scheduler} and {@code triggerer} to report + * {@code "healthy"}, so an environment is never AVAILABLE without the triggerer its deferrable + * tasks need. + */ + static boolean isHealthy(String body) { + return healthySection(body, "metadatabase") && healthySection(body, "scheduler") + && healthySection(body, "triggerer"); + } + /** * True when either container backing this environment, Postgres or Airflow, was created but is * no longer running: for example a startup script or {@code airflow db migrate} failing @@ -360,16 +388,20 @@ public class MwaaEnvironmentManager { } } - /** Writes requirements.txt into the container and runs {@code pip install -r} against it. */ + /** + * Writes requirements.txt into the running container and installs it with + * {@link #requirementsInstallScript}, for a requirements file whose content changed after the + * environment started. The script's own time limit stops pip before this exec gives up waiting, + * so a timed-out install never keeps running beside the next one. + */ public void installRequirements(Environment environment, byte[] requirementsContent) { String containerId = environment.getAirflowContainerId(); - if (containerId == null) { + if (containerId == null || !copyRequirementsIntoContainer(containerId, requirementsContent)) { return; } - copyFileIntoContainer(containerId, "/tmp", "mwaa-requirements.txt", requirementsContent); try { - ContainerExec.Result result = execInContainer(containerId, - new String[]{"pip", "install", "--no-cache-dir", "-r", "/tmp/mwaa-requirements.txt"}); + ContainerExec.Result result = execInContainer(containerId, new String[]{"sh", INSTALL_SCRIPT_PATH}, + REQUIREMENTS_INSTALL_TIMEOUT_SECONDS + 60); if (result.exitCode() != 0) { LOG.warnv("pip install -r requirements.txt exited {0} for environment {1}: {2}", String.valueOf(result.exitCode()), environment.getName(), result.stderr()); @@ -637,17 +669,68 @@ public class MwaaEnvironmentManager { .map(v -> "export " + v + "=\"$_FLOCI_ORIG_" + v + "\"") .collect(Collectors.joining("\n", "", "\n")); + // Same order as real MWAA: the startup script, then requirements.txt, then Airflow. The + // exported environment is saved for the DAG-sync reinstall. A failing install is logged and + // Airflow still starts; the first DAG-sync pass reads its exit code and installs again. + // The triggerer is restarted if it exits, since nothing else would bring it back. return snapshot + "if [ -f /startup.sh ]; then . /startup.sh || exit 1; fi\n" + restore + + "(umask 077; export -p > " + STARTUP_ENV_PATH + ")\n" + + "if [ -f " + REQUIREMENTS_PATH + " ]; then sh " + INSTALL_SCRIPT_PATH + + " || echo 'pip install -r requirements.txt failed' >&2; fi\n" + "airflow db migrate && " + "(airflow users create --username \"$_AIRFLOW_WWW_USER_USERNAME\" " + "--password \"$_AIRFLOW_WWW_USER_PASSWORD\" --firstname Admin --lastname User " + "--role Admin --email admin@example.com || true); " + + "(while true; do airflow triggerer; echo 'airflow triggerer exited; restarting it' >&2; " + + "sleep 5; done) & " + "airflow scheduler & " + "exec airflow webserver"; } + /** + * The exit code {@link #requirementsInstallScript} recorded for the container's last install, or + * {@code null} when there is none to read. + */ + public Integer lastRequirementsInstallExitCode(Environment environment) { + String containerId = environment.getAirflowContainerId(); + if (containerId == null) { + return null; + } + try { + ContainerExec.Result result = execInContainer(containerId, new String[]{"cat", INSTALL_EXIT_CODE_PATH}); + return result.exitCode() == 0 ? Integer.valueOf(result.stdout().trim()) : null; + } catch (Exception e) { + LOG.warnv("Could not read the requirements.txt install result for environment {0}: {1}", + environment.getName(), e.getMessage()); + return null; + } + } + + private boolean copyRequirementsIntoContainer(String containerId, byte[] requirementsContent) { + return copyFileIntoContainer(containerId, REQUIREMENTS_DIR, REQUIREMENTS_FILE, requirementsContent) + && copyFileIntoContainer(containerId, REQUIREMENTS_DIR, INSTALL_SCRIPT_FILE, + requirementsInstallScript().getBytes(StandardCharsets.UTF_8)); + } + + /** + * Installs requirements.txt for both the bootstrap and the DAG-sync reinstall: with the + * variables the startup script exported (saved by the bootstrap, since a {@code docker exec} + * does not inherit them), under a time limit, and with pip's exit code recorded for + * {@link #lastRequirementsInstallExitCode}. Runs pip as {@code python -m pip}: the image's + * {@code PATH} starts with {@code /root/bin}, which the {@code airflow} user cannot read, so a + * bare {@code pip} exec fails with "Permission denied". + */ + static String requirementsInstallScript() { + return "if [ -f " + STARTUP_ENV_PATH + " ]; then . " + STARTUP_ENV_PATH + "; fi\n" + + "timeout " + REQUIREMENTS_INSTALL_TIMEOUT_SECONDS + " python -m pip install --no-cache-dir -r " + + REQUIREMENTS_PATH + "\n" + + "code=$?\n" + + "echo \"$code\" > " + INSTALL_EXIT_CODE_PATH + "\n" + + "exit \"$code\"\n"; + } + /** * Probes over TCP loopback on purpose. The official image runs first-boot init against a * temporary server that listens only on the Unix socket, so a socket probe can pass before @@ -715,9 +798,16 @@ public class MwaaEnvironmentManager { } ContainerExec.Result execInContainer(String containerId, String[] cmd) throws Exception { - return ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 30).throwIfTimedOut(containerId); + return execInContainer(containerId, cmd, 30); } + private ContainerExec.Result execInContainer(String containerId, String[] cmd, int timeoutSeconds) + throws Exception { + return ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, timeoutSeconds) + .throwIfTimedOut(containerId); + } + + private static String generateSecret(int bytes) { byte[] buf = new byte[bytes]; new SecureRandom().nextBytes(buf); diff --git a/src/main/java/io/floci/aws/services/mwaa/MwaaService.java b/src/main/java/io/floci/aws/services/mwaa/MwaaService.java index 4e07bd179e..d6ca94ecf8 100644 --- a/src/main/java/io/floci/aws/services/mwaa/MwaaService.java +++ b/src/main/java/io/floci/aws/services/mwaa/MwaaService.java @@ -33,6 +33,8 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -54,6 +56,10 @@ public class MwaaService implements TagHandler { */ private static final Pattern AIRFLOW_VERSION_PATTERN = Pattern.compile("\\d+\\.\\d+(\\.\\d+)?"); + /** S3 errors that mean the requirements object is not there (yet), rather than a fault. */ + private static final Set MISSING_OBJECT_ERRORS = Set.of("NoSuchKey", "NoSuchBucket"); + private static final int REQUIREMENTS_INSTALL_THREADS = 2; + private final StorageBackend storage; private final EmulatorConfig config; private final RegionResolver regionResolver; @@ -61,6 +67,8 @@ public class MwaaService implements TagHandler { private final MwaaProxyManager proxyManager; private final PortAllocator portAllocator; private final S3Service s3Service; + /** Runs DAG-sync reinstalls, which can take minutes, off the poller that syncs every environment. */ + private final Executor requirementsInstaller; private final ScheduledExecutorService readinessPoller = Executors.newSingleThreadScheduledExecutor(); private final ScheduledExecutorService dagSyncPoller = Executors.newSingleThreadScheduledExecutor(); @@ -74,10 +82,27 @@ public class MwaaService implements TagHandler { /** Last-installed requirements.txt ETag, per environment. */ private final Map requirementsEtagByEnvironment = new ConcurrentHashMap<>(); + /** Environments whose bootstrap install the first DAG-sync pass still has to check. */ + private final Set bootstrapInstallsToCheck = ConcurrentHashMap.newKeySet(); + + /** Environments with a reinstall running, so a slow one is never started twice. */ + private final Set requirementsInstallsInFlight = ConcurrentHashMap.newKeySet(); + @Inject public MwaaService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, MwaaEnvironmentManager environmentManager, MwaaProxyManager proxyManager, PortAllocator portAllocator, S3Service s3Service) { + this(storageFactory, config, regionResolver, environmentManager, proxyManager, portAllocator, s3Service, + Executors.newFixedThreadPool(REQUIREMENTS_INSTALL_THREADS, runnable -> { + Thread thread = new Thread(runnable, "mwaa-requirements-install"); + thread.setDaemon(true); + return thread; + })); + } + + MwaaService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, + MwaaEnvironmentManager environmentManager, MwaaProxyManager proxyManager, + PortAllocator portAllocator, S3Service s3Service, Executor requirementsInstaller) { this.storage = storageFactory.create("mwaa", "mwaa-environments.json", new TypeReference>() { }); @@ -87,6 +112,7 @@ public class MwaaService implements TagHandler { this.proxyManager = proxyManager; this.portAllocator = portAllocator; this.s3Service = s3Service; + this.requirementsInstaller = requirementsInstaller; } @PostConstruct @@ -101,6 +127,9 @@ public class MwaaService implements TagHandler { public void shutdown() { readinessPoller.shutdownNow(); dagSyncPoller.shutdownNow(); + if (requirementsInstaller instanceof ExecutorService installer) { + installer.shutdownNow(); + } if (!config.services().mwaa().mock() && !config.services().mwaa().keepRunningOnShutdown()) { for (Environment environment : allEnvironments()) { proxyManager.stopProxy(environmentIdentity(environment)); @@ -165,7 +194,16 @@ public class MwaaService implements TagHandler { boolean provisioned = false; try { byte[] startupScriptContent = fetchStartupScript(environment); - environmentManager.startEnvironment(environment, version, startupScriptContent); + S3Object requirements = fetchRequirements(environment); + if (requirements != null) { + // The container's bootstrap installs this file, so the DAG-sync pass must not + // install it again unless that install failed. Recorded before the start, so no + // sync can run in between. + requirementsEtagByEnvironment.put(environmentIdentity(environment), requirements.getETag()); + bootstrapInstallsToCheck.add(environmentIdentity(environment)); + } + environmentManager.startEnvironment(environment, version, startupScriptContent, + requirements != null ? requirements.getData() : null); proxyPort = portAllocator.allocate( config.services().mwaa().proxyBasePort(), config.services().mwaa().proxyMaxPort()); environment.setProxyPort(proxyPort); @@ -320,6 +358,7 @@ public class MwaaService implements TagHandler { cliTokensByEnvironment.remove(environmentIdentity); dagSyncState.remove(environmentIdentity); requirementsEtagByEnvironment.remove(environmentIdentity); + bootstrapInstallsToCheck.remove(environmentIdentity); deleteEnvironment(environment); return environment; } @@ -549,7 +588,8 @@ public class MwaaService implements TagHandler { }, intervalSeconds, intervalSeconds, TimeUnit.SECONDS); } - private void syncDags(Environment environment) { + // Package-private (not private) so MwaaServiceTest can run a single sync pass directly. + void syncDags(Environment environment) { if (environment.getSourceBucketArn() == null || environment.getDagS3Path() == null) { return; } @@ -595,26 +635,73 @@ public class MwaaService implements TagHandler { // 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 — at the cost of re-running `pip install` - // on every pass where the file's ETag changed, which is the same cadence as DAG changes. + // matching how DAG file changes are already picked up. The install itself runs on + // requirementsInstaller, one at a time per environment, so a slow pip never holds up the DAG + // sync of every other environment. private void syncRequirementsIfNeeded(Environment environment, String bucket) { if (!config.services().mwaa().installRequirements() || environment.getRequirementsS3Path() == null) { return; } + String environmentIdentity = environmentIdentity(environment); + if (bootstrapInstallsToCheck.remove(environmentIdentity)) { + checkBootstrapInstall(environment, environmentIdentity); + } try { S3Object requirements = s3Service.getObject(bucket, environment.getRequirementsS3Path()); - String environmentIdentity = environmentIdentity(environment); - String lastEtag = requirementsEtagByEnvironment.get(environmentIdentity); - if (!requirements.getETag().equals(lastEtag)) { - environmentManager.installRequirements(environment, requirements.getData()); - requirementsEtagByEnvironment.put(environmentIdentity, requirements.getETag()); + if (requirements.getETag().equals(requirementsEtagByEnvironment.get(environmentIdentity)) + || !requirementsInstallsInFlight.add(environmentIdentity)) { + return; } + requirementsInstaller.execute(() -> reinstallRequirements(environment, environmentIdentity, requirements)); } catch (Exception e) { LOG.warnv("Could not sync requirements.txt for environment {0}: {1}", environment.getName(), e.getMessage()); } } + // A failed bootstrap install forgets the recorded ETag, so the same sync pass installs the file again. + private void checkBootstrapInstall(Environment environment, String environmentIdentity) { + Integer exitCode = environmentManager.lastRequirementsInstallExitCode(environment); + if (exitCode != null && exitCode != 0) { + LOG.warnv("pip install -r requirements.txt exited {0} while MWAA environment {1} started; " + + "installing it again", String.valueOf(exitCode), environment.getName()); + requirementsEtagByEnvironment.remove(environmentIdentity); + } + } + + private void reinstallRequirements(Environment environment, String environmentIdentity, S3Object requirements) { + try { + environmentManager.installRequirements(environment, requirements.getData()); + if (environment.getStatus() == EnvironmentStatus.AVAILABLE) { + requirementsEtagByEnvironment.put(environmentIdentity, requirements.getETag()); + } + } finally { + requirementsInstallsInFlight.remove(environmentIdentity); + } + } + + // Fetched at creation so the container installs requirements.txt before Airflow starts, the + // order real MWAA uses. A missing object does not fail the environment, since the DAG-sync pass + // installs the file once it appears; any other S3 error fails CreateEnvironment, as it does for + // the startup script. + private S3Object fetchRequirements(Environment environment) { + if (!config.services().mwaa().installRequirements() || environment.getRequirementsS3Path() == null + || environment.getSourceBucketArn() == null) { + return null; + } + try { + return s3Service.getObject(bucketNameFromArn(environment.getSourceBucketArn()), + environment.getRequirementsS3Path()); + } catch (AwsException e) { + if (!MISSING_OBJECT_ERRORS.contains(e.getErrorCode())) { + throw e; + } + LOG.warnv("requirements.txt for environment {0} is not in S3 yet ({1}); the DAG-sync pass installs it " + + "once it is", environment.getName(), e.getErrorCode()); + return null; + } + } + // Unlike DAG/requirements sync (which run periodically post-creation and must never fail the // environment over one bad object), the startup script only ever runs once, at container // creation — a missing/unreadable object here is a genuine configuration error, so it diff --git a/src/test/java/io/floci/aws/services/mwaa/MwaaEnvironmentManagerTest.java b/src/test/java/io/floci/aws/services/mwaa/MwaaEnvironmentManagerTest.java index 7c24169c61..170070d1b3 100644 --- a/src/test/java/io/floci/aws/services/mwaa/MwaaEnvironmentManagerTest.java +++ b/src/test/java/io/floci/aws/services/mwaa/MwaaEnvironmentManagerTest.java @@ -23,6 +23,7 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Optional; @@ -30,6 +31,7 @@ import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -96,8 +98,13 @@ class MwaaEnvironmentManagerTest { return startAirflowAndCaptureSpec(runningInContainer, null); } - @SuppressWarnings("unchecked") private ContainerSpec startAirflowAndCaptureSpec(boolean runningInContainer, byte[] startupScriptContent) { + return startAirflowAndCaptureSpec(runningInContainer, startupScriptContent, null); + } + + @SuppressWarnings("unchecked") + private ContainerSpec startAirflowAndCaptureSpec(boolean runningInContainer, byte[] startupScriptContent, + byte[] requirementsContent) { when(containerDetector.isRunningInContainer()).thenReturn(runningInContainer); when(lifecycleManager.create(any())).thenReturn("airflow-container-id"); ContainerInfo info = new ContainerInfo("airflow-container-id", @@ -107,7 +114,8 @@ class MwaaEnvironmentManagerTest { Environment environment = new Environment(); environment.setName("my-env"); - manager.startAirflowContainer(environment, "2.10.5", "172.18.0.9", "db-secret-pw", startupScriptContent); + manager.startAirflowContainer(environment, "2.10.5", "172.18.0.9", "db-secret-pw", startupScriptContent, + requirementsContent); ArgumentCaptor captor = ArgumentCaptor.forClass(ContainerSpec.class); Mockito.verify(lifecycleManager).create(captor.capture()); @@ -198,7 +206,7 @@ class MwaaEnvironmentManagerTest { "core.dags_are_paused_at_creation", "false", "core.executor", "CeleryExecutor")); - manager.startAirflowContainer(environment, "2.10.5", "172.18.0.9", "db-secret-pw", null); + manager.startAirflowContainer(environment, "2.10.5", "172.18.0.9", "db-secret-pw", null, null); ArgumentCaptor captor = ArgumentCaptor.forClass(ContainerSpec.class); verify(lifecycleManager).create(captor.capture()); @@ -242,7 +250,7 @@ class MwaaEnvironmentManagerTest { environment.setName("my-env"); environment.setArn("arn:aws:airflow:eu-west-1:111111111111:environment/my-env"); - manager.startAirflowContainer(environment, "2.10.5", "172.18.0.9", "db-secret-pw", null); + manager.startAirflowContainer(environment, "2.10.5", "172.18.0.9", "db-secret-pw", null, null); ArgumentCaptor captor = ArgumentCaptor.forClass(ContainerSpec.class); verify(lifecycleManager).create(captor.capture()); @@ -258,12 +266,86 @@ class MwaaEnvironmentManagerTest { String script = spec.cmd().get(0); assertTrue(script.contains("airflow db migrate")); assertTrue(script.contains("airflow users create")); + assertTrue(script.contains("(while true; do airflow triggerer; ")); assertTrue(script.contains("airflow scheduler &")); assertTrue(script.contains("exec airflow webserver")); - // migrate/user-create must precede the background scheduler, not run inside its background chain. + // migrate/user-create must precede the background triggerer and scheduler, not run inside + // their background chain. + assertTrue(script.indexOf("airflow db migrate") < script.indexOf("airflow triggerer")); assertTrue(script.indexOf("airflow db migrate") < script.indexOf("airflow scheduler &")); } + @Test + void bootstrapScriptInstallsRequirementsAfterTheStartupScriptAndBeforeAirflowStarts() { + String script = MwaaEnvironmentManager.airflowBootstrapScript(); + + int startupIdx = script.indexOf("/startup.sh"); + int saveEnvIdx = script.indexOf("(umask 077; export -p > /tmp/mwaa-startup.env)"); + int installIdx = script.indexOf("if [ -f /tmp/mwaa-requirements.txt ]; then sh /tmp/mwaa-install-requirements.sh" + + " || "); + int migrateIdx = script.indexOf("airflow db migrate"); + + assertTrue(saveEnvIdx >= 0 && installIdx >= 0); + assertTrue(startupIdx < saveEnvIdx && saveEnvIdx < installIdx && installIdx < migrateIdx, + "real MWAA runs the startup script, then installs requirements, then starts Airflow"); + } + + @Test + void requirementsInstallScriptKeepsTheStartupExportsLimitsPipAndRecordsItsExitCode() { + String script = MwaaEnvironmentManager.requirementsInstallScript(); + + assertTrue(script.startsWith("if [ -f /tmp/mwaa-startup.env ]; then . /tmp/mwaa-startup.env; fi\n")); + assertTrue(script.contains("timeout 900 python -m pip install --no-cache-dir -r /tmp/mwaa-requirements.txt\n")); + assertTrue(script.contains("echo \"$code\" > /tmp/mwaa-requirements.exit\n")); + assertTrue(script.endsWith("exit \"$code\"\n")); + } + + @Test + void requirementsReinstallCopiesTheFileAndRunsTheInstallScript() throws Exception { + DockerClient dockerClient = Mockito.mock(DockerClient.class); + CopyArchiveToContainerCmd copyCmd = Mockito.mock(CopyArchiveToContainerCmd.class, Mockito.RETURNS_SELF); + when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + when(dockerClient.copyArchiveToContainerCmd(anyString())).thenReturn(copyCmd); + List> commands = ContainerExecStubs.completeEveryExec(dockerClient, "airflow-container-id", 0, + "", ""); + Environment environment = new Environment(); + environment.setName("my-env"); + environment.setAirflowContainerId("airflow-container-id"); + + manager.installRequirements(environment, "boto3\n".getBytes(StandardCharsets.UTF_8)); + + verify(copyCmd, times(2)).withRemotePath("/tmp"); + assertEquals(List.of(List.of("sh", "/tmp/mwaa-install-requirements.sh")), commands); + } + + @Test + void lastRequirementsInstallExitCodeReadsWhatTheInstallScriptRecorded() { + DockerClient dockerClient = Mockito.mock(DockerClient.class); + when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + Environment environment = new Environment(); + environment.setName("my-env"); + environment.setAirflowContainerId("airflow-container-id"); + + List> commands = ContainerExecStubs.completeEveryExec(dockerClient, "airflow-container-id", 0, + "1\n", ""); + + assertEquals(1, manager.lastRequirementsInstallExitCode(environment)); + assertEquals(List.of(List.of("cat", "/tmp/mwaa-requirements.exit")), commands); + } + + @Test + void lastRequirementsInstallExitCodeIsUnknownWhenNothingWasRecorded() { + DockerClient dockerClient = Mockito.mock(DockerClient.class); + when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + Environment environment = new Environment(); + environment.setName("my-env"); + environment.setAirflowContainerId("airflow-container-id"); + ContainerExecStubs.completeEveryExec(dockerClient, "airflow-container-id", 1, "", + "cat: /tmp/mwaa-requirements.exit: No such file or directory\n"); + + assertNull(manager.lastRequirementsInstallExitCode(environment)); + } + @Test void bootstrapScriptSourcesAnOptionalStartupScriptBeforeMigrating() { ContainerSpec spec = startAirflowAndCaptureSpec(false); @@ -362,6 +444,17 @@ class MwaaEnvironmentManagerTest { MwaaEnvironmentManager.airflowContainerName(null, westEnvironment)); } + @Test + void healthCheckRequiresMetadatabaseSchedulerAndTriggererHealthy() { + String allHealthy = "{\"metadatabase\": {\"status\": \"healthy\"}, \"scheduler\": {\"status\": \"healthy\"}, " + + "\"triggerer\": {\"latest_triggerer_heartbeat\": \"2026-11-15T00:40:57+00:00\", \"status\": \"healthy\"}}"; + String noTriggerer = "{\"metadatabase\": {\"status\": \"healthy\"}, \"scheduler\": {\"status\": \"healthy\"}, " + + "\"triggerer\": {\"latest_triggerer_heartbeat\": null, \"status\": null}}"; + + assertTrue(MwaaEnvironmentManager.isHealthy(allHealthy)); + assertFalse(MwaaEnvironmentManager.isHealthy(noTriggerer)); + } + @Test void healthCheckRequiresBothMetadatabaseAndSchedulerHealthy() { String bothHealthy = "{\"metadatabase\":{\"status\":\"healthy\"},\"scheduler\":{\"status\":\"healthy\"}}"; @@ -425,6 +518,31 @@ class MwaaEnvironmentManagerTest { verify(copyCmd, times(2)).exec(); } + @Test + void requirementsAreInjectedBeforeTheContainerStartsWhenProvided() { + startAirflowAndCaptureSpec(false, null, "boto3\n".getBytes(StandardCharsets.UTF_8)); + + verify(copyCmd).withRemotePath("/etc/sudoers.d"); + verify(copyCmd, times(2)).withRemotePath("/tmp"); + verify(copyCmd, times(3)).exec(); + } + + @Test + void requirementsInjectionFailurePreventsTheContainerFromStarting() { + when(copyCmd.exec()).thenThrow(new RuntimeException("docker cp failed")); + when(lifecycleManager.create(any())).thenReturn("airflow-container-id"); + + Environment environment = new Environment(); + environment.setName("my-env"); + + assertThrows(IllegalStateException.class, () -> manager.startAirflowContainer( + environment, "2.10.5", "172.18.0.9", "db-secret-pw", null, + "boto3\n".getBytes(StandardCharsets.UTF_8))); + + verify(lifecycleManager).removeIfExists("airflow-container-id"); + verify(lifecycleManager, never()).startCreated(anyString(), any()); + } + @Test void startupScriptInjectionFailurePreventsTheContainerFromStarting() { // Shared copyCmd mock, so this also makes the (best-effort) sudoers-grant copy fail — @@ -436,7 +554,7 @@ class MwaaEnvironmentManagerTest { environment.setName("my-env"); assertThrows(IllegalStateException.class, () -> manager.startAirflowContainer( - environment, "2.10.5", "172.18.0.9", "db-secret-pw", "export FOO=bar\n".getBytes())); + environment, "2.10.5", "172.18.0.9", "db-secret-pw", "export FOO=bar\n".getBytes(), null)); verify(lifecycleManager).removeIfExists("airflow-container-id"); verify(lifecycleManager, never()).startCreated(anyString(), any()); diff --git a/src/test/java/io/floci/aws/services/mwaa/MwaaServiceTest.java b/src/test/java/io/floci/aws/services/mwaa/MwaaServiceTest.java index fbba039a90..5b20715bd3 100644 --- a/src/test/java/io/floci/aws/services/mwaa/MwaaServiceTest.java +++ b/src/test/java/io/floci/aws/services/mwaa/MwaaServiceTest.java @@ -16,6 +16,7 @@ import io.floci.aws.services.mwaa.model.NetworkConfiguration; import io.floci.aws.services.mwaa.model.UpdateEnvironmentRequest; import io.floci.aws.services.mwaa.proxy.MwaaProxyManager; import io.floci.aws.services.s3.S3Service; +import io.floci.aws.services.s3.model.S3Object; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -24,6 +25,8 @@ import org.mockito.Mockito; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; @@ -551,6 +554,8 @@ class MwaaServiceTest { private MwaaEnvironmentManager environmentManager; private MwaaProxyManager proxyManager; private MwaaService realModeService; + private S3Service s3Service; + private final List queuedInstalls = new ArrayList<>(); private boolean keepRunningOnShutdown; @BeforeEach @@ -573,6 +578,7 @@ class MwaaServiceTest { case "proxyMaxPort" -> 8799; case "dagSyncIntervalSeconds" -> 30; case "keepRunningOnShutdown" -> keepRunningOnShutdown; + case "installRequirements" -> true; default -> defaultValue(method); }); EmulatorConfig.ServicesConfig servicesConfig = proxy(EmulatorConfig.ServicesConfig.class, @@ -592,14 +598,14 @@ class MwaaServiceTest { }); RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); - S3Service s3Service = Mockito.mock(S3Service.class); + s3Service = Mockito.mock(S3Service.class); environmentManager = Mockito.mock(MwaaEnvironmentManager.class); proxyManager = Mockito.mock(MwaaProxyManager.class); portAllocator = Mockito.mock(PortAllocator.class); when(portAllocator.allocate(8700, 8799)).thenReturn(8701); realModeService = new MwaaService(storageFactory, config, regionResolver, - environmentManager, proxyManager, portAllocator, s3Service); + environmentManager, proxyManager, portAllocator, s3Service, queuedInstalls::add); } @Test @@ -640,6 +646,99 @@ class MwaaServiceTest { verify(proxyManager).stopProxy(mwaaService.environmentIdentity(environment)); } + private Environment createWithRequirements(String name, byte[] requirements) { + return createWithRequirements(name, requirements, 0); + } + + private Environment createWithRequirements(String name, byte[] requirements, int bootstrapExitCode) { + when(s3Service.getObject("my-bucket", "requirements.txt")) + .thenReturn(new S3Object("my-bucket", "requirements.txt", requirements, "text/plain")); + when(environmentManager.lastRequirementsInstallExitCode(any())).thenReturn(bootstrapExitCode); + CreateEnvironmentRequest request = createRequest("arn:aws:s3:::my-bucket", "dags"); + request.setRequirementsS3Path("requirements.txt"); + Environment environment = realModeService.createEnvironment(name, request); + when(environmentManager.isReady(environment)).thenReturn(true); + realModeService.checkReadiness(environment); + return environment; + } + + @Test + void requirementsReachTheContainerBeforeAirflowStartsAndTheFirstSyncDoesNotReinstall() { + byte[] requirements = "boto3==1.35.0\n".getBytes(StandardCharsets.UTF_8); + + Environment environment = createWithRequirements("req-env", requirements); + realModeService.syncDags(environment); + + verify(environmentManager).startEnvironment(environment, "2.10.5", null, requirements); + assertTrue(queuedInstalls.isEmpty()); + } + + @Test + void aFailedBootstrapInstallIsInstalledAgainByTheFirstSync() { + byte[] requirements = "boto3==1.35.0\n".getBytes(StandardCharsets.UTF_8); + Environment environment = createWithRequirements("req-failed-env", requirements, 1); + + realModeService.syncDags(environment); + queuedInstalls.forEach(Runnable::run); + + verify(environmentManager).installRequirements(environment, requirements); + } + + @Test + void aReinstallStillRunningIsNotStartedAgain() { + Environment environment = createWithRequirements("req-slow-env", + "boto3==1.35.0\n".getBytes(StandardCharsets.UTF_8)); + when(s3Service.getObject("my-bucket", "requirements.txt")).thenReturn(new S3Object("my-bucket", + "requirements.txt", "boto3==1.36.0\n".getBytes(StandardCharsets.UTF_8), "text/plain")); + + realModeService.syncDags(environment); + realModeService.syncDags(environment); + + assertEquals(1, queuedInstalls.size()); + } + + @Test + void changedRequirementsAreReinstalledByTheNextSync() { + Environment environment = createWithRequirements("req-change-env", + "boto3==1.35.0\n".getBytes(StandardCharsets.UTF_8)); + byte[] changed = "boto3==1.36.0\n".getBytes(StandardCharsets.UTF_8); + when(s3Service.getObject("my-bucket", "requirements.txt")) + .thenReturn(new S3Object("my-bucket", "requirements.txt", changed, "text/plain")); + + realModeService.syncDags(environment); + queuedInstalls.forEach(Runnable::run); + realModeService.syncDags(environment); + + verify(environmentManager).installRequirements(environment, changed); + assertEquals(1, queuedInstalls.size()); + } + + @Test + void anS3FaultReadingRequirementsFailsTheEnvironment() { + when(s3Service.getObject("my-bucket", "requirements.txt")).thenThrow(new AwsException("InternalError", + "We encountered an internal error. Please try again.", 500)); + CreateEnvironmentRequest request = createRequest("arn:aws:s3:::my-bucket", "dags"); + request.setRequirementsS3Path("requirements.txt"); + + Environment environment = realModeService.createEnvironment("faulty-req-env", request); + + assertEquals(EnvironmentStatus.CREATE_FAILED, environment.getStatus()); + verify(environmentManager, Mockito.never()).startEnvironment(any(), any(), any(), any()); + } + + @Test + void aMissingRequirementsObjectDoesNotFailTheEnvironment() { + when(s3Service.getObject("my-bucket", "requirements.txt")).thenThrow(new AwsException("NoSuchKey", + "The specified key does not exist.", 404)); + CreateEnvironmentRequest request = createRequest("arn:aws:s3:::my-bucket", "dags"); + request.setRequirementsS3Path("requirements.txt"); + + Environment environment = realModeService.createEnvironment("missing-req-env", request); + + assertEquals(EnvironmentStatus.CREATING, environment.getStatus()); + verify(environmentManager).startEnvironment(environment, "2.10.5", null, null); + } + @Test void checkReadinessMarksEnvironmentAvailableOnceReady() { Environment environment = realModeService.createEnvironment("ready-env",