fix(mwaa): run the triggerer and install requirements.txt before Airflow starts (#8398)

Deferrable tasks stayed deferred forever: the Airflow container ran only
the scheduler and the webserver. The bootstrap now runs `airflow
triggerer` beside the scheduler in a restart loop, as MWAA runs one for
Airflow 2.2 and later, and an environment is only AVAILABLE once
/health reports the triggerer healthy.

requirements.txt was never installed. It was installed by a docker exec
of `pip` after the container started, and in the apache/airflow image
`pip` resolves to /root/bin/pip, which the airflow user cannot read, so
the exec exited 126; the exec was also cut off after 30 seconds. The
file is now fetched at CreateEnvironment and installed by the container
bootstrap after the startup script and before Airflow starts, the order
AWS documents. One install script serves the bootstrap and the DAG-sync
reinstall: it sources the environment saved after the startup script,
runs `timeout 900 python -m pip install`, and records pip's exit code.
The first DAG-sync pass reinstalls only when that bootstrap install
failed. Reinstalls run on their own pool, one at a time per
environment, so a slow pip no longer holds up the DAG sync. Only a
missing requirements object leaves CreateEnvironment going; other S3
errors fail it, as they do for the startup script.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-14 22:20:33 -04:00
1 parent be6488b7ea
commit b4fbe99123
5 files changed
+433 -40

No files matched your search

@@ -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<String> MWAA_CLI_COMMANDS = Set.of("cheat-sheet", "version");
private static final Map<String, Set<String>> 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);
@@ -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<String> MISSING_OBJECT_ERRORS = Set.of("NoSuchKey", "NoSuchBucket");
private static final int REQUIREMENTS_INSTALL_THREADS = 2;
private final StorageBackend<String, Environment> 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<String, String> requirementsEtagByEnvironment = new ConcurrentHashMap<>();
/** Environments whose bootstrap install the first DAG-sync pass still has to check. */
private final Set<String> bootstrapInstallsToCheck = ConcurrentHashMap.newKeySet();
/** Environments with a reinstall running, so a slow one is never started twice. */
private final Set<String> 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<Map<String, Environment>>() {
});
@@ -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