mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
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:
1 parent
5f7d4d2dc8
commit
7e4e3e8c50
23 files changed
+3182
-1
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+118
@@ -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
|
||||
}
|
||||
+42
@@ -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; }
|
||||
}
|
||||
+30
@@ -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; }
|
||||
}
|
||||
+26
@@ -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; }
|
||||
}
|
||||
+104
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user