feat(mwaa): add Amazon MWAA emulation backed by real Airflow (LocalExecutor) (#2086)

* feat(mwaa): add Amazon MWAA emulation backed by real Airflow (LocalExecutor)

Adds a new services/mwaa package following the EKS lifecycle pattern
(Controller/Service/EnvironmentManager, one Docker container-set per
resource, readiness polling) and the Neptune/ElastiCache proxy pattern
(MwaaWebProxy/MwaaProxyManager: Floci owns the host-facing port, the
backing container stays internal-only).

Each environment is backed by two real containers — postgres:16-alpine
for the metadata DB and apache/airflow:<version>-python3.12 running
LocalExecutor — with AirflowVersion genuinely selecting the image tag
(validated against a configured allow-list), unlike EKS's cosmetic-only
version field. MwaaWebProxy fronts the real Airflow webserver and
intercepts POST /aws_mwaa/cli, bridging it to a docker-exec'd `airflow`
CLI call and returning the documented {stdout, stderr} shape.

DAGs and requirements.txt sync from S3 on a poller, reusing the existing
S3Service in-process rather than a new AWS-facing surface. The Airflow
container is pointed back at Floci via LaunchedContainerAwsEnv (the same
mechanism Lambda/ECS containers already use), so a DAG's own boto3 calls
resolve against Floci instead of real AWS.

StartupScriptS3Path is supported end-to-end: fetched from S3 at create
time, injected before the container starts (create -> inject -> start,
mirroring EksClusterManager's config-injection sequencing), sourced
before migrate/scheduler/webserver so exported vars propagate. The
airflow user gets a passwordless sudo grant (verified against the real
image — sudo ships but isn't passwordless by default, and AWS's own
startup-script examples assume sudo just works), and a fixed set of
Floci-critical env vars (Fernet key, DB DSN, executor, AWS-SDK-redirection
vars) are snapshotted before and restored after the script runs, mirroring
real MWAA's reserved-environment-variable protection.

Verified end-to-end against real Docker (not just the mock=true unit
suite): environment reaches AVAILABLE, proxy pass-through and the CLI
bridge both work with real output, a DAG uploaded to S3 syncs and parses,
a second environment on a different AirflowVersion pulls a genuinely
distinct image, and delete tears down both containers/volumes and the
proxy cleanly.

45 new tests (unit + RestAssured integration, all against mock=true in
the default suite so Docker is never required for `mvnw test`); full
suite otherwise unchanged.

* fix(mwaa): hard-fail startup-script injection failures, release proxy ports on delete

Two issues from review:

copyFileIntoContainer swallowed every failure identically, including the
one case where that's wrong: a configured StartupScriptS3Path that fails
to copy into the container. The entrypoint's "if [ -f /startup.sh ]"
guard would silently skip it and the environment would reach AVAILABLE
having never applied the requested setup, contradicting the documented
intent of gating environment creation on startup-script failure (matching
real MWAA). copyFileIntoContainer now reports success/failure; the
startup-script call site checks it and throws, while DAG sync and the
best-effort sudoers grant keep their existing soft-fail behavior.

deleteEnvironment allocated a proxy port via PortAllocator on create but
never released it on delete, unlike every other service that uses
PortAllocator (Lambda, MSK, EC2, ECR) — repeated create/delete cycles
would eventually exhaust the configured proxy port range even with zero
MWAA proxies actually running.

* fix(mwaa): roll back allocated proxy port and containers on create failure

If startEnvironment() succeeded (containers running) but PortAllocator.allocate
or MwaaProxyManager.startProxy failed afterward, createEnvironment's catch
block set CREATE_FAILED without releasing the reserved port or stopping the
containers that had already started — leaking both on every such failure.

Mirrors NeptuneService.createDbCluster/rollbackDbCluster's already-proven
shape for this exact class of problem (container + proxy + port, partial
failure must roll back everything): a provisioned flag set only after every
step succeeds, and a try/finally that runs rollbackFailedCreate whenever it
doesn't — stopping the proxy (a no-op if it never started), stopping any
containers that did start (MwaaEnvironmentManager.stopEnvironment already
null-checks each container id, so it's safe for partial startup too), and
always releasing the port.

* fix(mwaa): correct CreateEnvironment error shape, namespace container names, add docs

Two items from maintainer review:

- Duplicate CreateEnvironment threw ResourceAlreadyExistsException, a shape the
  operation doesn't declare (verified against the real botocore mwaa/2020-07-01
  model: CreateEnvironment's only errors are ServiceUnavailableException,
  ValidationException, InternalServerException) — SDK clients couldn't map it.
  Now throws ValidationException.

- dbContainerName/airflowContainerName built names via raw string concatenation
  instead of routing through ContainerStorageHelper.dockerName like every other
  Docker-backed service (EKS, RDS, ...), so MWAA alone didn't participate in the
  FLOCI_DOCKER_RESOURCE_NAMESPACE convention that keeps multiple Floci instances
  sharing one Docker daemon from colliding. Both static methods now take the
  EmulatorConfig and route through the shared helper; volume names inherit the
  fix automatically since they're built by extending the container name.

Also adds docs/services/mwaa.md (mkdocs nav updated) following eks.md's
structure — operations table, mock/real mode, the web/CLI proxy, startup-script
behavior (sudo grant, reserved-variable protection), config reference, ARN
format, CLI/SDK examples, and an honest "Not Implemented" section covering the
known gaps already discussed on the PR (PluginsS3Path, cross-account container
naming, restart restoration).
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-08-04 22:16:14 -05:00
1 parent 5f7d4d2dc8
commit 7e4e3e8c50
23 files changed
+3182 -1

No files matched your search

+4 -1
View File
@@ -222,7 +222,7 @@ Floci supports local emulation for application services, data services, eventing
| Core app services | S3, SQS, SNS, DynamoDB, Lambda, IAM, KMS, Secrets Manager, SSM |
| Events and workflows | EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, CloudWatch Logs, CloudWatch Metrics |
| API and identity | API Gateway REST, API Gateway v2, AppSync, Cognito, ACM, Route53, Cloud Map |
| Containers and compute | ECS, EC2, Lightsail, EKS, ECR, CodeBuild, CodeDeploy, CodePipeline, AWS Batch, Auto Scaling, Elastic Beanstalk, ELB v2 |
| Containers and compute | ECS, EC2, Lightsail, EKS, MWAA, ECR, CodeBuild, CodeDeploy, CodePipeline, AWS Batch, Auto Scaling, Elastic Beanstalk, ELB v2 |
| Data, analytics, and AI | Athena, Glue, EMR, Firehose, OpenSearch, S3 Vectors, Textract, Transcribe, Bedrock Runtime |
| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache |
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core |
@@ -283,6 +283,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| AppConfigData | In-process | Configuration sessions and dynamic configuration retrieval |
| Bedrock Runtime | In-process stub | Dummy Converse and InvokeModel responses for local development |
| EKS | Real Docker, mock mode available | k3s clusters with live Kubernetes API server |
| MWAA | Real Docker, mock mode available | Real Apache Airflow (LocalExecutor) + Postgres metadata DB per environment; web/CLI proxy; S3-backed DAG sync |
| ELB v2 | In-process | ALB, NLB, target groups, listeners, routing rules, Lambda targets, tags |
| CodeBuild | In-process with real Docker | Real buildspec execution, CloudWatch logs, S3 artifacts |
| CodeDeploy | In-process with Lambda traffic shifting | Deployment groups, configs, lifecycle hooks, auto-rollback |
@@ -326,6 +327,7 @@ Floci uses real Docker containers when in-process emulation would reduce fidelit
| EC2 | AMI-mapped Linux images | Linux containers, SSH key injection, UserData, IMDS, IAM credentials |
| ECS | User-specified task image | Container lifecycle, start, stop, health checks |
| EKS | `rancher/k3s:latest` | Kubernetes API server via k3s |
| MWAA | `apache/airflow:<version>-python3.12` + `postgres:16-alpine` | Real Apache Airflow (LocalExecutor: scheduler + webserver) with its own Postgres metadata DB; webserver/CLI reachable via Floci's proxy |
| CodeBuild | User-specified environment image | Buildspec execution, log streaming, S3 artifact upload |
| OpenSearch | `opensearchproject/opensearch:2` | Full OpenSearch engine with REST API |
| ECR | `registry:2` | OCI-compatible registry for docker push and docker pull |
@@ -354,6 +356,7 @@ docker run -d --name floci \
| `FLOCI_SERVICES_NEPTUNE_DEFAULT_NEO4J_IMAGE` | `neo4j:5-community` |
| `FLOCI_SERVICES_DOCDB_DEFAULT_IMAGE` | `mongo:7.0` |
| `FLOCI_SERVICES_EKS_DEFAULT_IMAGE` | `rancher/k3s:latest` |
| `FLOCI_SERVICES_MWAA_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` |
| `FLOCI_SERVICES_ECR_REGISTRY_IMAGE` | `registry:2` |
| `FLOCI_ECR_BASE_URI` | `public.ecr.aws` |
+187
View File
@@ -0,0 +1,187 @@
# MWAA (Amazon Managed Workflows for Apache Airflow)
**Protocol:** REST-JSON
**Endpoint:** `http://localhost:4566/` (path-routed via JAX-RS)
MWAA signs requests as `airflow` (its SigV4 signing name) but registers under the `mwaa` endpoint id, the same signing-name/endpoint-id split as Bedrock Runtime — both are registered so credential-scope lookups resolve correctly either way.
## Supported Operations
| Operation | Description |
|---|---|
| `CreateEnvironment` | Create a new MWAA environment |
| `GetEnvironment` | Describe an environment by name |
| `ListEnvironments` | List all environment names |
| `UpdateEnvironment` | Update metadata-only fields on an environment |
| `DeleteEnvironment` | Delete an environment |
| `CreateWebLoginToken` | Get a token + URL for the Airflow UI |
| `CreateCliToken` | Get a token for the `/aws_mwaa/cli` bridge |
| `TagResource` | Add tags to an environment (via the shared tags controller) |
| `UntagResource` | Remove tags from an environment (via the shared tags controller) |
| `ListTagsForResource` | List tags on an environment (via the shared tags controller) |
## Modes
### Mock mode (`mock: true`)
Environment metadata is stored in-process. No Docker containers are started. The environment transitions directly to `AVAILABLE` on creation. Use this in CI or whenever you only need the MWAA API shape, not a real Airflow instance.
### Real mode (`mock: false`, default)
Floci starts two containers per environment:
- `floci-mwaa-<name>-db` — a private `postgres` metadata database, never given a published host port; it's only ever reached by the sibling Airflow container over the Docker network.
- `floci-mwaa-<name>-airflow` — a real `apache/airflow` container running **LocalExecutor** (webserver + scheduler in one process tree). `AirflowVersion` genuinely selects the image tag (`apache/airflow:<version>-python3.12`), validated against `supported-versions` — unlike some Floci services where a requested version is echoed back but not actually applied, MWAA always runs the exact Airflow version requested.
Once Airflow's unauthenticated `/health` endpoint reports both `metadatabase` and `scheduler` as `"healthy"`, the environment transitions to `AVAILABLE`.
### Web/CLI proxy
Floci runs its own HTTP proxy per environment (published on a host port from the configured range) that fronts the real Airflow webserver: every request is forwarded through to Airflow as-is, **except** `POST /aws_mwaa/cli`, which the proxy intercepts itself — it validates the `Authorization: Bearer <CliToken>` from `CreateCliToken`, then runs the requested `airflow` CLI command inside the container via `docker exec` and returns the AWS-documented `{stdout, stderr}` (base64) shape. `Environment.WebserverUrl` and the URL returned by `CreateWebLoginToken` both point at this proxy, so Airflow-UI browsing and the CLI-token flow go through the same place.
### 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:
- 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.
- A script that fails (non-zero exit, or fails to inject at all) fails `CreateEnvironment` outright, matching real MWAA gating environment creation on startup-script success.
### AWS SDK calls from DAG code
The Airflow container is pointed back at Floci itself (`AWS_ENDPOINT_URL`, placeholder credentials, region) using the same mechanism Lambda and ECS containers already use to reach the emulator — so a DAG's own `boto3.client("s3")`/`boto3.client("secretsmanager")` calls resolve against Floci instead of attempting to reach real AWS.
!!! note "Docker socket required"
Real mode starts privileged Docker containers. Mount the Docker socket and set the Docker network so containers can reach each other.
```yaml
services:
floci:
image: floci/floci:latest
volumes:
- /var/run/docker.sock:/var/run/docker.sock
ports:
- "4566:4566"
environment:
FLOCI_SERVICES_MWAA_DOCKER_NETWORK: my_project_default
```
## Configuration
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_MWAA_ENABLED` | `true` | Enable the MWAA service |
| `FLOCI_SERVICES_MWAA_MOCK` | `false` | Metadata-only mode (no Docker) |
| `FLOCI_SERVICES_MWAA_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Metadata-database Docker image |
| `FLOCI_SERVICES_MWAA_SUPPORTED_VERSIONS` | `2.10.5,2.9.3,2.8.4` | Comma-separated `AirflowVersion` allow-list; `CreateEnvironment` rejects any other value |
| `FLOCI_SERVICES_MWAA_DEFAULT_VERSION` | `2.10.5` | `AirflowVersion` used when the request omits one |
| `FLOCI_SERVICES_MWAA_PROXY_BASE_PORT` | `8700` | First port in the web/CLI proxy range |
| `FLOCI_SERVICES_MWAA_PROXY_MAX_PORT` | `8799` | Last port in the web/CLI proxy range |
| `FLOCI_SERVICES_MWAA_DATA_PATH` | `./data/mwaa` | Host data directory root |
| `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 |
## 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.
## ARN Format
```
arn:aws:airflow:<region>:<accountId>:environment/<name>
```
## Examples
```bash
export AWS_ENDPOINT_URL=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
# Create an environment
aws mwaa create-environment \
--name my-environment \
--execution-role-arn arn:aws:iam::000000000000:role/mwaa-role \
--source-bucket-arn arn:aws:s3:::my-mwaa-bucket \
--dag-s3-path dags \
--network-configuration SubnetIds=subnet-1,subnet-2,SecurityGroupIds=sg-1 \
--airflow-version 2.10.5
# Get the environment (poll Status until AVAILABLE)
aws mwaa get-environment --name my-environment
# List environments
aws mwaa list-environments
# Get a web login token
aws mwaa create-web-login-token --name my-environment
# Get a CLI token, then call the bridge directly
aws mwaa create-cli-token --name my-environment
curl -s -X POST "http://localhost:<proxyPort>/aws_mwaa/cli" \
-H "Authorization: Bearer <CliToken>" \
-H "Content-Type: text/plain" \
--data-raw "dags list"
# Tag the environment
aws mwaa tag-resource \
--resource-arn arn:aws:airflow:us-east-1:000000000000:environment/my-environment \
--tags env=dev,team=platform
# Delete the environment
aws mwaa delete-environment --name my-environment
```
## Java SDK Example
```java
MwaaClient mwaa = MwaaClient.builder()
.endpointOverride(URI.create("http://localhost:4566"))
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("test", "test")))
.build();
// Create environment
CreateEnvironmentResponse created = mwaa.createEnvironment(r -> r
.name("my-environment")
.executionRoleArn("arn:aws:iam::000000000000:role/mwaa-role")
.sourceBucketArn("arn:aws:s3:::my-mwaa-bucket")
.dagS3Path("dags")
.networkConfiguration(n -> n
.subnetIds("subnet-1", "subnet-2")
.securityGroupIds("sg-1"))
.airflowVersion("2.10.5"));
// Get environment
GetEnvironmentResponse described = mwaa.getEnvironment(r -> r
.name("my-environment"));
System.out.println(described.environment().statusAsString()); // AVAILABLE
// List environments
List<String> names = mwaa.listEnvironments(r -> {}).environments();
// Tag resource
mwaa.tagResource(r -> r
.resourceArn(created.arn())
.tags(Map.of("team", "platform")));
// Delete environment
mwaa.deleteEnvironment(r -> r.name("my-environment"));
```
## Not Implemented
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.
- 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.
+1
View File
@@ -110,6 +110,7 @@ nav:
- ECR: services/ecr.md
- Resource Groups Tagging API: services/resource-groups-tagging.md
- EKS: services/eks.md
- MWAA: services/mwaa.md
- OpenSearch: services/opensearch.md
- EC2: services/ec2.md
- Lightsail: services/lightsail.md
@@ -563,6 +563,7 @@ public interface EmulatorConfig {
ResourceGroupsTaggingServiceConfig tagging();
BedrockRuntimeServiceConfig bedrockRuntime();
EksServiceConfig eks();
MwaaServiceConfig mwaa();
PipesServiceConfig pipes();
ElbV2ServiceConfig elbv2();
CodeBuildServiceConfig codebuild();
@@ -1551,6 +1552,60 @@ public interface EmulatorConfig {
boolean disableCni();
}
/**
* MWAA (Managed Workflows for Apache Airflow), backed by a real Apache Airflow instance
* (LocalExecutor) plus a dedicated Postgres metadata database, one pair of containers per
* environment. See {@code services/mwaa/MwaaEnvironmentManager}.
*/
interface MwaaServiceConfig {
@WithDefault("true")
boolean enabled();
/** When true, environments go straight to AVAILABLE without starting real Docker containers. */
@WithDefault("false")
boolean mock();
/** Image for the per-environment Postgres metadata database. Not shared with RDS's config knob. */
@WithDefault("postgres:16-alpine")
String defaultPostgresImage();
/** Airflow versions environments may request. Combined with the image tag
* {@code apache/airflow:<version>-python3.12}. */
@WithDefault("2.10.5,2.9.3,2.8.4")
List<String> supportedVersions();
/** Airflow version used when {@code CreateEnvironment} omits {@code AirflowVersion}. */
@WithDefault("2.10.5")
String defaultVersion();
/** Base port of the web/CLI proxy port range. First environment gets this port. */
@WithDefault("8700")
int proxyBasePort();
/** Inclusive upper bound of the proxy port range. */
@WithDefault("8799")
int proxyMaxPort();
@WithDefault("./data/mwaa")
String dataPath();
/** Docker network to attach the Postgres/Airflow containers to. Empty = default bridge. */
Optional<String> dockerNetwork();
@WithDefault("false")
boolean keepRunningOnShutdown();
/** Poll interval for syncing DAGs (and optionally requirements) from the environment's
* S3 {@code DagS3Path} into the Airflow container. */
@WithDefault("30")
int dagSyncIntervalSeconds();
/** When true, {@code RequirementsS3Path} is installed via {@code pip install -r} on create
* and on every DAG-sync pass in which the requirements file's ETag changed. */
@WithDefault("true")
boolean installRequirements();
}
interface InitHooksConfig {
@WithDefault("/bin/sh")
String shellExecutable();
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.bedrockruntime.BedrockRuntimeControll
import io.github.hectorvent.floci.services.cognito.CognitoOAuthController;
import io.github.hectorvent.floci.services.cognito.CognitoWellKnownController;
import io.github.hectorvent.floci.services.eks.EksController;
import io.github.hectorvent.floci.services.mwaa.MwaaController;
import io.github.hectorvent.floci.services.iot.IotController;
import io.github.hectorvent.floci.services.iot.IotDataController;
import io.github.hectorvent.floci.services.pipes.PipesController;
@@ -264,6 +265,17 @@ public class ResolvedServiceCatalog {
"eks", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("eks"), Set.of(), Set.of(EksController.class)),
descriptor("mwaa", "mwaa", config.services().mwaa().enabled(), true,
"mwaa", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(),
// Register both the signing name and the endpoint id. botocore's service
// model declares signingName=airflow for mwaa (endpointPrefix=airflow too);
// register the "mwaa" config/external key as well as a safety net, same
// double-registration technique as bedrock-runtime/bedrock above.
Set.of("airflow", "mwaa"),
Set.of(),
Set.of(MwaaController.class)),
descriptor("pipes", "pipes", config.services().pipes().enabled(), true,
"pipes", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
@@ -0,0 +1,88 @@
package io.github.hectorvent.floci.services.mwaa;
import io.github.hectorvent.floci.services.mwaa.model.CreateEnvironmentRequest;
import io.github.hectorvent.floci.services.mwaa.model.Environment;
import io.github.hectorvent.floci.services.mwaa.model.UpdateEnvironmentRequest;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
/**
* MWAA REST-JSON controller.
*
* <p>Like EKS, MWAA uses standard HTTP verbs with JSON bodies — not JSON 1.1 (X-Amz-Target)
* or Query protocol. Paths and verbs mirror the real MWAA API exactly (see botocore's
* {@code mwaa/2020-07-01/service-2.json}): {@code CreateEnvironment} is a {@code PUT}, not a
* {@code POST}, and {@code UpdateEnvironment} is a {@code PATCH}.
*/
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MwaaController {
private final MwaaService mwaaService;
@Inject
public MwaaController(MwaaService mwaaService) {
this.mwaaService = mwaaService;
}
@PUT
@Path("/environments/{name}")
public Response createEnvironment(@PathParam("name") String name, CreateEnvironmentRequest request) {
Environment environment = mwaaService.createEnvironment(name, request);
return Response.ok(Map.of("Arn", environment.getArn())).build();
}
@GET
@Path("/environments/{name}")
public Response getEnvironment(@PathParam("name") String name) {
Environment environment = mwaaService.getEnvironment(name);
return Response.ok(Map.of("Environment", environment)).build();
}
@GET
@Path("/environments")
public Response listEnvironments() {
List<String> names = mwaaService.listEnvironments();
return Response.ok(Map.of("Environments", names)).build();
}
@PATCH
@Path("/environments/{name}")
public Response updateEnvironment(@PathParam("name") String name, UpdateEnvironmentRequest request) {
Environment environment = mwaaService.updateEnvironment(name, request);
return Response.ok(Map.of("Arn", environment.getArn())).build();
}
@DELETE
@Path("/environments/{name}")
public Response deleteEnvironment(@PathParam("name") String name) {
mwaaService.deleteEnvironment(name);
return Response.ok(Map.of()).build();
}
@POST
@Path("/webtoken/{name}")
public Response createWebLoginToken(@PathParam("name") String name) {
return Response.ok(mwaaService.createWebLoginToken(name)).build();
}
@POST
@Path("/clitoken/{name}")
public Response createCliToken(@PathParam("name") String name) {
return Response.ok(mwaaService.createCliToken(name)).build();
}
}
@@ -0,0 +1,545 @@
package io.github.hectorvent.floci.services.mwaa;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.mwaa.model.Environment;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* Manages the Docker lifecycle of the Postgres + Apache Airflow container pair backing a real-mode
* MWAA environment. Not used when {@code floci.services.mwaa.mock=true}.
*
* <p>Neither container publishes a host port for the Postgres side — it is only ever reached by the
* sibling Airflow container, over the Docker network, so its address is resolved directly from the
* Docker daemon (container IP), the same way {@code EksClusterManager} avoids relying on
* container-name DNS on the default bridge network. The Airflow container, unlike Postgres, must
* also be reachable by Floci itself (the readiness poller and {@code MwaaWebProxy}'s relay target),
* so it follows the same host-port pattern as the Neptune/RDS backend containers: a dynamic host
* port when Floci runs natively, none when Floci itself runs inside Docker.
*/
@ApplicationScoped
public class MwaaEnvironmentManager {
private static final Logger LOG = Logger.getLogger(MwaaEnvironmentManager.class);
private static final int POSTGRES_PORT = 5432;
private static final int AIRFLOW_WEBSERVER_PORT = 8080;
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
* the Airflow web-UI admin login username configured via {@code _AIRFLOW_WWW_USER_USERNAME}. */
private static final String CONTAINER_OS_USER = "airflow";
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerDetector containerDetector;
private final EmulatorConfig config;
private final LaunchedContainerAwsEnv awsEnv;
@Inject
public MwaaEnvironmentManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerDetector containerDetector,
EmulatorConfig config,
LaunchedContainerAwsEnv awsEnv) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.containerDetector = containerDetector;
this.config = config;
this.awsEnv = awsEnv;
}
/**
* 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.
*
* @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
*/
public void startEnvironment(Environment environment, String airflowVersion, byte[] startupScriptContent) {
String name = environment.getName();
String dbPassword = generateSecret(24);
environment.setDbPassword(dbPassword);
String dbContainerName = dbContainerName(config, name);
String dbVolume = dbContainerName;
lifecycleManager.removeIfExists(dbContainerName);
lifecycleManager.ensureVolume(dbVolume);
ContainerSpec dbSpec = containerBuilder.newContainer(config.services().mwaa().defaultPostgresImage())
.withName(dbContainerName)
.withEnv(List.of(
"POSTGRES_USER=airflow",
"POSTGRES_PASSWORD=" + dbPassword,
"POSTGRES_DB=airflow"))
.withNamedVolume(dbVolume, "/var/lib/postgresql/data")
.withDockerNetwork(config.services().mwaa().dockerNetwork())
.withExposedPort(POSTGRES_PORT)
.withLogRotation()
.build();
String dbContainerId = lifecycleManager.create(dbSpec);
lifecycleManager.startCreated(dbContainerId, dbSpec);
environment.setDbContainerId(dbContainerId);
waitForPostgresReady(dbContainerId);
String dbIp = resolveContainerIp(dbContainerId, dbSpec.networkMode());
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);
}
// 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) {
String name = environment.getName();
String airflowContainerName = airflowContainerName(config, name);
String dagsVolume = airflowContainerName + "-dags";
String logsVolume = airflowContainerName + "-logs";
lifecycleManager.removeIfExists(airflowContainerName);
lifecycleManager.ensureVolume(dagsVolume);
lifecycleManager.ensureVolume(logsVolume);
String image = "apache/airflow:%s-python3.12".formatted(airflowVersion);
String adminUser = "admin";
String adminPassword = generateSecret(24);
String sqlAlchemyConn = "postgresql+psycopg2://airflow:" + 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
// boto3.client("s3") etc. would target real AWS instead of this emulator.
List<String> env = new ArrayList<>(awsEnv.sdkBaselineEnv(config.defaultRegion(), Optional.empty()));
env.addAll(List.of(
"AIRFLOW__CORE__EXECUTOR=LocalExecutor",
"AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=" + sqlAlchemyConn,
"AIRFLOW__CORE__SQL_ALCHEMY_CONN=" + sqlAlchemyConn,
"AIRFLOW__CORE__FERNET_KEY=" + generateFernetKey(),
"AIRFLOW__WEBSERVER__SECRET_KEY=" + generateSecret(32),
"AIRFLOW__CORE__LOAD_EXAMPLES=false",
"_AIRFLOW_WWW_USER_USERNAME=" + adminUser,
"_AIRFLOW_WWW_USER_PASSWORD=" + adminPassword));
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(airflowContainerName)
.withEnv(env)
// 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.
.withEntrypoint(List.of("sh", "-c"))
.withCmd(List.of(airflowBootstrapScript()))
.withNamedVolume(dagsVolume, DAGS_MOUNT)
.withNamedVolume(logsVolume, LOGS_MOUNT)
.withDockerNetwork(config.services().mwaa().dockerNetwork())
.withLogRotation();
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(AIRFLOW_WEBSERVER_PORT);
} else {
specBuilder.withExposedPort(AIRFLOW_WEBSERVER_PORT);
}
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
// registries.yaml/the webhook kubeconfig before the k3s container's entrypoint boots.
String containerId = lifecycleManager.create(spec);
ContainerInfo info;
try {
// Real MWAA documents startup scripts using "sudo yum install ..." as the baseline way
// to install OS packages — sudo is assumed to just work for the airflow user. The stock
// apache/airflow image ships sudo but requires a password, so without this grant every
// sudo line in a script copied from AWS's own docs would hang/fail. Granted unconditionally
// (not only when a startup script is configured), matching that it's a baseline capability
// of the environment on real MWAA, not something tied to having a script at all.
// Best-effort: absence of sudo access doesn't mean requested configuration was silently
// skipped, just that "sudo" lines in a startup script won't work.
copyFileIntoContainer(containerId, "/etc/sudoers.d", "floci-airflow-nopasswd",
(CONTAINER_OS_USER + " ALL=(ALL) NOPASSWD:ALL\n").getBytes(StandardCharsets.UTF_8));
if (startupScriptContent != null && startupScriptContent.length > 0) {
// Unlike the sudoers grant (best-effort infra) or DAG-file sync (a bad DAG must never
// fail the environment), a *configured* startup script is the user's explicit request —
// if injection fails, the entrypoint's "if [ -f /startup.sh ]" guard would just silently
// skip it and the environment would reach AVAILABLE without ever having applied the
// requested setup. Hard-fail instead, matching real MWAA gating environment creation on
// startup-script failure.
if (!copyFileIntoContainer(containerId, "/", "startup.sh", startupScriptContent)) {
throw new IllegalStateException(
"Could not inject the configured startup script into MWAA container "
+ containerId + " for environment " + environment.getName());
}
}
info = lifecycleManager.startCreated(containerId, spec);
} catch (Exception e) {
lifecycleManager.removeIfExists(containerId);
throw e;
}
environment.setAirflowContainerId(info.containerId());
ContainerLifecycleManager.EndpointInfo endpoint = info.getEndpoint(AIRFLOW_WEBSERVER_PORT);
if (endpoint != null) {
environment.setAirflowInternalHost(endpoint.host());
environment.setAirflowInternalPort(endpoint.port());
} else {
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()));
}
/**
* Polls the Airflow container's unauthenticated {@code /health} endpoint and requires both
* {@code metadatabase.status} and {@code scheduler.status} to be {@code "healthy"}.
*/
public boolean isReady(Environment environment) {
String host = environment.getAirflowInternalHost();
if (host == null || environment.getAirflowContainerId() == null) {
return false;
}
String url = "http://" + host + ":" + environment.getAirflowInternalPort() + "/health";
try {
HttpURLConnection conn = (HttpURLConnection) URI.create(url).toURL().openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(2000);
conn.setReadTimeout(2000);
if (conn.getResponseCode() != 200) {
return false;
}
String body;
try (var in = conn.getInputStream()) {
body = new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
return body.contains("\"metadatabase\"") && body.contains("\"scheduler\"")
&& healthySection(body, "metadatabase") && healthySection(body, "scheduler");
} catch (Exception e) {
return false;
}
}
/** Crude but dependency-free check for {@code "<section>":{"status":"healthy"...}} in the /health JSON. */
static boolean healthySection(String body, String section) {
int idx = body.indexOf("\"" + section + "\"");
if (idx < 0) {
return false;
}
int statusIdx = body.indexOf("\"status\"", idx);
if (statusIdx < 0) {
return false;
}
int healthyIdx = body.indexOf("\"healthy\"", statusIdx);
int nextSectionCommaIdx = body.indexOf("},", idx);
return healthyIdx >= 0 && (nextSectionCommaIdx < 0 || healthyIdx < nextSectionCommaIdx + 2);
}
/** Stops and removes both containers and all three named volumes for the given environment. */
public void stopEnvironment(Environment environment) {
if (config.services().mwaa().keepRunningOnShutdown()) {
LOG.infov("Leaving MWAA containers for environment {0} running", environment.getName());
return;
}
String name = environment.getName();
if (environment.getAirflowContainerId() != null) {
lifecycleManager.stopAndRemove(environment.getAirflowContainerId(), null);
}
if (environment.getDbContainerId() != null) {
lifecycleManager.stopAndRemove(environment.getDbContainerId(), null);
}
String airflowContainerName = airflowContainerName(config, name);
lifecycleManager.removeVolume(dbContainerName(config, name));
lifecycleManager.removeVolume(airflowContainerName + "-dags");
lifecycleManager.removeVolume(airflowContainerName + "-logs");
LOG.infov("Stopped MWAA containers for environment {0}", name);
}
/** Writes {@code content} to {@code DAGS_MOUNT/relativePath} inside the Airflow container. */
public void copyDagFile(Environment environment, String relativePath, byte[] content) {
copyFileIntoContainer(environment.getAirflowContainerId(), DAGS_MOUNT, relativePath, content);
}
/** Removes {@code DAGS_MOUNT/relativePath} from the Airflow container (best-effort). */
public void removeDagFile(Environment environment, String relativePath) {
try {
execInContainer(environment.getAirflowContainerId(), new String[]{"rm", "-f", DAGS_MOUNT + "/" + relativePath});
} catch (Exception e) {
LOG.warnv("Could not remove DAG {0} from environment {1}: {2}",
relativePath, environment.getName(), e.getMessage());
}
}
/** Writes requirements.txt into the container and runs {@code pip install -r} against it. */
public void installRequirements(Environment environment, byte[] requirementsContent) {
String containerId = environment.getAirflowContainerId();
if (containerId == null) {
return;
}
copyFileIntoContainer(containerId, "/tmp", "mwaa-requirements.txt", requirementsContent);
try {
ExecResult result = execInContainer(containerId,
new String[]{"pip", "install", "--no-cache-dir", "-r", "/tmp/mwaa-requirements.txt"});
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());
} else {
LOG.infov("Installed requirements.txt for MWAA environment {0}", environment.getName());
}
} catch (Exception e) {
LOG.warnv("Failed to install requirements for environment {0}: {1}", environment.getName(), e.getMessage());
}
}
/** Runs {@code airflow <cliCommand>} inside the Airflow container via {@code sh -c}. */
public ExecResult runAirflowCli(String airflowContainerId, String cliCommand) throws Exception {
return execInContainer(airflowContainerId, new String[]{"sh", "-c", "airflow " + cliCommand});
}
/** Routed through {@link ContainerStorageHelper} so multiple Floci instances sharing one Docker
* daemon (via {@code FLOCI_DOCKER_RESOURCE_NAMESPACE}) don't collide, same as every other
* Docker-backed service (EKS, RDS, ...). {@code config} may be {@code null} — the helper treats
* that as "no namespace configured" and returns the base name unchanged. */
static String dbContainerName(EmulatorConfig config, String environmentName) {
return ContainerStorageHelper.dockerName(config, "floci-mwaa-" + environmentName + "-db");
}
static String airflowContainerName(EmulatorConfig config, String environmentName) {
return ContainerStorageHelper.dockerName(config, "floci-mwaa-" + environmentName + "-airflow");
}
/**
* Environment variables a startup script must not be able to permanently override — mirrors
* real MWAA's documented "reserved environment variables" (which AWS silently restores after a
* startup script runs), scoped to the subset Floci itself configures and depends on: the
* LocalExecutor/DB/security wiring generated in {@link #startAirflowContainer}, plus the
* AWS-SDK-redirection vars from {@link LaunchedContainerAwsEnv} that this environment's own
* AWS-facing DAG code relies on to reach Floci instead of real AWS. Unlike AWS's full ~30-entry
* list, this omits Celery/StatsD-only vars Floci never sets — LocalExecutor has no broker, so
* there is nothing of Floci's there to protect.
*/
private static final List<String> PROTECTED_ENV_VARS = List.of(
"AIRFLOW__CORE__EXECUTOR",
"AIRFLOW__DATABASE__SQL_ALCHEMY_CONN",
"AIRFLOW__CORE__SQL_ALCHEMY_CONN",
"AIRFLOW__CORE__FERNET_KEY",
"AIRFLOW__WEBSERVER__SECRET_KEY",
"AIRFLOW__CORE__LOAD_EXAMPLES",
"AIRFLOW_HOME",
"AWS_DEFAULT_REGION",
"AWS_REGION",
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"AWS_ENDPOINT_URL",
"FLOCI_HOSTNAME",
"FLOCI_ENDPOINT");
/**
* Overridden ENTRYPOINT script: run the optional startup script (if {@code /startup.sh} was
* injected before the container started), migrate the metadata database, idempotently
* bootstrap the admin user from the stock {@code _AIRFLOW_WWW_USER_*} env var names,
* background the scheduler, then {@code exec} the webserver so it becomes PID 1.
*
* <p>The startup script is {@code .}-sourced (not run as a subshell) so any environment
* variables it exports — its documented purpose on real MWAA, mirroring
* {@code StartupScriptS3Path} — are visible to the migrate/scheduler/webserver steps that
* follow in the same shell. {@code || exit 1} converts a failing sourced script (one that
* doesn't itself call {@code exit}) into a hard stop of this whole entrypoint, so — matching
* real MWAA gating environment creation on startup-script failure — a broken startup script
* prevents Airflow from ever starting rather than being silently ignored.
*
* <p>{@link #PROTECTED_ENV_VARS} are snapshotted to {@code _FLOCI_ORIG_*} names before the
* script runs and re-exported from those snapshots immediately after, so a script that
* overwrites e.g. {@code AIRFLOW__CORE__FERNET_KEY} or {@code AWS_ENDPOINT_URL} — accidentally
* or otherwise — can't actually corrupt the environment Floci just set up, matching real MWAA
* restoring reserved variables to their managed values.
*
* <p>The migrate + user-create steps are joined with {@code &&} (each blocks until the
* previous succeeds) and only "airflow scheduler" is backgrounded with {@code &} — backgrounding
* the whole chain (as in {@code "migrate && scheduler & exec webserver"}) would let the webserver
* start racing the migration instead of after it, since {@code &} has lower precedence than
* {@code &&} and would apply to the entire left-hand chain.
*/
static String airflowBootstrapScript() {
String snapshot = PROTECTED_ENV_VARS.stream()
.map(v -> "_FLOCI_ORIG_" + v + "=\"$" + v + "\"")
.collect(Collectors.joining("\n", "", "\n"));
String restore = PROTECTED_ENV_VARS.stream()
.map(v -> "export " + v + "=\"$_FLOCI_ORIG_" + v + "\"")
.collect(Collectors.joining("\n", "", "\n"));
return snapshot
+ "if [ -f /startup.sh ]; then . /startup.sh || exit 1; fi\n"
+ restore
+ "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); "
+ "airflow scheduler & "
+ "exec airflow webserver";
}
private void waitForPostgresReady(String containerId) {
Exception last = null;
for (int attempt = 1; attempt <= 60; attempt++) {
try {
ExecResult result = execInContainer(containerId, new String[]{"pg_isready", "-U", "airflow"});
if (result.exitCode() == 0) {
return;
}
} catch (Exception e) {
last = e;
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted waiting for MWAA Postgres readiness", e);
}
}
throw new IllegalStateException("Timed out waiting for MWAA Postgres container " + containerId
+ " to become ready" + (last != null ? ": " + last.getMessage() : ""));
}
private String resolveContainerIp(String containerId, String preferredNetwork) {
InspectContainerResponse inspect = lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec();
Map<String, ContainerNetwork> networks = inspect.getNetworkSettings().getNetworks();
if (networks != null) {
if (preferredNetwork != null && networks.containsKey(preferredNetwork)) {
String ip = networks.get(preferredNetwork).getIpAddress();
if (ip != null && !ip.isBlank()) {
return ip;
}
}
for (ContainerNetwork net : networks.values()) {
if (net.getIpAddress() != null && !net.getIpAddress().isBlank()) {
return net.getIpAddress();
}
}
}
return inspect.getNetworkSettings().getIpAddress();
}
/**
* @return {@code true} on success, {@code false} on failure (logged as a warning either way).
* Callers for whom a missing file is tolerable (DAG sync, the sudoers grant) can ignore
* the result; callers for whom it isn't (the configured startup script) must check it.
*/
private boolean copyFileIntoContainer(String containerId, String remoteDir, String relativePath, byte[] content) {
if (containerId == null) {
return false;
}
try {
lifecycleManager.getDockerClient()
.copyArchiveToContainerCmd(containerId)
.withTarInputStream(new ByteArrayInputStream(tarSingleFile(relativePath, content)))
.withRemotePath(remoteDir)
.exec();
return true;
} catch (Exception e) {
LOG.warnv("Could not copy {0} into MWAA container {1}: {2}", relativePath, containerId, e.getMessage());
return false;
}
}
private static byte[] tarSingleFile(String entryName, byte[] content) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(out)) {
TarArchiveEntry entry = new TarArchiveEntry(entryName);
entry.setSize(content.length);
entry.setMode(0644);
tar.putArchiveEntry(entry);
tar.write(content);
tar.closeArchiveEntry();
}
return out.toByteArray();
} catch (IOException e) {
throw new IllegalStateException("Could not build in-memory tar for " + entryName, e);
}
}
ExecResult execInContainer(String containerId, String[] cmd) throws Exception {
var dockerClient = lifecycleManager.getDockerClient();
var exec = dockerClient.execCreateCmd(containerId)
.withCmd(cmd)
.withAttachStdout(true)
.withAttachStderr(true)
.exec();
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
boolean completed = dockerClient.execStartCmd(exec.getId())
.exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
if (frame.getStreamType() == StreamType.STDERR) {
stderr.writeBytes(frame.getPayload());
} else {
stdout.writeBytes(frame.getPayload());
}
}
})
.awaitCompletion(30, TimeUnit.SECONDS);
if (!completed) {
throw new RuntimeException("exec timed out in container " + containerId);
}
Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();
return new ExecResult(exitCode != null ? exitCode : -1,
stdout.toString(StandardCharsets.UTF_8), stderr.toString(StandardCharsets.UTF_8));
}
private static String generateSecret(int bytes) {
byte[] buf = new byte[bytes];
new SecureRandom().nextBytes(buf);
return Base64.getUrlEncoder().withoutPadding().encodeToString(buf);
}
/** A Fernet key must be 32 url-safe base64-encoded bytes (Airflow's {@code AIRFLOW__CORE__FERNET_KEY}). */
private static String generateFernetKey() {
byte[] buf = new byte[32];
new SecureRandom().nextBytes(buf);
return Base64.getUrlEncoder().encodeToString(buf);
}
public record ExecResult(long exitCode, String stdout, String stderr) {}
}
@@ -0,0 +1,542 @@
package io.github.hectorvent.floci.services.mwaa;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.TagHandler;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.mwaa.model.CreateEnvironmentRequest;
import io.github.hectorvent.floci.services.mwaa.model.Environment;
import io.github.hectorvent.floci.services.mwaa.model.EnvironmentStatus;
import io.github.hectorvent.floci.services.mwaa.model.UpdateEnvironmentRequest;
import io.github.hectorvent.floci.services.mwaa.proxy.MwaaProxyManager;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@ApplicationScoped
public class MwaaService implements TagHandler {
private static final Logger LOG = Logger.getLogger(MwaaService.class);
private final StorageBackend<String, Environment> storage;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final MwaaEnvironmentManager environmentManager;
private final MwaaProxyManager proxyManager;
private final PortAllocator portAllocator;
private final S3Service s3Service;
private final ScheduledExecutorService readinessPoller = Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService dagSyncPoller = Executors.newSingleThreadScheduledExecutor();
/** Opaque CLI tokens minted by CreateCliToken, per environment. In-memory only — not persisted. */
private final Map<String, Set<String>> cliTokensByEnvironment = new ConcurrentHashMap<>();
/** Last-synced DAG file state (S3 key relative to DagS3Path -> ETag), per environment. */
private final Map<String, Map<String, String>> dagSyncState = new ConcurrentHashMap<>();
/** Last-installed requirements.txt ETag, per environment. */
private final Map<String, String> requirementsEtagByEnvironment = new ConcurrentHashMap<>();
@Inject
public MwaaService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
MwaaEnvironmentManager environmentManager, MwaaProxyManager proxyManager,
PortAllocator portAllocator, S3Service s3Service) {
this.storage = storageFactory.create("mwaa", "mwaa-environments.json",
new TypeReference<Map<String, Environment>>() {
});
this.config = config;
this.regionResolver = regionResolver;
this.environmentManager = environmentManager;
this.proxyManager = proxyManager;
this.portAllocator = portAllocator;
this.s3Service = s3Service;
}
@PostConstruct
public void init() {
if (!config.services().mwaa().mock()) {
startReadinessPoller();
startDagSyncPoller();
}
}
@PreDestroy
public void shutdown() {
readinessPoller.shutdownNow();
dagSyncPoller.shutdownNow();
if (!config.services().mwaa().mock() && !config.services().mwaa().keepRunningOnShutdown()) {
for (Environment environment : allEnvironments()) {
proxyManager.stopProxy(environment.getName());
environmentManager.stopEnvironment(environment);
}
}
}
public Environment createEnvironment(String name, CreateEnvironmentRequest request) {
if (name == null || name.isBlank()) {
throw new AwsException("ValidationException", "Environment name is required", 400);
}
if (storage.get(name).isPresent()) {
// CreateEnvironment's botocore model declares only ServiceUnavailableException,
// ValidationException, and InternalServerException — no "already exists" shape — so an
// SDK client can't map a ResourceAlreadyExistsException here.
throw new AwsException("ValidationException",
"Environment already exists: " + name, 400);
}
String version = resolveAirflowVersion(request.getAirflowVersion());
String region = config.defaultRegion();
String accountId = regionResolver.getAccountId();
String arn = AwsArnUtils.Arn.of("airflow", region, accountId, "environment/" + name).toString();
Environment environment = new Environment();
environment.setName(name);
environment.setArn(arn);
environment.setAccountId(accountId);
environment.setCreatedAt(Instant.now());
environment.setStatus(EnvironmentStatus.CREATING);
environment.setExecutionRoleArn(request.getExecutionRoleArn());
environment.setAirflowVersion(version);
environment.setSourceBucketArn(request.getSourceBucketArn());
environment.setDagS3Path(request.getDagS3Path());
environment.setPluginsS3Path(request.getPluginsS3Path());
environment.setRequirementsS3Path(request.getRequirementsS3Path());
environment.setStartupScriptS3Path(request.getStartupScriptS3Path());
environment.setNetworkConfiguration(request.getNetworkConfiguration());
environment.setLoggingConfiguration(request.getLoggingConfiguration());
environment.setAirflowConfigurationOptions(request.getAirflowConfigurationOptions() != null
? new HashMap<>(request.getAirflowConfigurationOptions()) : new HashMap<>());
environment.setEnvironmentClass(request.getEnvironmentClass() != null ? request.getEnvironmentClass() : "mw1.small");
environment.setWebserverAccessMode(request.getWebserverAccessMode() != null
? request.getWebserverAccessMode() : "PUBLIC_ONLY");
environment.setMaxWorkers(request.getMaxWorkers() != null ? request.getMaxWorkers() : 10);
environment.setMinWorkers(request.getMinWorkers() != null ? request.getMinWorkers() : 1);
environment.setSchedulers(request.getSchedulers() != null ? request.getSchedulers() : 2);
environment.setTags(request.getTags() != null ? new HashMap<>(request.getTags()) : new HashMap<>());
if (config.services().mwaa().mock()) {
environment.setStatus(EnvironmentStatus.AVAILABLE);
environment.setWebserverUrl(buildWebserverUrl(config.services().mwaa().proxyBasePort()));
} else {
// proxyPort/provisioned tracked outside the try so the finally block below knows exactly
// how far setup got, mirroring NeptuneService.createDbCluster's rollback shape: a partial
// failure must never leak the reserved port or leave orphaned Postgres/Airflow containers
// behind — regardless of which of the three steps below actually failed.
int proxyPort = -1;
boolean provisioned = false;
try {
byte[] startupScriptContent = fetchStartupScript(environment);
environmentManager.startEnvironment(environment, version, startupScriptContent);
proxyPort = portAllocator.allocate(
config.services().mwaa().proxyBasePort(), config.services().mwaa().proxyMaxPort());
environment.setProxyPort(proxyPort);
environment.setWebserverUrl(buildWebserverUrl(proxyPort));
String airflowContainerId = environment.getAirflowContainerId();
proxyManager.startProxy(name, proxyPort,
environment.getAirflowInternalHost(), environment.getAirflowInternalPort(),
this::isValidCliToken,
cliCommand -> environmentManager.runAirflowCli(airflowContainerId, cliCommand));
provisioned = true;
} catch (Exception e) {
LOG.errorv(e, "Failed to start MWAA environment {0}", name);
environment.setStatus(EnvironmentStatus.CREATE_FAILED);
} finally {
if (!provisioned) {
rollbackFailedCreate(environment, proxyPort);
}
}
}
storage.put(name, environment);
return environment;
}
/**
* 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),
* stops any containers {@code environmentManager.startEnvironment} did manage to start before
* failing ({@link MwaaEnvironmentManager#stopEnvironment} null-checks each container id, so it's
* safe even when only Postgres — or nothing — started), and always releases the reserved proxy
* port. Mirrors {@code NeptuneService.rollbackDbCluster}.
*/
private void rollbackFailedCreate(Environment environment, int proxyPort) {
try {
proxyManager.stopProxy(environment.getName());
} catch (Exception e) {
LOG.warnv("Error stopping proxy while rolling back failed MWAA environment {0}: {1}",
environment.getName(), e.getMessage());
}
try {
environmentManager.stopEnvironment(environment);
} catch (Exception e) {
LOG.warnv("Error stopping containers while rolling back failed MWAA environment {0}: {1}",
environment.getName(), e.getMessage());
} finally {
if (proxyPort >= 0) {
portAllocator.release(proxyPort);
}
}
}
public Environment getEnvironment(String name) {
return storage.get(name)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No environment found for name: " + name, 404));
}
public List<String> listEnvironments() {
return storage.scan(k -> true).stream()
.map(Environment::getName)
.collect(Collectors.toList());
}
public Environment updateEnvironment(String name, UpdateEnvironmentRequest request) {
Environment environment = getEnvironment(name);
if (request.getAirflowVersion() != null && !request.getAirflowVersion().equals(environment.getAirflowVersion())) {
throw new AwsException("ValidationException",
"Updating AirflowVersion is not supported; it would require recreating the "
+ "environment's Airflow container. Delete and recreate the environment instead.", 400);
}
if (request.getAirflowConfigurationOptions() != null) {
throw new AwsException("ValidationException",
"Updating AirflowConfigurationOptions is not supported; it would require "
+ "recreating the environment's Airflow container.", 400);
}
if (request.getRequirementsS3Path() != null
&& !request.getRequirementsS3Path().equals(environment.getRequirementsS3Path())) {
throw new AwsException("ValidationException",
"Changing RequirementsS3Path via UpdateEnvironment is not supported; requirements "
+ "are re-installed automatically on the next DAG-sync pass when the file's "
+ "content changes at its existing path.", 400);
}
if (request.getStartupScriptS3Path() != null
&& !request.getStartupScriptS3Path().equals(environment.getStartupScriptS3Path())) {
throw new AwsException("ValidationException",
"Updating StartupScriptS3Path is not supported; it only runs once, at container "
+ "creation, so it would require recreating the environment's Airflow "
+ "container. Delete and recreate the environment instead.", 400);
}
if (request.getExecutionRoleArn() != null) {
environment.setExecutionRoleArn(request.getExecutionRoleArn());
}
if (request.getSourceBucketArn() != null) {
environment.setSourceBucketArn(request.getSourceBucketArn());
}
if (request.getDagS3Path() != null) {
environment.setDagS3Path(request.getDagS3Path());
}
if (request.getPluginsS3Path() != null) {
environment.setPluginsS3Path(request.getPluginsS3Path());
}
if (request.getNetworkConfiguration() != null) {
environment.setNetworkConfiguration(request.getNetworkConfiguration());
}
if (request.getLoggingConfiguration() != null) {
environment.setLoggingConfiguration(request.getLoggingConfiguration());
}
if (request.getEnvironmentClass() != null) {
environment.setEnvironmentClass(request.getEnvironmentClass());
}
if (request.getWebserverAccessMode() != null) {
environment.setWebserverAccessMode(request.getWebserverAccessMode());
}
if (request.getMaxWorkers() != null) {
environment.setMaxWorkers(request.getMaxWorkers());
}
if (request.getMinWorkers() != null) {
environment.setMinWorkers(request.getMinWorkers());
}
if (request.getSchedulers() != null) {
environment.setSchedulers(request.getSchedulers());
}
environment.setLastUpdate(new Environment.LastUpdate("SUCCESS", Instant.now()));
putEnvironment(environment);
return environment;
}
public Environment deleteEnvironment(String name) {
Environment environment = getEnvironment(name);
environment.setStatus(EnvironmentStatus.DELETING);
if (!config.services().mwaa().mock()) {
proxyManager.stopProxy(name);
environmentManager.stopEnvironment(environment);
// Mirrors how Lambda/MSK/EC2/ECR release their allocated ports on cleanup — otherwise
// repeated create/delete cycles exhaust the configured proxy port range even though no
// MWAA proxy is actually running anymore.
portAllocator.release(environment.getProxyPort());
}
cliTokensByEnvironment.remove(name);
dagSyncState.remove(name);
requirementsEtagByEnvironment.remove(name);
storage.delete(name);
return environment;
}
public Map<String, Object> createWebLoginToken(String name) {
Environment environment = getEnvironment(name);
String token = generateToken();
return Map.of(
"WebToken", token,
"WebServerHostname", hostnameFromUrl(environment.getWebserverUrl()),
"IamIdentity", "assumed-role/floci-local/user",
"AirflowIdentity", "admin");
}
public Map<String, Object> createCliToken(String name) {
Environment environment = getEnvironment(name);
String token = generateToken();
cliTokensByEnvironment.computeIfAbsent(name, k -> ConcurrentHashMap.newKeySet()).add(token);
return Map.of(
"CliToken", token,
"WebServerHostname", hostnameFromUrl(environment.getWebserverUrl()));
}
boolean isValidCliToken(String environmentName, String token) {
Set<String> tokens = cliTokensByEnvironment.get(environmentName);
return tokens != null && tokens.contains(token);
}
private String resolveAirflowVersion(String requested) {
List<String> supported = config.services().mwaa().supportedVersions();
String version = requested != null && !requested.isBlank() ? requested : config.services().mwaa().defaultVersion();
if (!supported.contains(version)) {
throw new AwsException("ValidationException",
"Unsupported AirflowVersion '" + version + "'. Supported versions: " + supported, 400);
}
return version;
}
private String buildWebserverUrl(int proxyPort) {
String scheme = config.tls().enabled() ? "https" : "http";
String host = config.hostname().orElse("localhost");
return scheme + "://" + host + ":" + proxyPort;
}
private static String hostnameFromUrl(String url) {
if (url == null) {
return "localhost";
}
String withoutScheme = url.replaceFirst("^[a-zA-Z]+://", "");
int slash = withoutScheme.indexOf('/');
return slash >= 0 ? withoutScheme.substring(0, slash) : withoutScheme;
}
private static String generateToken() {
byte[] buf = new byte[24];
new SecureRandom().nextBytes(buf);
return Base64.getUrlEncoder().withoutPadding().encodeToString(buf);
}
@Override
public String serviceKey() {
return "airflow";
}
@Override
public String tagsBodyKey() {
return "Tags";
}
@Override
public Map<String, String> listTags(String region, String resourceArn) {
Environment environment = findByArn(resourceArn);
return environment.getTags() != null ? environment.getTags() : Map.of();
}
@Override
public void tagResource(String region, String resourceArn, Map<String, String> tags) {
Environment environment = findByArn(resourceArn);
if (environment.getTags() == null) {
environment.setTags(new HashMap<>());
}
environment.getTags().putAll(tags);
putEnvironment(environment);
}
@Override
public void untagResource(String region, String resourceArn, List<String> tagKeys) {
Environment environment = findByArn(resourceArn);
if (environment.getTags() != null && tagKeys != null) {
tagKeys.forEach(environment.getTags()::remove);
}
putEnvironment(environment);
}
private Environment findByArn(String resourceArn) {
int idx = resourceArn.lastIndexOf('/');
if (idx < 0 || idx == resourceArn.length() - 1) {
throw new AwsException("ValidationException", "Invalid resource ARN: " + resourceArn, 400);
}
return getEnvironment(resourceArn.substring(idx + 1));
}
private void startReadinessPoller() {
readinessPoller.scheduleAtFixedRate(() -> {
try {
for (Environment environment : allEnvironments()) {
if (environment.getStatus() == EnvironmentStatus.CREATING
&& environmentManager.isReady(environment)) {
LOG.infov("MWAA environment {0} is now AVAILABLE", environment.getName());
environment.setStatus(EnvironmentStatus.AVAILABLE);
putEnvironment(environment);
}
}
} catch (Exception e) {
LOG.error("Error in MWAA readiness poller", e);
}
}, 2, 3, TimeUnit.SECONDS);
}
private void startDagSyncPoller() {
int intervalSeconds = Math.max(1, config.services().mwaa().dagSyncIntervalSeconds());
dagSyncPoller.scheduleAtFixedRate(() -> {
try {
for (Environment environment : allEnvironments()) {
if (environment.getStatus() != EnvironmentStatus.AVAILABLE) {
continue;
}
try {
syncDags(environment);
} catch (Exception e) {
// A bad/unsyncable DAG or S3 error must never fail the environment itself —
// only this poller pass for this one environment is affected.
LOG.warnv("DAG sync failed for MWAA environment {0}: {1}",
environment.getName(), e.getMessage());
}
}
} catch (Exception e) {
LOG.error("Error in MWAA DAG-sync poller", e);
}
}, intervalSeconds, intervalSeconds, TimeUnit.SECONDS);
}
private void syncDags(Environment environment) {
if (environment.getSourceBucketArn() == null || environment.getDagS3Path() == null) {
return;
}
String bucket = bucketNameFromArn(environment.getSourceBucketArn());
String prefix = environment.getDagS3Path().endsWith("/")
? environment.getDagS3Path() : environment.getDagS3Path() + "/";
List<S3Object> objects = s3Service.listObjects(bucket, prefix, null, 1000);
Map<String, String> currentByKey = new HashMap<>();
for (S3Object obj : objects) {
String relative = obj.getKey().substring(prefix.length());
if (relative.isBlank()) {
continue;
}
currentByKey.put(relative, obj.getETag());
}
Map<String, String> previous = dagSyncState.computeIfAbsent(environment.getName(), k -> new HashMap<>());
for (Map.Entry<String, String> entry : currentByKey.entrySet()) {
String relative = entry.getKey();
String etag = entry.getValue();
if (!etag.equals(previous.get(relative))) {
try {
S3Object obj = s3Service.getObject(bucket, prefix + relative);
environmentManager.copyDagFile(environment, relative, obj.getData());
} catch (Exception e) {
LOG.warnv("Skipping unsyncable DAG {0} for environment {1}: {2}",
relative, environment.getName(), e.getMessage());
}
}
}
for (String relative : new HashSet<>(previous.keySet())) {
if (!currentByKey.containsKey(relative)) {
environmentManager.removeDagFile(environment, relative);
}
}
previous.clear();
previous.putAll(currentByKey);
syncRequirementsIfNeeded(environment, bucket);
}
// 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.
private void syncRequirementsIfNeeded(Environment environment, String bucket) {
if (!config.services().mwaa().installRequirements() || environment.getRequirementsS3Path() == null) {
return;
}
try {
S3Object requirements = s3Service.getObject(bucket, environment.getRequirementsS3Path());
String lastEtag = requirementsEtagByEnvironment.get(environment.getName());
if (!requirements.getETag().equals(lastEtag)) {
environmentManager.installRequirements(environment, requirements.getData());
requirementsEtagByEnvironment.put(environment.getName(), requirements.getETag());
}
} catch (Exception e) {
LOG.warnv("Could not sync requirements.txt for environment {0}: {1}",
environment.getName(), e.getMessage());
}
}
// 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
// propagates and fails CreateEnvironment, matching real MWAA gating environment creation on
// a startup-script problem.
private byte[] fetchStartupScript(Environment environment) {
if (environment.getStartupScriptS3Path() == null) {
return null;
}
if (environment.getSourceBucketArn() == null) {
throw new AwsException("ValidationException",
"StartupScriptS3Path requires SourceBucketArn to be set", 400);
}
String bucket = bucketNameFromArn(environment.getSourceBucketArn());
return s3Service.getObject(bucket, environment.getStartupScriptS3Path()).getData();
}
private static String bucketNameFromArn(String sourceBucketArn) {
int idx = sourceBucketArn.lastIndexOf(':');
return idx >= 0 ? sourceBucketArn.substring(idx + 1) : sourceBucketArn;
}
private List<Environment> allEnvironments() {
if (storage instanceof AccountAwareStorageBackend<Environment> aware) {
return aware.scanAllAccounts();
}
return storage.scan(k -> true);
}
private void putEnvironment(Environment environment) {
if (environment.getAccountId() != null && storage instanceof AccountAwareStorageBackend<Environment> aware) {
aware.putForAccount(environment.getAccountId(), environment.getName(), environment);
} else {
storage.put(environment.getName(), environment);
}
}
}
@@ -0,0 +1,118 @@
package io.github.hectorvent.floci.services.mwaa.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class CreateEnvironmentRequest {
// Name is URI-bound in the real MWAA API (PUT /environments/{Name}); kept here only
// in case a caller also echoes it in the body, which is ignored in favor of the path param.
@JsonProperty("Name")
private String name;
@JsonProperty("ExecutionRoleArn")
private String executionRoleArn;
@JsonProperty("SourceBucketArn")
private String sourceBucketArn;
@JsonProperty("DagS3Path")
private String dagS3Path;
@JsonProperty("PluginsS3Path")
private String pluginsS3Path;
@JsonProperty("RequirementsS3Path")
private String requirementsS3Path;
@JsonProperty("StartupScriptS3Path")
private String startupScriptS3Path;
@JsonProperty("NetworkConfiguration")
private NetworkConfiguration networkConfiguration;
@JsonProperty("LoggingConfiguration")
private LoggingConfiguration loggingConfiguration;
@JsonProperty("AirflowConfigurationOptions")
private Map<String, String> airflowConfigurationOptions;
@JsonProperty("EnvironmentClass")
private String environmentClass;
@JsonProperty("AirflowVersion")
private String airflowVersion;
@JsonProperty("WebserverAccessMode")
private String webserverAccessMode;
@JsonProperty("MaxWorkers")
private Integer maxWorkers;
@JsonProperty("MinWorkers")
private Integer minWorkers;
@JsonProperty("Schedulers")
private Integer schedulers;
@JsonProperty("Tags")
private Map<String, String> tags;
public CreateEnvironmentRequest() {}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getExecutionRoleArn() { return executionRoleArn; }
public void setExecutionRoleArn(String executionRoleArn) { this.executionRoleArn = executionRoleArn; }
public String getSourceBucketArn() { return sourceBucketArn; }
public void setSourceBucketArn(String sourceBucketArn) { this.sourceBucketArn = sourceBucketArn; }
public String getDagS3Path() { return dagS3Path; }
public void setDagS3Path(String dagS3Path) { this.dagS3Path = dagS3Path; }
public String getPluginsS3Path() { return pluginsS3Path; }
public void setPluginsS3Path(String pluginsS3Path) { this.pluginsS3Path = pluginsS3Path; }
public String getRequirementsS3Path() { return requirementsS3Path; }
public void setRequirementsS3Path(String requirementsS3Path) { this.requirementsS3Path = requirementsS3Path; }
public String getStartupScriptS3Path() { return startupScriptS3Path; }
public void setStartupScriptS3Path(String startupScriptS3Path) { this.startupScriptS3Path = startupScriptS3Path; }
public NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; }
public void setNetworkConfiguration(NetworkConfiguration networkConfiguration) { this.networkConfiguration = networkConfiguration; }
public LoggingConfiguration getLoggingConfiguration() { return loggingConfiguration; }
public void setLoggingConfiguration(LoggingConfiguration loggingConfiguration) { this.loggingConfiguration = loggingConfiguration; }
public Map<String, String> getAirflowConfigurationOptions() { return airflowConfigurationOptions; }
public void setAirflowConfigurationOptions(Map<String, String> airflowConfigurationOptions) { this.airflowConfigurationOptions = airflowConfigurationOptions; }
public String getEnvironmentClass() { return environmentClass; }
public void setEnvironmentClass(String environmentClass) { this.environmentClass = environmentClass; }
public String getAirflowVersion() { return airflowVersion; }
public void setAirflowVersion(String airflowVersion) { this.airflowVersion = airflowVersion; }
public String getWebserverAccessMode() { return webserverAccessMode; }
public void setWebserverAccessMode(String webserverAccessMode) { this.webserverAccessMode = webserverAccessMode; }
public Integer getMaxWorkers() { return maxWorkers; }
public void setMaxWorkers(Integer maxWorkers) { this.maxWorkers = maxWorkers; }
public Integer getMinWorkers() { return minWorkers; }
public void setMinWorkers(Integer minWorkers) { this.minWorkers = minWorkers; }
public Integer getSchedulers() { return schedulers; }
public void setSchedulers(Integer schedulers) { this.schedulers = schedulers; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
}
@@ -0,0 +1,219 @@
package io.github.hectorvent.floci.services.mwaa.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class Environment {
@JsonProperty("Name")
private String name;
@JsonProperty("Arn")
private String arn;
@JsonProperty("CreatedAt")
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
private Instant createdAt;
@JsonProperty("LastUpdate")
private LastUpdate lastUpdate;
@JsonProperty("Status")
private EnvironmentStatus status;
@JsonProperty("ExecutionRoleArn")
private String executionRoleArn;
@JsonProperty("AirflowVersion")
private String airflowVersion;
@JsonProperty("SourceBucketArn")
private String sourceBucketArn;
@JsonProperty("DagS3Path")
private String dagS3Path;
@JsonProperty("PluginsS3Path")
private String pluginsS3Path;
@JsonProperty("RequirementsS3Path")
private String requirementsS3Path;
@JsonProperty("StartupScriptS3Path")
private String startupScriptS3Path;
@JsonProperty("NetworkConfiguration")
private NetworkConfiguration networkConfiguration;
@JsonProperty("LoggingConfiguration")
private LoggingConfiguration loggingConfiguration;
@JsonProperty("WebserverAccessMode")
private String webserverAccessMode;
@JsonProperty("WebserverUrl")
private String webserverUrl;
@JsonProperty("EnvironmentClass")
private String environmentClass;
@JsonProperty("AirflowConfigurationOptions")
private Map<String, String> airflowConfigurationOptions;
@JsonProperty("Tags")
private Map<String, String> tags;
// Echo-only fields for SDK compatibility; meaningless under LocalExecutor (single worker,
// no autoscaling), but round-tripped so SDKs/CLIs that read them back don't choke.
@JsonProperty("MaxWorkers")
private Integer maxWorkers;
@JsonProperty("MinWorkers")
private Integer minWorkers;
@JsonProperty("Schedulers")
private Integer schedulers;
@JsonIgnore
private String accountId;
@JsonIgnore
private String dbContainerId;
@JsonIgnore
private String airflowContainerId;
@JsonIgnore
private String airflowInternalHost;
@JsonIgnore
private int airflowInternalPort;
@JsonIgnore
private int proxyPort;
@JsonIgnore
private String dbPassword;
public Environment() {}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
public LastUpdate getLastUpdate() { return lastUpdate; }
public void setLastUpdate(LastUpdate lastUpdate) { this.lastUpdate = lastUpdate; }
public EnvironmentStatus getStatus() { return status; }
public void setStatus(EnvironmentStatus status) { this.status = status; }
public String getExecutionRoleArn() { return executionRoleArn; }
public void setExecutionRoleArn(String executionRoleArn) { this.executionRoleArn = executionRoleArn; }
public String getAirflowVersion() { return airflowVersion; }
public void setAirflowVersion(String airflowVersion) { this.airflowVersion = airflowVersion; }
public String getSourceBucketArn() { return sourceBucketArn; }
public void setSourceBucketArn(String sourceBucketArn) { this.sourceBucketArn = sourceBucketArn; }
public String getDagS3Path() { return dagS3Path; }
public void setDagS3Path(String dagS3Path) { this.dagS3Path = dagS3Path; }
public String getPluginsS3Path() { return pluginsS3Path; }
public void setPluginsS3Path(String pluginsS3Path) { this.pluginsS3Path = pluginsS3Path; }
public String getRequirementsS3Path() { return requirementsS3Path; }
public void setRequirementsS3Path(String requirementsS3Path) { this.requirementsS3Path = requirementsS3Path; }
public String getStartupScriptS3Path() { return startupScriptS3Path; }
public void setStartupScriptS3Path(String startupScriptS3Path) { this.startupScriptS3Path = startupScriptS3Path; }
public NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; }
public void setNetworkConfiguration(NetworkConfiguration networkConfiguration) { this.networkConfiguration = networkConfiguration; }
public LoggingConfiguration getLoggingConfiguration() { return loggingConfiguration; }
public void setLoggingConfiguration(LoggingConfiguration loggingConfiguration) { this.loggingConfiguration = loggingConfiguration; }
public String getWebserverAccessMode() { return webserverAccessMode; }
public void setWebserverAccessMode(String webserverAccessMode) { this.webserverAccessMode = webserverAccessMode; }
public String getWebserverUrl() { return webserverUrl; }
public void setWebserverUrl(String webserverUrl) { this.webserverUrl = webserverUrl; }
public String getEnvironmentClass() { return environmentClass; }
public void setEnvironmentClass(String environmentClass) { this.environmentClass = environmentClass; }
public Map<String, String> getAirflowConfigurationOptions() { return airflowConfigurationOptions; }
public void setAirflowConfigurationOptions(Map<String, String> airflowConfigurationOptions) { this.airflowConfigurationOptions = airflowConfigurationOptions; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public Integer getMaxWorkers() { return maxWorkers; }
public void setMaxWorkers(Integer maxWorkers) { this.maxWorkers = maxWorkers; }
public Integer getMinWorkers() { return minWorkers; }
public void setMinWorkers(Integer minWorkers) { this.minWorkers = minWorkers; }
public Integer getSchedulers() { return schedulers; }
public void setSchedulers(Integer schedulers) { this.schedulers = schedulers; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getDbContainerId() { return dbContainerId; }
public void setDbContainerId(String dbContainerId) { this.dbContainerId = dbContainerId; }
public String getAirflowContainerId() { return airflowContainerId; }
public void setAirflowContainerId(String airflowContainerId) { this.airflowContainerId = airflowContainerId; }
public String getAirflowInternalHost() { return airflowInternalHost; }
public void setAirflowInternalHost(String airflowInternalHost) { this.airflowInternalHost = airflowInternalHost; }
public int getAirflowInternalPort() { return airflowInternalPort; }
public void setAirflowInternalPort(int airflowInternalPort) { this.airflowInternalPort = airflowInternalPort; }
public int getProxyPort() { return proxyPort; }
public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; }
public String getDbPassword() { return dbPassword; }
public void setDbPassword(String dbPassword) { this.dbPassword = dbPassword; }
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class LastUpdate {
@JsonProperty("Status")
private String status;
@JsonProperty("CreatedAt")
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
private Instant createdAt;
public LastUpdate() {}
public LastUpdate(String status, Instant createdAt) {
this.status = status;
this.createdAt = createdAt;
}
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
}
}
@@ -0,0 +1,8 @@
package io.github.hectorvent.floci.services.mwaa.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public enum EnvironmentStatus {
CREATING, AVAILABLE, UPDATING, DELETING, DELETED, CREATE_FAILED, UPDATE_FAILED, UNAVAILABLE
}
@@ -0,0 +1,42 @@
package io.github.hectorvent.floci.services.mwaa.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class LoggingConfiguration {
@JsonProperty("DagProcessingLogs")
private ModuleLoggingConfiguration dagProcessingLogs;
@JsonProperty("SchedulerLogs")
private ModuleLoggingConfiguration schedulerLogs;
@JsonProperty("WebserverLogs")
private ModuleLoggingConfiguration webserverLogs;
@JsonProperty("WorkerLogs")
private ModuleLoggingConfiguration workerLogs;
@JsonProperty("TaskLogs")
private ModuleLoggingConfiguration taskLogs;
public LoggingConfiguration() {}
public ModuleLoggingConfiguration getDagProcessingLogs() { return dagProcessingLogs; }
public void setDagProcessingLogs(ModuleLoggingConfiguration dagProcessingLogs) { this.dagProcessingLogs = dagProcessingLogs; }
public ModuleLoggingConfiguration getSchedulerLogs() { return schedulerLogs; }
public void setSchedulerLogs(ModuleLoggingConfiguration schedulerLogs) { this.schedulerLogs = schedulerLogs; }
public ModuleLoggingConfiguration getWebserverLogs() { return webserverLogs; }
public void setWebserverLogs(ModuleLoggingConfiguration webserverLogs) { this.webserverLogs = webserverLogs; }
public ModuleLoggingConfiguration getWorkerLogs() { return workerLogs; }
public void setWorkerLogs(ModuleLoggingConfiguration workerLogs) { this.workerLogs = workerLogs; }
public ModuleLoggingConfiguration getTaskLogs() { return taskLogs; }
public void setTaskLogs(ModuleLoggingConfiguration taskLogs) { this.taskLogs = taskLogs; }
}
@@ -0,0 +1,30 @@
package io.github.hectorvent.floci.services.mwaa.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class ModuleLoggingConfiguration {
@JsonProperty("Enabled")
private Boolean enabled;
@JsonProperty("LogLevel")
private String logLevel;
@JsonProperty("CloudWatchLogGroupArn")
private String cloudWatchLogGroupArn;
public ModuleLoggingConfiguration() {}
public Boolean getEnabled() { return enabled; }
public void setEnabled(Boolean enabled) { this.enabled = enabled; }
public String getLogLevel() { return logLevel; }
public void setLogLevel(String logLevel) { this.logLevel = logLevel; }
public String getCloudWatchLogGroupArn() { return cloudWatchLogGroupArn; }
public void setCloudWatchLogGroupArn(String cloudWatchLogGroupArn) { this.cloudWatchLogGroupArn = cloudWatchLogGroupArn; }
}
@@ -0,0 +1,26 @@
package io.github.hectorvent.floci.services.mwaa.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class NetworkConfiguration {
@JsonProperty("SubnetIds")
private List<String> subnetIds;
@JsonProperty("SecurityGroupIds")
private List<String> securityGroupIds;
public NetworkConfiguration() {}
public List<String> getSubnetIds() { return subnetIds; }
public void setSubnetIds(List<String> subnetIds) { this.subnetIds = subnetIds; }
public List<String> getSecurityGroupIds() { return securityGroupIds; }
public void setSecurityGroupIds(List<String> securityGroupIds) { this.securityGroupIds = securityGroupIds; }
}
@@ -0,0 +1,104 @@
package io.github.hectorvent.floci.services.mwaa.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class UpdateEnvironmentRequest {
@JsonProperty("ExecutionRoleArn")
private String executionRoleArn;
@JsonProperty("SourceBucketArn")
private String sourceBucketArn;
@JsonProperty("DagS3Path")
private String dagS3Path;
@JsonProperty("PluginsS3Path")
private String pluginsS3Path;
@JsonProperty("RequirementsS3Path")
private String requirementsS3Path;
@JsonProperty("StartupScriptS3Path")
private String startupScriptS3Path;
@JsonProperty("NetworkConfiguration")
private NetworkConfiguration networkConfiguration;
@JsonProperty("LoggingConfiguration")
private LoggingConfiguration loggingConfiguration;
@JsonProperty("AirflowConfigurationOptions")
private Map<String, String> airflowConfigurationOptions;
@JsonProperty("EnvironmentClass")
private String environmentClass;
@JsonProperty("AirflowVersion")
private String airflowVersion;
@JsonProperty("WebserverAccessMode")
private String webserverAccessMode;
@JsonProperty("MaxWorkers")
private Integer maxWorkers;
@JsonProperty("MinWorkers")
private Integer minWorkers;
@JsonProperty("Schedulers")
private Integer schedulers;
public UpdateEnvironmentRequest() {}
public String getExecutionRoleArn() { return executionRoleArn; }
public void setExecutionRoleArn(String executionRoleArn) { this.executionRoleArn = executionRoleArn; }
public String getSourceBucketArn() { return sourceBucketArn; }
public void setSourceBucketArn(String sourceBucketArn) { this.sourceBucketArn = sourceBucketArn; }
public String getDagS3Path() { return dagS3Path; }
public void setDagS3Path(String dagS3Path) { this.dagS3Path = dagS3Path; }
public String getPluginsS3Path() { return pluginsS3Path; }
public void setPluginsS3Path(String pluginsS3Path) { this.pluginsS3Path = pluginsS3Path; }
public String getRequirementsS3Path() { return requirementsS3Path; }
public void setRequirementsS3Path(String requirementsS3Path) { this.requirementsS3Path = requirementsS3Path; }
public String getStartupScriptS3Path() { return startupScriptS3Path; }
public void setStartupScriptS3Path(String startupScriptS3Path) { this.startupScriptS3Path = startupScriptS3Path; }
public NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; }
public void setNetworkConfiguration(NetworkConfiguration networkConfiguration) { this.networkConfiguration = networkConfiguration; }
public LoggingConfiguration getLoggingConfiguration() { return loggingConfiguration; }
public void setLoggingConfiguration(LoggingConfiguration loggingConfiguration) { this.loggingConfiguration = loggingConfiguration; }
public Map<String, String> getAirflowConfigurationOptions() { return airflowConfigurationOptions; }
public void setAirflowConfigurationOptions(Map<String, String> airflowConfigurationOptions) { this.airflowConfigurationOptions = airflowConfigurationOptions; }
public String getEnvironmentClass() { return environmentClass; }
public void setEnvironmentClass(String environmentClass) { this.environmentClass = environmentClass; }
public String getAirflowVersion() { return airflowVersion; }
public void setAirflowVersion(String airflowVersion) { this.airflowVersion = airflowVersion; }
public String getWebserverAccessMode() { return webserverAccessMode; }
public void setWebserverAccessMode(String webserverAccessMode) { this.webserverAccessMode = webserverAccessMode; }
public Integer getMaxWorkers() { return maxWorkers; }
public void setMaxWorkers(Integer maxWorkers) { this.maxWorkers = maxWorkers; }
public Integer getMinWorkers() { return minWorkers; }
public void setMinWorkers(Integer minWorkers) { this.minWorkers = minWorkers; }
public Integer getSchedulers() { return schedulers; }
public void setSchedulers(Integer schedulers) { this.schedulers = schedulers; }
}
@@ -0,0 +1,53 @@
package io.github.hectorvent.floci.services.mwaa.proxy;
import io.vertx.core.Vertx;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.concurrent.ConcurrentHashMap;
/**
* Registry of all active {@link MwaaWebProxy} instances. One proxy per MWAA environment,
* started/stopped alongside the environment's containers. Mirrors {@code NeptuneProxyManager}.
*/
@ApplicationScoped
public class MwaaProxyManager {
private static final Logger LOG = Logger.getLogger(MwaaProxyManager.class);
private final Vertx vertx;
private final ConcurrentHashMap<String, MwaaWebProxy> proxies = new ConcurrentHashMap<>();
@Inject
public MwaaProxyManager(Vertx vertx) {
this.vertx = vertx;
}
public void startProxy(String environmentName, int proxyPort, String backendHost, int backendPort,
MwaaWebProxy.CliTokenValidator tokenValidator, MwaaWebProxy.CliExecutor cliExecutor) {
MwaaWebProxy proxy = new MwaaWebProxy(environmentName, vertx, backendHost, backendPort,
tokenValidator, cliExecutor);
try {
proxy.start(proxyPort);
proxies.put(environmentName, proxy);
} catch (Exception e) {
throw new RuntimeException("Failed to start MWAA web proxy for environment " + environmentName
+ " on port " + proxyPort, e);
}
}
public void stopProxy(String environmentName) {
MwaaWebProxy proxy = proxies.remove(environmentName);
if (proxy != null) {
proxy.stop();
LOG.infov("Stopped MWAA web proxy for environment {0}", environmentName);
}
}
public void stopAll() {
proxies.values().forEach(MwaaWebProxy::stop);
proxies.clear();
LOG.info("Stopped all MWAA web proxies");
}
}
@@ -0,0 +1,190 @@
package io.github.hectorvent.floci.services.mwaa.proxy;
import io.github.hectorvent.floci.services.mwaa.MwaaEnvironmentManager;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.RequestOptions;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* HTTP relay for a single MWAA environment's webserver traffic.
*
* <p>Every request is transparently forwarded to the backend Airflow container's internal
* {@code host:8080} and the response streamed back verbatim, using the same Vert.x
* {@code HttpClient}/{@code HttpServer} style as {@code ElbV2DataPlane} — except for
* {@code POST /aws_mwaa/cli}, which this proxy intercepts itself: it validates the
* {@code Authorization: Bearer <token>} header against the token(s) minted by
* {@code CreateCliToken} for this environment, then runs the request body (the raw Airflow CLI
* command, e.g. {@code "dags list"}) inside the Airflow container and returns the
* AWS-documented {@code {"stdout": "<base64>", "stderr": "<base64>"}} shape.
*/
public class MwaaWebProxy {
private static final Logger LOG = Logger.getLogger(MwaaWebProxy.class);
private static final String CLI_PATH = "/aws_mwaa/cli";
private static final List<String> HOP_BY_HOP_HEADERS = List.of(
"connection", "keep-alive", "transfer-encoding", "upgrade", "te", "trailers",
"proxy-authorization", "proxy-authenticate");
private final String environmentName;
private final Vertx vertx;
private final String backendHost;
private final int backendPort;
private final CliTokenValidator tokenValidator;
private final CliExecutor cliExecutor;
private HttpServer server;
private HttpClient client;
public MwaaWebProxy(String environmentName, Vertx vertx, String backendHost, int backendPort,
CliTokenValidator tokenValidator, CliExecutor cliExecutor) {
this.environmentName = environmentName;
this.vertx = vertx;
this.backendHost = backendHost;
this.backendPort = backendPort;
this.tokenValidator = tokenValidator;
this.cliExecutor = cliExecutor;
}
/** Starts listening on {@code proxyPort}, blocking until bound (or throwing on failure). */
public void start(int proxyPort) throws Exception {
client = vertx.createHttpClient(new HttpClientOptions()
.setConnectTimeout(5000)
.setKeepAlive(true));
server = vertx.createHttpServer(new HttpServerOptions()
.setHost("0.0.0.0")
.setPort(proxyPort));
server.requestHandler(this::handleRequest);
try {
server.listen().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
} catch (ExecutionException e) {
throw new IllegalStateException("Could not bind MWAA web proxy for environment "
+ environmentName + " on port " + proxyPort, e.getCause() != null ? e.getCause() : e);
} catch (TimeoutException e) {
throw new IllegalStateException("Timed out binding MWAA web proxy for environment "
+ environmentName + " on port " + proxyPort, e);
}
LOG.infov("MWAA web proxy started for environment {0} on port {1} -> {2}:{3}",
environmentName, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort));
}
public void stop() {
if (server != null) {
server.close();
}
if (client != null) {
client.close();
}
}
private void handleRequest(HttpServerRequest req) {
if (req.method() == HttpMethod.POST && CLI_PATH.equals(req.path())) {
handleCli(req);
} else {
forward(req);
}
}
private void handleCli(HttpServerRequest req) {
String token = extractBearerToken(req.getHeader("Authorization"));
if (token == null || !tokenValidator.isValid(environmentName, token)) {
req.response().setStatusCode(401)
.putHeader("Content-Type", "application/json")
.end("{\"message\":\"Missing or invalid CLI token\"}");
return;
}
req.bodyHandler(body -> {
String command = body.toString(StandardCharsets.UTF_8).trim();
try {
MwaaEnvironmentManager.ExecResult result = cliExecutor.execute(command);
String stdoutB64 = Base64.getEncoder().encodeToString(result.stdout().getBytes(StandardCharsets.UTF_8));
String stderrB64 = Base64.getEncoder().encodeToString(result.stderr().getBytes(StandardCharsets.UTF_8));
req.response()
.putHeader("Content-Type", "application/json")
.end("{\"stdout\":\"" + stdoutB64 + "\",\"stderr\":\"" + stderrB64 + "\"}");
} catch (Exception e) {
LOG.warnv("MWAA CLI exec failed for environment {0}: {1}", environmentName, e.getMessage());
req.response().setStatusCode(500)
.putHeader("Content-Type", "application/json")
.end("{\"message\":\"" + escapeJson(e.getMessage()) + "\"}");
}
});
}
private void forward(HttpServerRequest req) {
req.bodyHandler(body -> {
RequestOptions opts = new RequestOptions()
.setHost(backendHost)
.setPort(backendPort)
.setURI(req.uri())
.setMethod(req.method());
client.request(opts)
.onSuccess(clientReq -> {
req.headers().forEach(h -> {
if (!HOP_BY_HOP_HEADERS.contains(h.getKey().toLowerCase())) {
clientReq.putHeader(h.getKey(), h.getValue());
}
});
clientReq.putHeader("Host", backendHost + ":" + backendPort);
clientReq.send(body)
.onSuccess(resp -> {
req.response().setStatusCode(resp.statusCode());
resp.headers().forEach(h -> {
if (!HOP_BY_HOP_HEADERS.contains(h.getKey().toLowerCase())) {
req.response().putHeader(h.getKey(), h.getValue());
}
});
resp.body()
.onSuccess(req.response()::end)
.onFailure(err -> req.response().setStatusCode(502).end("Body error"));
})
.onFailure(err -> req.response().setStatusCode(502).end("Bad gateway"));
})
.onFailure(err -> req.response().setStatusCode(503).end("Service unavailable"));
});
}
static String extractBearerToken(String authorizationHeader) {
if (authorizationHeader == null) {
return null;
}
String prefix = "Bearer ";
if (!authorizationHeader.regionMatches(true, 0, prefix, 0, prefix.length())) {
return null;
}
String token = authorizationHeader.substring(prefix.length()).trim();
return token.isEmpty() ? null : token;
}
private static String escapeJson(String message) {
return message == null ? "" : message.replace("\\", "\\\\").replace("\"", "\\\"");
}
/** Determines which path/method combination is routed to the CLI handler. Used by tests. */
public static boolean isCliRequest(String method, String path) {
return "POST".equalsIgnoreCase(method) && CLI_PATH.equals(path);
}
@FunctionalInterface
public interface CliTokenValidator {
boolean isValid(String environmentName, String token);
}
@FunctionalInterface
public interface CliExecutor {
MwaaEnvironmentManager.ExecResult execute(String cliCommand) throws Exception;
}
}
+12
View File
@@ -379,6 +379,18 @@ floci:
iam-auth-webhook: true # wire a token-auth webhook into k3s so `aws eks get-token` works
ecr-registry-mirror: true # inject a registries.yaml so pods can pull images pushed to Floci ECR
disable-cni: false # start k3s without its bundled flannel/kube-proxy so a real CNI (e.g. Cilium) can take over
mwaa:
enabled: true
mock: false
default-postgres-image: "postgres:16-alpine"
supported-versions: "2.10.5,2.9.3,2.8.4"
default-version: "2.10.5"
proxy-base-port: 8700
proxy-max-port: 8799
data-path: ./data/mwaa
keep-running-on-shutdown: false
dag-sync-interval-seconds: 30
install-requirements: true
elbv2:
enabled: true
mock: false
@@ -0,0 +1,297 @@
package io.github.hectorvent.floci.services.mwaa;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.services.mwaa.model.Environment;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.model.Mount;
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.Mockito;
import java.util.List;
import java.util.Map;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class MwaaEnvironmentManagerTest {
private ContainerLifecycleManager lifecycleManager;
private ContainerDetector containerDetector;
private MwaaEnvironmentManager manager;
@BeforeEach
void setUp() {
EmulatorConfig.DockerConfig dockerConfig = Mockito.mock(EmulatorConfig.DockerConfig.class);
when(dockerConfig.imageRegistryBase()).thenReturn(Optional.empty());
when(dockerConfig.logMaxSize()).thenReturn("10m");
when(dockerConfig.logMaxFile()).thenReturn("3");
EmulatorConfig.MwaaServiceConfig mwaaConfig = Mockito.mock(EmulatorConfig.MwaaServiceConfig.class);
when(mwaaConfig.dockerNetwork()).thenReturn(Optional.empty());
when(mwaaConfig.defaultPostgresImage()).thenReturn("postgres:16-alpine");
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
when(servicesConfig.mwaa()).thenReturn(mwaaConfig);
when(servicesConfig.dockerNetwork()).thenReturn(Optional.empty());
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
when(config.docker()).thenReturn(dockerConfig);
when(config.services()).thenReturn(servicesConfig);
when(config.defaultRegion()).thenReturn("us-east-1");
DockerHostResolver dockerHostResolver = Mockito.mock(DockerHostResolver.class);
EmbeddedDnsServer embeddedDnsServer = Mockito.mock(EmbeddedDnsServer.class);
when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty());
ContainerBuilder containerBuilder = new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer);
lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
containerDetector = Mockito.mock(ContainerDetector.class);
LaunchedContainerAwsEnv awsEnv = Mockito.mock(LaunchedContainerAwsEnv.class);
when(awsEnv.sdkBaselineEnv(eq("us-east-1"), any())).thenReturn(List.of(
"AWS_DEFAULT_REGION=us-east-1",
"AWS_ACCESS_KEY_ID=test",
"AWS_SECRET_ACCESS_KEY=test",
"AWS_ENDPOINT_URL=http://localhost:4566"));
manager = new MwaaEnvironmentManager(containerBuilder, lifecycleManager, containerDetector, config, awsEnv);
}
@SuppressWarnings("unchecked")
private ContainerSpec startAirflowAndCaptureSpec(boolean runningInContainer) {
return startAirflowAndCaptureSpec(runningInContainer, null);
}
@SuppressWarnings("unchecked")
private ContainerSpec startAirflowAndCaptureSpec(boolean runningInContainer, byte[] startupScriptContent) {
when(containerDetector.isRunningInContainer()).thenReturn(runningInContainer);
when(lifecycleManager.create(any())).thenReturn("airflow-container-id");
ContainerInfo info = new ContainerInfo("airflow-container-id",
Map.of(8080, new EndpointInfo("172.18.0.5", 8080)));
when(lifecycleManager.startCreated(eq("airflow-container-id"), any())).thenReturn(info);
Environment environment = new Environment();
environment.setName("my-env");
manager.startAirflowContainer(environment, "2.10.5", "172.18.0.9", "db-secret-pw", startupScriptContent);
ArgumentCaptor<ContainerSpec> captor = ArgumentCaptor.forClass(ContainerSpec.class);
Mockito.verify(lifecycleManager).create(captor.capture());
Mockito.verify(lifecycleManager).startCreated(eq("airflow-container-id"), any());
assertEquals("airflow-container-id", environment.getAirflowContainerId());
assertEquals("172.18.0.5", environment.getAirflowInternalHost());
assertEquals(8080, environment.getAirflowInternalPort());
return captor.getValue();
}
@Test
void airflowImageTagSubstitutesTheRequestedVersion() {
ContainerSpec spec = startAirflowAndCaptureSpec(false);
assertEquals("apache/airflow:2.10.5-python3.12", spec.image());
}
@Test
void airflowEnvVarsWireTheResolvedPostgresDsn() {
ContainerSpec spec = startAirflowAndCaptureSpec(false);
assertTrue(spec.env().contains("AIRFLOW__CORE__EXECUTOR=LocalExecutor"));
assertTrue(spec.env().contains("AIRFLOW__CORE__LOAD_EXAMPLES=false"));
assertTrue(spec.env().stream().anyMatch(e -> e.startsWith("AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=")
&& e.contains("172.18.0.9") && e.contains("db-secret-pw")));
assertTrue(spec.env().stream().anyMatch(e -> e.startsWith("AIRFLOW__CORE__FERNET_KEY=")));
assertTrue(spec.env().stream().anyMatch(e -> e.startsWith("AIRFLOW__WEBSERVER__SECRET_KEY=")));
assertTrue(spec.env().stream().anyMatch(e -> e.startsWith("_AIRFLOW_WWW_USER_USERNAME=")));
assertTrue(spec.env().stream().anyMatch(e -> e.startsWith("_AIRFLOW_WWW_USER_PASSWORD=")));
}
@Test
void airflowContainerGetsPointedBackAtFlociForItsOwnAwsSdkCalls() {
ContainerSpec spec = startAirflowAndCaptureSpec(false);
assertTrue(spec.env().contains("AWS_ENDPOINT_URL=http://localhost:4566"),
"DAG code's own boto3 calls must target Floci, not real AWS");
assertTrue(spec.env().contains("AWS_DEFAULT_REGION=us-east-1"));
}
@Test
void entrypointAndCmdOverrideTheStockImageDefaults() {
ContainerSpec spec = startAirflowAndCaptureSpec(false);
assertEquals(List.of("sh", "-c"), spec.entrypoint());
assertEquals(1, spec.cmd().size());
String script = spec.cmd().get(0);
assertTrue(script.contains("airflow db migrate"));
assertTrue(script.contains("airflow users create"));
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.
assertTrue(script.indexOf("airflow db migrate") < script.indexOf("airflow scheduler &"));
}
@Test
void bootstrapScriptSourcesAnOptionalStartupScriptBeforeMigrating() {
ContainerSpec spec = startAirflowAndCaptureSpec(false);
String script = spec.cmd().get(0);
assertTrue(script.contains("if [ -f /startup.sh ]; then . /startup.sh || exit 1; fi"));
assertTrue(script.indexOf("/startup.sh") < script.indexOf("airflow db migrate"),
"the startup script must run before migration, matching real MWAA's ordering");
}
// Coverage for supplying startup-script bytes now lives in the ContainerFileInjection nested
// class below, where the DockerClient is actually mocked — the copy must succeed for the
// create -> inject -> start sequence to continue (see startupScriptInjectionFailurePreventsThe-
// ContainerFromStarting for the failure path this class didn't previously test).
@Test
void namedVolumesMountDagsAndLogs() {
ContainerSpec spec = startAirflowAndCaptureSpec(false);
List<String> targets = spec.mounts().stream().map(Mount::getTarget).toList();
assertTrue(targets.contains("/opt/airflow/dags"));
assertTrue(targets.contains("/opt/airflow/logs"));
assertTrue(spec.mounts().stream().map(Mount::getSource).anyMatch(s -> s.endsWith("-dags")));
assertTrue(spec.mounts().stream().map(Mount::getSource).anyMatch(s -> s.endsWith("-logs")));
}
@Test
void nativeModeAllocatesADynamicHostPortForTheWebserver() {
ContainerSpec spec = startAirflowAndCaptureSpec(false);
assertTrue(spec.exposedPorts().contains(8080));
assertTrue(spec.portBindings().containsKey(8080));
assertEquals(0, spec.portBindings().get(8080), "0 is the dynamic-allocation sentinel");
}
@Test
void containerModePublishesNoHostPortForTheWebserver() {
ContainerSpec spec = startAirflowAndCaptureSpec(true);
assertTrue(spec.exposedPorts().contains(8080));
assertFalse(spec.portBindings().containsKey(8080));
}
@Test
void containerNamingMatchesThePlan() {
assertEquals("floci-mwaa-my-env-db", MwaaEnvironmentManager.dbContainerName(null, "my-env"));
assertEquals("floci-mwaa-my-env-airflow", MwaaEnvironmentManager.airflowContainerName(null, "my-env"));
}
@Test
void containerNamingAppliesTheConfiguredResourceNamespace() {
EmulatorConfig.DockerConfig dockerConfig = Mockito.mock(EmulatorConfig.DockerConfig.class);
when(dockerConfig.resourceNamespace()).thenReturn(Optional.of("ns1"));
EmulatorConfig namespacedConfig = Mockito.mock(EmulatorConfig.class);
when(namespacedConfig.docker()).thenReturn(dockerConfig);
assertEquals("floci-ns1-mwaa-my-env-db",
MwaaEnvironmentManager.dbContainerName(namespacedConfig, "my-env"));
assertEquals("floci-ns1-mwaa-my-env-airflow",
MwaaEnvironmentManager.airflowContainerName(namespacedConfig, "my-env"));
}
@Test
void healthCheckRequiresBothMetadatabaseAndSchedulerHealthy() {
String bothHealthy = "{\"metadatabase\":{\"status\":\"healthy\"},\"scheduler\":{\"status\":\"healthy\"}}";
assertTrue(MwaaEnvironmentManager.healthySection(bothHealthy, "metadatabase"));
assertTrue(MwaaEnvironmentManager.healthySection(bothHealthy, "scheduler"));
String schedulerUnhealthy = "{\"metadatabase\":{\"status\":\"healthy\"},\"scheduler\":{\"status\":\"unhealthy\"}}";
assertTrue(MwaaEnvironmentManager.healthySection(schedulerUnhealthy, "metadatabase"));
assertFalse(MwaaEnvironmentManager.healthySection(schedulerUnhealthy, "scheduler"));
}
@Test
void bootstrapScriptSnapshotsAndRestoresProtectedVarsAroundTheStartupScript() {
String script = MwaaEnvironmentManager.airflowBootstrapScript();
int snapshotIdx = script.indexOf("_FLOCI_ORIG_AIRFLOW__CORE__FERNET_KEY=\"$AIRFLOW__CORE__FERNET_KEY\"");
int startupIdx = script.indexOf("/startup.sh");
int restoreIdx = script.indexOf("export AIRFLOW__CORE__FERNET_KEY=\"$_FLOCI_ORIG_AIRFLOW__CORE__FERNET_KEY\"");
assertTrue(snapshotIdx >= 0, "must snapshot the original value before the startup script can touch it");
assertTrue(restoreIdx >= 0, "must re-export the snapshotted value after the startup script runs");
assertTrue(snapshotIdx < startupIdx && startupIdx < restoreIdx,
"ordering must be snapshot -> startup script -> restore, so an override can't survive");
// Spot-check a Floci-specific (non-AWS-reserved) var too, since a script accidentally
// clobbering AWS_ENDPOINT_URL would break the AWS-SDK-redirection this environment depends on.
assertTrue(script.contains("_FLOCI_ORIG_AWS_ENDPOINT_URL=\"$AWS_ENDPOINT_URL\""));
assertTrue(script.contains("export AWS_ENDPOINT_URL=\"$_FLOCI_ORIG_AWS_ENDPOINT_URL\""));
}
/** Sudoers-grant and startup-script injection, verified against a mocked DockerClient — mirrors
* EksClusterManagerTest's InjectEcrRegistryMirror nested class for the same kind of assertion. */
@Nested
class ContainerFileInjection {
private DockerClient dockerClient;
private CopyArchiveToContainerCmd copyCmd;
@BeforeEach
void setUpDockerClient() {
dockerClient = Mockito.mock(DockerClient.class);
copyCmd = Mockito.mock(CopyArchiveToContainerCmd.class, Mockito.RETURNS_SELF);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.copyArchiveToContainerCmd(anyString())).thenReturn(copyCmd);
}
@Test
void sudoersGrantIsAlwaysInjectedEvenWithoutAStartupScript() {
startAirflowAndCaptureSpec(false, null);
verify(copyCmd).withRemotePath("/etc/sudoers.d");
verify(copyCmd, times(1)).exec();
}
@Test
void startupScriptIsInjectedInAdditionToTheSudoersGrantWhenProvided() {
startAirflowAndCaptureSpec(false, "export FOO=bar\n".getBytes());
verify(copyCmd).withRemotePath("/etc/sudoers.d");
verify(copyCmd).withRemotePath("/");
verify(copyCmd, times(2)).exec();
}
@Test
void startupScriptInjectionFailurePreventsTheContainerFromStarting() {
// Shared copyCmd mock, so this also makes the (best-effort) sudoers-grant copy fail —
// that alone must not abort anything; only the configured-startup-script failure should.
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", "export FOO=bar\n".getBytes()));
verify(lifecycleManager).removeIfExists("airflow-container-id");
verify(lifecycleManager, never()).startCreated(anyString(), any());
}
}
}
@@ -0,0 +1,195 @@
package io.github.hectorvent.floci.services.mwaa;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* MWAA REST flow against {@code floci.services.mwaa.mock=true} (see test {@code application.yml}),
* so no Docker daemon is touched. Mirrors {@code EksNodegroupIntegrationTest}'s style: real HTTP
* calls via RestAssured, ordered because environment state carries across tests.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class MwaaIntegrationTest {
private static final String JSON = "application/json";
private static final String ENV = "mwaa-it-env";
private static String createBody(String extraFields) {
return "{\"ExecutionRoleArn\":\"arn:aws:iam::000000000000:role/mwaa-execution-role\","
+ "\"SourceBucketArn\":\"arn:aws:s3:::mwaa-it-bucket\","
+ "\"DagS3Path\":\"dags\","
+ "\"NetworkConfiguration\":{\"SubnetIds\":[\"subnet-1\",\"subnet-2\"],\"SecurityGroupIds\":[\"sg-1\"]}"
+ (extraFields != null ? "," + extraFields : "")
+ "}";
}
@Test
@Order(1)
void createEnvironment() {
given().contentType(JSON)
.body(createBody(null))
.when().put("/environments/" + ENV)
.then().statusCode(200)
.body("Arn", containsString("environment/" + ENV))
.body("Arn", containsString(":airflow:"));
}
@Test
@Order(2)
void getEnvironmentReturnsDefaultsAndAvailableStatus() {
given().contentType(JSON)
.when().get("/environments/" + ENV)
.then().statusCode(200)
.body("Environment.Name", equalTo(ENV))
.body("Environment.Status", equalTo("AVAILABLE"))
.body("Environment.AirflowVersion", equalTo("2.10.5"))
.body("Environment.WebserverUrl", notNullValue())
.body("Environment.NetworkConfiguration.SubnetIds", hasItem("subnet-1"));
}
@Test
@Order(3)
void createEnvironmentDuplicateFails() {
given().contentType(JSON)
.body(createBody(null))
.when().put("/environments/" + ENV)
.then().statusCode(400);
}
@Test
@Order(4)
void listEnvironmentsIncludesCreatedEnvironment() {
given().contentType(JSON)
.when().get("/environments")
.then().statusCode(200)
.body("Environments", hasItem(ENV));
}
@Test
@Order(5)
void updateEnvironmentAppliesMetadataOnlyChange() {
given().contentType(JSON)
.body("{\"EnvironmentClass\":\"mw1.large\"}")
.when().patch("/environments/" + ENV)
.then().statusCode(200)
.body("Arn", containsString("environment/" + ENV));
given().contentType(JSON)
.when().get("/environments/" + ENV)
.then().statusCode(200)
.body("Environment.EnvironmentClass", equalTo("mw1.large"));
}
@Test
@Order(6)
void updateEnvironmentRejectsAirflowVersionChange() {
given().contentType(JSON)
.body("{\"AirflowVersion\":\"2.9.3\"}")
.when().patch("/environments/" + ENV)
.then().statusCode(400);
}
@Test
@Order(7)
void tagResourceUntagResourceAndListTagsForResourceRoundTrip() {
String arn = given().contentType(JSON)
.when().get("/environments/" + ENV)
.then().statusCode(200)
.extract().path("Environment.Arn");
given().contentType(JSON)
.body("{\"Tags\":{\"team\":\"data\",\"env\":\"test\"}}")
.when().post("/tags/" + arn)
.then().statusCode(204);
given().contentType(JSON)
.when().get("/tags/" + arn)
.then().statusCode(200)
.body("Tags.team", equalTo("data"))
.body("Tags.env", equalTo("test"));
given().contentType(JSON)
.when().delete("/tags/" + arn + "?tagKeys=env")
.then().statusCode(204);
given().contentType(JSON)
.when().get("/tags/" + arn)
.then().statusCode(200)
.body("Tags.team", equalTo("data"))
.body("Tags.env", nullValue());
}
@Test
@Order(8)
void createWebLoginTokenAndCliTokenReturnOpaqueTokens() {
given().contentType(JSON)
.when().post("/webtoken/" + ENV)
.then().statusCode(200)
.body("WebToken", notNullValue())
.body("WebServerHostname", notNullValue());
given().contentType(JSON)
.when().post("/clitoken/" + ENV)
.then().statusCode(200)
.body("CliToken", notNullValue())
.body("WebServerHostname", notNullValue());
}
@Test
@Order(9)
void deleteEnvironment() {
given().contentType(JSON)
.when().delete("/environments/" + ENV)
.then().statusCode(200);
given().contentType(JSON)
.when().get("/environments/" + ENV)
.then().statusCode(404);
}
@Test
@Order(10)
void everySupportedAirflowVersionRoundTrips() {
String[] versions = {"2.10.5", "2.9.3", "2.8.4"};
for (String version : versions) {
String name = "mwaa-it-v" + version.replace(".", "");
given().contentType(JSON)
.body(createBody("\"AirflowVersion\":\"" + version + "\""))
.when().put("/environments/" + name)
.then().statusCode(200);
given().contentType(JSON)
.when().get("/environments/" + name)
.then().statusCode(200)
.body("Environment.AirflowVersion", equalTo(version));
given().contentType(JSON)
.when().delete("/environments/" + name)
.then().statusCode(200);
}
}
@Test
@Order(11)
void unsupportedAirflowVersionIsRejected() {
given().contentType(JSON)
.body(createBody("\"AirflowVersion\":\"1.10.15\""))
.when().put("/environments/mwaa-it-bad-version")
.then().statusCode(400);
given().contentType(JSON)
.when().get("/environments/mwaa-it-bad-version")
.then().statusCode(404);
}
}
@@ -0,0 +1,404 @@
package io.github.hectorvent.floci.services.mwaa;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.mwaa.model.CreateEnvironmentRequest;
import io.github.hectorvent.floci.services.mwaa.model.Environment;
import io.github.hectorvent.floci.services.mwaa.model.EnvironmentStatus;
import io.github.hectorvent.floci.services.mwaa.model.NetworkConfiguration;
import io.github.hectorvent.floci.services.mwaa.model.UpdateEnvironmentRequest;
import io.github.hectorvent.floci.services.mwaa.proxy.MwaaProxyManager;
import io.github.hectorvent.floci.services.s3.S3Service;
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Map;
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.assertNotNull;
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.Mockito.verify;
import static org.mockito.Mockito.when;
class MwaaServiceTest {
private MwaaService mwaaService;
@BeforeEach
void setUp() {
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return new InMemoryStorage<>();
}
};
EmulatorConfig config = testConfig();
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
S3Service s3Service = Mockito.mock(S3Service.class);
mwaaService = new MwaaService(storageFactory, config, regionResolver, null, null, null, s3Service);
}
private EmulatorConfig testConfig() {
EmulatorConfig.MwaaServiceConfig mwaaConfig = proxy(EmulatorConfig.MwaaServiceConfig.class,
(proxy, method, args) -> switch (method.getName()) {
case "enabled", "mock" -> true;
case "supportedVersions" -> List.of("2.10.5", "2.9.3", "2.8.4");
case "defaultVersion" -> "2.10.5";
case "proxyBasePort" -> 8700;
case "proxyMaxPort" -> 8799;
case "dagSyncIntervalSeconds" -> 30;
default -> defaultValue(method);
});
EmulatorConfig.ServicesConfig servicesConfig = proxy(EmulatorConfig.ServicesConfig.class,
(proxy, method, args) -> switch (method.getName()) {
case "mwaa" -> mwaaConfig;
default -> defaultValue(method);
});
EmulatorConfig.TlsConfig tlsConfig = proxy(EmulatorConfig.TlsConfig.class,
(proxy, method, args) -> defaultValue(method));
return proxy(EmulatorConfig.class, (proxy, method, args) -> switch (method.getName()) {
case "services" -> servicesConfig;
case "tls" -> tlsConfig;
case "defaultRegion" -> "us-east-1";
case "defaultAccountId" -> "000000000000";
case "hostname" -> Optional.empty();
default -> defaultValue(method);
});
}
@SuppressWarnings("unchecked")
private <T> T proxy(Class<T> type, InvocationHandler handler) {
return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] { type }, (proxy, method, args) -> {
if (method.getDeclaringClass() == Object.class) {
return switch (method.getName()) {
case "toString" -> type.getSimpleName() + "TestProxy";
case "hashCode" -> System.identityHashCode(proxy);
case "equals" -> proxy == args[0];
default -> method.invoke(this, args);
};
}
return handler.invoke(proxy, method, args);
});
}
private Object defaultValue(Method method) {
Class<?> returnType = method.getReturnType();
if (returnType == boolean.class) {
return false;
}
if (returnType == int.class) {
return 0;
}
if (returnType == long.class) {
return 0L;
}
if (returnType == Optional.class) {
return Optional.empty();
}
if (returnType == String.class) {
return "";
}
if (returnType == List.class) {
return List.of();
}
return null;
}
private CreateEnvironmentRequest createRequest(String bucketArn, String dagPath) {
CreateEnvironmentRequest request = new CreateEnvironmentRequest();
request.setExecutionRoleArn("arn:aws:iam::000000000000:role/mwaa-execution-role");
request.setSourceBucketArn(bucketArn);
request.setDagS3Path(dagPath);
NetworkConfiguration network = new NetworkConfiguration();
network.setSubnetIds(List.of("subnet-1", "subnet-2"));
network.setSecurityGroupIds(List.of("sg-1"));
request.setNetworkConfiguration(network);
return request;
}
@Test
void createEnvironment() {
Environment environment = mwaaService.createEnvironment("test-env",
createRequest("arn:aws:s3:::my-bucket", "dags"));
assertNotNull(environment);
assertEquals("test-env", environment.getName());
assertEquals(EnvironmentStatus.AVAILABLE, environment.getStatus());
assertTrue(environment.getArn().contains("airflow"));
assertTrue(environment.getArn().contains("environment/test-env"));
assertEquals("2.10.5", environment.getAirflowVersion());
assertNotNull(environment.getWebserverUrl());
assertNotNull(environment.getCreatedAt());
}
@Test
void createEnvironmentDuplicateFails() {
mwaaService.createEnvironment("dup-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
AwsException ex = assertThrows(AwsException.class,
() -> mwaaService.createEnvironment("dup-env", createRequest("arn:aws:s3:::my-bucket", "dags")));
assertEquals(400, ex.getHttpStatus());
// CreateEnvironment's botocore model declares no "already exists" shape.
assertEquals("ValidationException", ex.getErrorCode());
}
@Test
void createEnvironmentWithUnsupportedVersionFails() {
CreateEnvironmentRequest request = createRequest("arn:aws:s3:::my-bucket", "dags");
request.setAirflowVersion("1.10.15");
AwsException ex = assertThrows(AwsException.class,
() -> mwaaService.createEnvironment("bad-version-env", request));
assertEquals(400, ex.getHttpStatus());
assertEquals("ValidationException", ex.getErrorCode());
}
@Test
void createEnvironmentWithSupportedVersionRoundTrips() {
CreateEnvironmentRequest request = createRequest("arn:aws:s3:::my-bucket", "dags");
request.setAirflowVersion("2.9.3");
Environment environment = mwaaService.createEnvironment("versioned-env", request);
assertEquals("2.9.3", environment.getAirflowVersion());
}
@Test
void getEnvironment() {
mwaaService.createEnvironment("my-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
Environment described = mwaaService.getEnvironment("my-env");
assertEquals("my-env", described.getName());
}
@Test
void getEnvironmentNotFound() {
AwsException ex = assertThrows(AwsException.class, () -> mwaaService.getEnvironment("nonexistent"));
assertEquals(404, ex.getHttpStatus());
}
@Test
void listEnvironments() {
mwaaService.createEnvironment("env-a", createRequest("arn:aws:s3:::my-bucket", "dags"));
mwaaService.createEnvironment("env-b", createRequest("arn:aws:s3:::my-bucket", "dags"));
List<String> names = mwaaService.listEnvironments();
assertEquals(2, names.size());
assertTrue(names.contains("env-a"));
assertTrue(names.contains("env-b"));
}
@Test
void deleteEnvironment() {
mwaaService.createEnvironment("to-delete", createRequest("arn:aws:s3:::my-bucket", "dags"));
Environment deleted = mwaaService.deleteEnvironment("to-delete");
assertEquals(EnvironmentStatus.DELETING, deleted.getStatus());
assertTrue(mwaaService.listEnvironments().isEmpty());
}
@Test
void updateEnvironmentAppliesMetadataFields() {
mwaaService.createEnvironment("update-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
UpdateEnvironmentRequest request = new UpdateEnvironmentRequest();
request.setEnvironmentClass("mw1.large");
request.setDagS3Path("dags-v2");
Environment updated = mwaaService.updateEnvironment("update-env", request);
assertNotNull(updated.getArn());
Environment described = mwaaService.getEnvironment("update-env");
assertEquals("mw1.large", described.getEnvironmentClass());
assertEquals("dags-v2", described.getDagS3Path());
assertEquals("SUCCESS", described.getLastUpdate().getStatus());
}
@Test
void updateEnvironmentRejectsAirflowVersionChange() {
mwaaService.createEnvironment("no-version-change-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
UpdateEnvironmentRequest request = new UpdateEnvironmentRequest();
request.setAirflowVersion("2.9.3");
AwsException ex = assertThrows(AwsException.class,
() -> mwaaService.updateEnvironment("no-version-change-env", request));
assertEquals(400, ex.getHttpStatus());
}
@Test
void updateEnvironmentRejectsAirflowConfigurationOptionsChange() {
mwaaService.createEnvironment("no-config-change-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
UpdateEnvironmentRequest request = new UpdateEnvironmentRequest();
request.setAirflowConfigurationOptions(Map.of("core.parallelism", "10"));
AwsException ex = assertThrows(AwsException.class,
() -> mwaaService.updateEnvironment("no-config-change-env", request));
assertEquals(400, ex.getHttpStatus());
}
@Test
void updateEnvironmentRejectsStartupScriptS3PathChange() {
CreateEnvironmentRequest createRequest = createRequest("arn:aws:s3:::my-bucket", "dags");
createRequest.setStartupScriptS3Path("startup.sh");
Environment environment = mwaaService.createEnvironment("no-startup-script-change-env", createRequest);
assertEquals("startup.sh", environment.getStartupScriptS3Path());
UpdateEnvironmentRequest request = new UpdateEnvironmentRequest();
request.setStartupScriptS3Path("startup-v2.sh");
AwsException ex = assertThrows(AwsException.class,
() -> mwaaService.updateEnvironment("no-startup-script-change-env", request));
assertEquals(400, ex.getHttpStatus());
}
@Test
void taggingOperations() {
Environment environment = mwaaService.createEnvironment("tagged-env",
createRequest("arn:aws:s3:::my-bucket", "dags"));
String arn = environment.getArn();
mwaaService.tagResource(null, arn, Map.of("env", "test", "team", "data"));
Map<String, String> tags = mwaaService.listTags(null, arn);
assertEquals("test", tags.get("env"));
assertEquals("data", tags.get("team"));
mwaaService.untagResource(null, arn, List.of("env"));
tags = mwaaService.listTags(null, arn);
assertFalse(tags.containsKey("env"));
assertEquals("data", tags.get("team"));
}
@Test
void tagHandlerServiceKeyIsAirflow() {
assertEquals("airflow", mwaaService.serviceKey());
assertEquals("Tags", mwaaService.tagsBodyKey());
}
@Test
void createWebLoginTokenReturnsTokenAndHostname() {
mwaaService.createEnvironment("web-token-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
Map<String, Object> response = mwaaService.createWebLoginToken("web-token-env");
assertNotNull(response.get("WebToken"));
assertNotNull(response.get("WebServerHostname"));
}
@Test
void createCliTokenIsValidatedByIsValidCliToken() {
mwaaService.createEnvironment("cli-token-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
Map<String, Object> response = mwaaService.createCliToken("cli-token-env");
String token = (String) response.get("CliToken");
assertNotNull(token);
assertTrue(mwaaService.isValidCliToken("cli-token-env", token));
assertFalse(mwaaService.isValidCliToken("cli-token-env", "not-a-real-token"));
assertFalse(mwaaService.isValidCliToken("other-env", token));
}
/** Exercises the real (non-mock) create/delete path — the outer class's {@code mwaaService}
* always runs with {@code mock=true}, which never touches {@code PortAllocator} at all. */
@Nested
class RealModeLifecycle {
private PortAllocator portAllocator;
private MwaaEnvironmentManager environmentManager;
private MwaaProxyManager proxyManager;
private MwaaService realModeService;
@BeforeEach
void setUpRealMode() {
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return new InMemoryStorage<>();
}
};
EmulatorConfig.MwaaServiceConfig mwaaConfig = proxy(EmulatorConfig.MwaaServiceConfig.class,
(proxy, method, args) -> switch (method.getName()) {
case "enabled" -> true;
case "mock" -> false;
case "supportedVersions" -> List.of("2.10.5", "2.9.3", "2.8.4");
case "defaultVersion" -> "2.10.5";
case "proxyBasePort" -> 8700;
case "proxyMaxPort" -> 8799;
case "dagSyncIntervalSeconds" -> 30;
default -> defaultValue(method);
});
EmulatorConfig.ServicesConfig servicesConfig = proxy(EmulatorConfig.ServicesConfig.class,
(proxy, method, args) -> switch (method.getName()) {
case "mwaa" -> mwaaConfig;
default -> defaultValue(method);
});
EmulatorConfig.TlsConfig tlsConfig = proxy(EmulatorConfig.TlsConfig.class,
(proxy, method, args) -> defaultValue(method));
EmulatorConfig config = proxy(EmulatorConfig.class, (proxy, method, args) -> switch (method.getName()) {
case "services" -> servicesConfig;
case "tls" -> tlsConfig;
case "defaultRegion" -> "us-east-1";
case "defaultAccountId" -> "000000000000";
case "hostname" -> Optional.empty();
default -> defaultValue(method);
});
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
S3Service 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);
}
@Test
void deletingAnEnvironmentReleasesItsProxyPort() {
Environment environment = realModeService.createEnvironment("real-env",
createRequest("arn:aws:s3:::my-bucket", "dags"));
assertEquals(8701, environment.getProxyPort());
realModeService.deleteEnvironment("real-env");
verify(portAllocator).release(8701);
}
@Test
void proxyStartupFailureRollsBackTheAllocatedPortAndAnyStartedContainers() {
// Containers start fine; only the proxy bind fails (e.g. the port got taken out from
// under us between allocate() and bind()). The port must not leak, and whatever
// startEnvironment() already started must get torn down, not orphaned.
Mockito.doThrow(new RuntimeException("bind failed"))
.when(proxyManager).startProxy(any(), anyInt(), any(), anyInt(), any(), any());
Environment environment = realModeService.createEnvironment("failed-proxy-env",
createRequest("arn:aws:s3:::my-bucket", "dags"));
assertEquals(EnvironmentStatus.CREATE_FAILED, environment.getStatus());
verify(portAllocator).release(8701);
verify(environmentManager).stopEnvironment(environment);
verify(proxyManager).stopProxy("failed-proxy-env");
}
}
}
@@ -0,0 +1,47 @@
package io.github.hectorvent.floci.services.mwaa.proxy;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Routing-decision tests for {@link MwaaWebProxy}: which requests get intercepted by the CLI
* handler versus forwarded verbatim to the backend Airflow container, and bearer-token parsing.
* No real sockets are used — {@code isCliRequest}/{@code extractBearerToken} are pure functions.
*/
class MwaaWebProxyTest {
@Test
void interceptsOnlyPostToTheCliPath() {
assertTrue(MwaaWebProxy.isCliRequest("POST", "/aws_mwaa/cli"));
assertTrue(MwaaWebProxy.isCliRequest("post", "/aws_mwaa/cli"), "method match should be case-insensitive");
}
@Test
void forwardsEverythingElse() {
assertFalse(MwaaWebProxy.isCliRequest("GET", "/aws_mwaa/cli"), "GET to the CLI path is not intercepted");
assertFalse(MwaaWebProxy.isCliRequest("POST", "/"), "POST elsewhere is forwarded");
assertFalse(MwaaWebProxy.isCliRequest("POST", "/api/v1/dags"), "Airflow REST API traffic is forwarded");
assertFalse(MwaaWebProxy.isCliRequest("POST", "/aws_mwaa/cli/"), "trailing slash does not match");
assertFalse(MwaaWebProxy.isCliRequest("PUT", "/aws_mwaa/cli"));
}
@Test
void extractsBearerTokenCaseInsensitively() {
assertEquals("abc123", MwaaWebProxy.extractBearerToken("Bearer abc123"));
assertEquals("abc123", MwaaWebProxy.extractBearerToken("bearer abc123"));
assertEquals("abc123", MwaaWebProxy.extractBearerToken("BEARER abc123".replace(" ", " ")));
}
@Test
void rejectsMissingOrMalformedAuthorizationHeaders() {
assertNull(MwaaWebProxy.extractBearerToken(null));
assertNull(MwaaWebProxy.extractBearerToken(""));
assertNull(MwaaWebProxy.extractBearerToken("Basic dXNlcjpwYXNz"));
assertNull(MwaaWebProxy.extractBearerToken("Bearer "));
assertNull(MwaaWebProxy.extractBearerToken("Bearer"));
}
}
+3
View File
@@ -227,6 +227,9 @@ floci:
enabled: true
mock: true
ecr-registry-mirror: true
mwaa:
enabled: true
mock: true
pipes:
enabled: true
elbv2: