mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
be6488b7ea
commit
b4fbe99123
5 files changed
+433
-40
No files matched your search
@@ -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<ContainerSpec> 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<ContainerSpec> 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<ContainerSpec> 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<List<String>> 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<List<String>> 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());
|
||||
|
||||
@@ -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<Runnable> 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",
|
||||
|
||||
Reference in new issue
Block a user