mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix: run CloudWatch alarms, CodeDeploy deployments and MWAA DAG syncs in their own account (#9607)
Three background workers ran outside any request scope, so their calls went to the default account and a resource in any other account was never served. Each now runs as the account that owns its resource, in that resource's region. The alarm evaluator lists the metric alarms of every account with the account that owns each, and evaluates each one as that account in the alarm's region, so its metric, its state change and its SNS or scaling actions are that account's. A CodeDeploy deployment's state machine thread captures the creating account at submit and runs as it in the deployment's region, so the Lambda alias shift, the ECS task-set calls and the EC2 and SSM lookups act on that account's resources. The in-memory deployments are keyed by account and region, so another account can no longer read them. The MWAA DAG-sync poller runs each environment's sync as the environment's account in its region, so the DAG prefix and requirements file come from that account's buckets. Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
1feda30eb7
commit
c4af7c14ae
8 files changed
+393
-24
No files matched your search
@@ -1,5 +1,7 @@
|
||||
package io.floci.aws.services.cloudwatch.metrics;
|
||||
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
@@ -76,12 +78,15 @@ public class AlarmEvaluator {
|
||||
* ScheduledExecutorService#scheduleAtFixedRate} silently stops all future executions
|
||||
* forever if the submitted task throws, so a transient failure fetching the alarm list
|
||||
* itself (not just evaluating one alarm) must not be allowed to kill every future tick.
|
||||
* Each alarm is evaluated as the account that owns it, in its region, so its metric, its
|
||||
* state change and its actions are that account's.
|
||||
*/
|
||||
void evaluateAll() {
|
||||
try {
|
||||
for (MetricAlarm alarm : metricsService.allAlarms()) {
|
||||
for (AccountAwareStorageBackend.AccountEntry<MetricAlarm> entry : metricsService.metricAlarmsInEveryAccount()) {
|
||||
MetricAlarm alarm = entry.value();
|
||||
try {
|
||||
evaluate(alarm);
|
||||
RequestScopes.runAs(entry.accountId(), alarm.getRegion(), () -> evaluate(alarm));
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Alarm evaluation failed for {0}: {1}", alarm.getAlarmName(), e.getMessage());
|
||||
}
|
||||
|
||||
+22
-1
@@ -674,12 +674,33 @@ public class CloudWatchMetricsService implements Resettable {
|
||||
return node;
|
||||
}
|
||||
|
||||
/** Metric alarms evaluated by the existing metric evaluator. */
|
||||
/** The metric alarms of the caller's account. */
|
||||
public List<MetricAlarm> allAlarms() {
|
||||
return alarmStore.scan(k -> true).stream().filter(MetricAlarm.class::isInstance)
|
||||
.map(MetricAlarm.class::cast).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* The metric alarms of every account, each with the account that owns it, for the evaluator,
|
||||
* which runs outside any request and so has no account of its own.
|
||||
*/
|
||||
public List<AccountAwareStorageBackend.AccountEntry<MetricAlarm>> metricAlarmsInEveryAccount() {
|
||||
List<AccountAwareStorageBackend.AccountEntry<MetricAlarm>> alarms = new ArrayList<>();
|
||||
if (alarmStore instanceof AccountAwareStorageBackend<Alarm> aware) {
|
||||
for (AccountAwareStorageBackend.AccountEntry<Alarm> entry : aware.scanAllAccountEntries(k -> true)) {
|
||||
if (entry.value() instanceof MetricAlarm alarm) {
|
||||
alarms.add(new AccountAwareStorageBackend.AccountEntry<>(entry.accountId(), entry.key(), alarm));
|
||||
}
|
||||
}
|
||||
return alarms;
|
||||
}
|
||||
for (MetricAlarm alarm : allAlarms()) {
|
||||
alarms.add(new AccountAwareStorageBackend.AccountEntry<>(regionResolver.getDefaultAccountId(),
|
||||
alarm.getRegion() + "::" + alarm.getAlarmName(), alarm));
|
||||
}
|
||||
return alarms;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads current action settings after metric evaluation. Handlers run outside this monitor;
|
||||
* disabling actions does not cancel work already admitted by this lookup.
|
||||
|
||||
@@ -10,6 +10,7 @@ import io.floci.aws.core.common.EpochSeconds;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.Pagination;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.storage.StorageBackedMap;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.codedeploy.model.Application;
|
||||
@@ -115,9 +116,9 @@ public class CodeDeployService {
|
||||
private Map<String, Map<String, OnPremisesInstance>> onPremisesInstances = new ConcurrentHashMap<>();
|
||||
|
||||
// ---- Transient runtime state (in memory only) ----
|
||||
// key: region -> deploymentId -> Deployment
|
||||
// key: account:region -> deploymentId -> Deployment
|
||||
private final ConcurrentHashMap<String, ConcurrentHashMap<String, Deployment>> deployments = new ConcurrentHashMap<>();
|
||||
// key: region -> deploymentId -> targetId -> DeploymentTarget wrapper
|
||||
// key: account:region -> deploymentId -> targetId -> DeploymentTarget wrapper
|
||||
private final ConcurrentHashMap<String, ConcurrentHashMap<String, ConcurrentHashMap<String, Map<String, Object>>>> deploymentTargets = new ConcurrentHashMap<>();
|
||||
// key: lifecycleEventHookExecutionId -> CompletableFuture<status>
|
||||
private final ConcurrentHashMap<String, CompletableFuture<String>> hookFutures = new ConcurrentHashMap<>();
|
||||
@@ -607,11 +608,25 @@ public class CodeDeployService {
|
||||
// ---- Deployments ----
|
||||
|
||||
private Map<String, Deployment> deploymentsFor(String region) {
|
||||
return deployments.computeIfAbsent(region, r -> new ConcurrentHashMap<>());
|
||||
return deployments.computeIfAbsent(deploymentScope(region), r -> new ConcurrentHashMap<>());
|
||||
}
|
||||
|
||||
private Map<String, ConcurrentHashMap<String, Map<String, Object>>> deploymentTargetsFor(String region) {
|
||||
return deploymentTargets.computeIfAbsent(region, r -> new ConcurrentHashMap<>());
|
||||
return deploymentTargets.computeIfAbsent(deploymentScope(region), r -> new ConcurrentHashMap<>());
|
||||
}
|
||||
|
||||
/** Deployments live in memory, so they are keyed by the caller's account as well as the region. */
|
||||
private String deploymentScope(String region) {
|
||||
return regionResolver.getAccountId() + ":" + region;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a deployment's state machine on its own virtual thread as the account that created it,
|
||||
* in its region, so the Lambda, ECS, EC2 and SSM calls it makes act on that account's resources.
|
||||
*/
|
||||
private void startDeploymentThread(String name, String region, Runnable stateMachine) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
Thread.ofVirtual().name(name).start(() -> RequestScopes.runAs(accountId, region, stateMachine));
|
||||
}
|
||||
|
||||
private Map<String, OnPremisesInstance> onPremisesFor(String region) {
|
||||
@@ -677,7 +692,7 @@ public class CodeDeployService {
|
||||
stopFlags.put(deploymentId, stopFlag);
|
||||
|
||||
String finalEffectiveConfig = effectiveConfig;
|
||||
Thread.ofVirtual().name("codedeploy-" + deploymentId).start(
|
||||
startDeploymentThread("codedeploy-" + deploymentId, region,
|
||||
() -> runStateMachine(region, deployment, appSpec, lambdaTargetMap, stopFlag, finalEffectiveConfig));
|
||||
|
||||
return deploymentId;
|
||||
@@ -891,7 +906,7 @@ public class CodeDeployService {
|
||||
AtomicBoolean stopFlag = new AtomicBoolean(false);
|
||||
stopFlags.put(deploymentId, stopFlag);
|
||||
|
||||
Thread.ofVirtual().name("codedeploy-server-" + deploymentId).start(
|
||||
startDeploymentThread("codedeploy-server-" + deploymentId, region,
|
||||
() -> runServerStateMachine(region, deployment, appSpec, instanceIds,
|
||||
instanceTargetMaps, stopFlag));
|
||||
return deploymentId;
|
||||
@@ -1393,7 +1408,7 @@ public class CodeDeployService {
|
||||
final String finalBlueTgArn = blueTgArn;
|
||||
final String finalGreenTgArn = greenTgArn;
|
||||
final List<String> finalListenerArns = listenerArns;
|
||||
Thread.ofVirtual().name("codedeploy-ecs-" + deploymentId).start(
|
||||
startDeploymentThread("codedeploy-ecs-" + deploymentId, region,
|
||||
() -> runEcsStateMachine(region, deployment, appSpec, ecsTargetMap, stopFlag,
|
||||
effectiveConfig, finalCluster, finalService,
|
||||
finalBlueTgArn, finalGreenTgArn, finalListenerArns));
|
||||
|
||||
@@ -1096,25 +1096,34 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
|
||||
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());
|
||||
}
|
||||
}
|
||||
syncDagsOfAvailableEnvironments();
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error in MWAA DAG-sync poller", e);
|
||||
}
|
||||
}, intervalSeconds, intervalSeconds, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* One pass of the DAG-sync poller over every account's available environments, each synced as
|
||||
* the account that owns it, in its region, so its DAGs and requirements come from that account's S3.
|
||||
*/
|
||||
void syncDagsOfAvailableEnvironments() {
|
||||
for (Environment environment : allEnvironments()) {
|
||||
if (environment.getStatus() != EnvironmentStatus.AVAILABLE) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
RequestScopes.runAs(environmentAccount(environment), environmentRegion(environment),
|
||||
() -> 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Package-private (not private) so MwaaServiceTest can run a single sync pass directly.
|
||||
void syncDags(Environment environment) {
|
||||
if (environment.getSourceBucketArn() == null || environment.getDagS3Path() == null) {
|
||||
|
||||
@@ -200,7 +200,7 @@ class AlarmEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void evaluateAllSurvivesAllAlarmsThrowing() {
|
||||
when(metricsService.allAlarms()).thenThrow(new RuntimeException("storage hiccup"));
|
||||
when(metricsService.metricAlarmsInEveryAccount()).thenThrow(new RuntimeException("storage hiccup"));
|
||||
|
||||
assertDoesNotThrow(evaluator::evaluateAll);
|
||||
}
|
||||
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package io.floci.aws.services.cloudwatch.metrics;
|
||||
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.allOf;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
|
||||
/**
|
||||
* The alarm evaluator runs outside any request, so it has to evaluate every account's alarms in
|
||||
* that account: an alarm of a non-default account reads that account's metric, changes state
|
||||
* there and notifies that account's SNS topic.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudWatchAlarmAccountScopeIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "222222222222";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String JSON = "application/x-amz-json-1.0";
|
||||
|
||||
@Inject
|
||||
AlarmEvaluator alarmEvaluator;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configure() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void alarmOfANonDefaultAccountChangesStateOnThatAccountsMetricAndNotifiesThatAccountsTopic() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String alarm = "account-scope-alarm-" + suffix;
|
||||
String namespace = "Custom/AccountScope" + suffix;
|
||||
String topicArn = sns("CreateTopic", "Name", "account-scope-topic-" + suffix)
|
||||
.xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
|
||||
cleanup.register(() -> sns("DeleteTopic", "TopicArn", topicArn));
|
||||
assertThat(topicArn, containsString(":" + ACCOUNT + ":"));
|
||||
String queueUrl = sqs("CreateQueue", "{\"QueueName\":\"account-scope-queue-" + suffix + "\"}")
|
||||
.jsonPath().getString("QueueUrl");
|
||||
cleanup.register(() -> sqs("DeleteQueue", "{\"QueueUrl\":\"" + queueUrl + "\"}"));
|
||||
String queueArn = sqs("GetQueueAttributes", "{\"QueueUrl\":\"" + queueUrl + "\",\"AttributeNames\":[\"QueueArn\"]}")
|
||||
.jsonPath().getString("Attributes.QueueArn");
|
||||
sns("Subscribe", "TopicArn", topicArn, "Protocol", "sqs", "Endpoint", queueArn);
|
||||
|
||||
long now = Instant.now().getEpochSecond();
|
||||
StringBuilder data = new StringBuilder();
|
||||
for (int minutesAgo = 1; minutesAgo <= 3; minutesAgo++) {
|
||||
if (!data.isEmpty()) {
|
||||
data.append(',');
|
||||
}
|
||||
data.append("{\"MetricName\":\"Load\",\"Value\":90,\"Timestamp\":").append(now - 60L * minutesAgo).append('}');
|
||||
}
|
||||
cloudWatch("PutMetricData", "{\"Namespace\":\"" + namespace + "\",\"MetricData\":[" + data + "]}");
|
||||
cloudWatch("PutMetricAlarm", """
|
||||
{"AlarmName":"%s","Namespace":"%s","MetricName":"Load","Statistic":"Maximum","Period":60,
|
||||
"EvaluationPeriods":1,"Threshold":50,"ComparisonOperator":"GreaterThanThreshold",
|
||||
"AlarmActions":["%s"]}
|
||||
""".formatted(alarm, namespace, topicArn));
|
||||
cleanup.register(() -> cloudWatch("DeleteAlarms", "{\"AlarmNames\":[\"" + alarm + "\"]}"));
|
||||
|
||||
// evaluateNow runs one pass synchronously, so the state has changed when it returns.
|
||||
AlarmEvaluatorTestAccess.evaluateNow(alarmEvaluator);
|
||||
cloudWatch("DescribeAlarms", "{\"AlarmNames\":[\"" + alarm + "\"]}")
|
||||
.then().body("MetricAlarms[0].StateValue", equalTo("ALARM"));
|
||||
|
||||
// The evaluator re-sends an alarm's actions on every pass while it stays in ALARM, so a
|
||||
// scheduled pass may add a message: wait for this account's notification, not a count.
|
||||
await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(200)).untilAsserted(() -> {
|
||||
List<String> bodies = sqs("ReceiveMessage", "{\"QueueUrl\":\"" + queueUrl + "\",\"MaxNumberOfMessages\":10}")
|
||||
.jsonPath().getList("Messages.Body", String.class);
|
||||
assertThat(bodies, hasItem(allOf(containsString(alarm), containsString(ACCOUNT))));
|
||||
});
|
||||
}
|
||||
|
||||
private static Response cloudWatch(String operation, String body) {
|
||||
return given().contentType(JSON)
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801." + operation)
|
||||
.header("Authorization", auth(ACCOUNT, REGION, "monitoring"))
|
||||
.body(body)
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().response();
|
||||
}
|
||||
|
||||
private static Response sqs(String operation, String body) {
|
||||
return given().contentType(JSON)
|
||||
.header("X-Amz-Target", "AmazonSQS." + operation)
|
||||
.header("Authorization", auth(ACCOUNT, REGION, "sqs"))
|
||||
.body(body)
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().response();
|
||||
}
|
||||
|
||||
private static Response sns(String action, String... params) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", auth(ACCOUNT, REGION, "sns"))
|
||||
.formParam("Action", action);
|
||||
for (int i = 0; i < params.length; i += 2) {
|
||||
request = request.formParam(params[i], params[i + 1]);
|
||||
}
|
||||
return request.when().post("/").then().statusCode(200).extract().response();
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package io.floci.aws.services.codedeploy;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
/**
|
||||
* A CodeDeploy deployment runs on its own thread after CreateDeployment returns, so it has to
|
||||
* act as the account that created it: a Lambda deployment of a non-default account shifts that
|
||||
* account's alias, and the deployment is visible only to that account.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CodeDeployAccountScopeIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "222222222222";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String LAMBDA = "/2015-03-31";
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void lambdaDeploymentOfANonDefaultAccountShiftsThatAccountsAlias() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String function = "cd-account-fn-" + suffix;
|
||||
String application = "cd-account-app-" + suffix;
|
||||
String group = "cd-account-dg-" + suffix;
|
||||
|
||||
lambda().contentType("application/json")
|
||||
.body(OBJECT_MAPPER.createObjectNode().put("FunctionName", function).put("Runtime", "nodejs20.x")
|
||||
.put("Role", "arn:aws:iam::" + ACCOUNT + ":role/lambda-role").put("Handler", "index.handler")
|
||||
.toString())
|
||||
.when().post(LAMBDA + "/functions").then().statusCode(201);
|
||||
cleanup.register(() -> lambda().when().delete(LAMBDA + "/functions/" + function).then().statusCode(204));
|
||||
publishVersion(function, "1");
|
||||
lambda().contentType("application/json").body("{\"Description\":\"second\"}")
|
||||
.when().put(LAMBDA + "/functions/" + function + "/configuration").then().statusCode(200);
|
||||
publishVersion(function, "2");
|
||||
lambda().contentType("application/json").body("{\"Name\":\"live\",\"FunctionVersion\":\"1\"}")
|
||||
.when().post(LAMBDA + "/functions/" + function + "/aliases").then().statusCode(201);
|
||||
|
||||
codeDeploy("CreateApplication", OBJECT_MAPPER.createObjectNode()
|
||||
.put("applicationName", application).put("computePlatform", "Lambda"));
|
||||
cleanup.register(() -> codeDeploy("DeleteApplication",
|
||||
OBJECT_MAPPER.createObjectNode().put("applicationName", application)));
|
||||
ObjectNode groupRequest = OBJECT_MAPPER.createObjectNode()
|
||||
.put("applicationName", application).put("deploymentGroupName", group)
|
||||
.put("deploymentConfigName", "CodeDeployDefault.LambdaAllAtOnce")
|
||||
.put("serviceRoleArn", "arn:aws:iam::" + ACCOUNT + ":role/codedeploy-role");
|
||||
groupRequest.putObject("deploymentStyle")
|
||||
.put("deploymentType", "BLUE_GREEN").put("deploymentOption", "WITH_TRAFFIC_CONTROL");
|
||||
codeDeploy("CreateDeploymentGroup", groupRequest);
|
||||
cleanup.register(() -> codeDeploy("DeleteDeploymentGroup", OBJECT_MAPPER.createObjectNode()
|
||||
.put("applicationName", application).put("deploymentGroupName", group)));
|
||||
|
||||
ObjectNode appSpec = OBJECT_MAPPER.createObjectNode().put("version", 0.0);
|
||||
ArrayNode resources = appSpec.putArray("Resources");
|
||||
resources.addObject().putObject("fn").put("Type", "AWS::Lambda::Function").putObject("Properties")
|
||||
.put("Name", function).put("Alias", "live").put("CurrentVersion", "1").put("TargetVersion", "2");
|
||||
ObjectNode deploymentRequest = OBJECT_MAPPER.createObjectNode()
|
||||
.put("applicationName", application).put("deploymentGroupName", group);
|
||||
deploymentRequest.putObject("revision").put("revisionType", "AppSpecContent")
|
||||
.putObject("appSpecContent").put("content", appSpec.toString());
|
||||
String deploymentId = codeDeploy("CreateDeployment", deploymentRequest).jsonPath().getString("deploymentId");
|
||||
|
||||
ObjectNode getDeployment = OBJECT_MAPPER.createObjectNode().put("deploymentId", deploymentId);
|
||||
await().atMost(Duration.ofSeconds(5)).pollInterval(Duration.ofMillis(200)).untilAsserted(() ->
|
||||
codeDeploy("GetDeployment", getDeployment)
|
||||
.then().body("deploymentInfo.status", equalTo("Succeeded")));
|
||||
lambda().when().get(LAMBDA + "/functions/" + function + "/aliases/live")
|
||||
.then().statusCode(200).body("FunctionVersion", equalTo("2"));
|
||||
given().header("X-Amz-Target", "CodeDeploy_20141006.GetDeployment")
|
||||
.contentType("application/x-amz-json-1.1").body(getDeployment.toString())
|
||||
.when().post("/")
|
||||
.then().statusCode(400).body("__type", containsString("DeploymentDoesNotExistException"));
|
||||
}
|
||||
|
||||
private static void publishVersion(String function, String expected) {
|
||||
lambda().contentType("application/json").body("{}")
|
||||
.when().post(LAMBDA + "/functions/" + function + "/versions")
|
||||
.then().statusCode(201).body("Version", equalTo(expected));
|
||||
}
|
||||
|
||||
private static RequestSpecification lambda() {
|
||||
return given().header("Authorization", auth(ACCOUNT, REGION, "lambda"));
|
||||
}
|
||||
|
||||
private static Response codeDeploy(String operation, ObjectNode body) {
|
||||
return given().header("X-Amz-Target", "CodeDeploy_20141006." + operation)
|
||||
.header("Authorization", auth(ACCOUNT, REGION, "codedeploy"))
|
||||
.contentType("application/x-amz-json-1.1").body(body.toString())
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().response();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package io.floci.aws.services.mwaa;
|
||||
|
||||
import io.floci.aws.services.mwaa.model.Environment;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* The DAG-sync poller runs outside any request, so each environment has to read its DAG bucket
|
||||
* as the account that owns it: an environment of a non-default account syncs the DAGs of that
|
||||
* account's bucket.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class MwaaDagSyncAccountScopeIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "222222222222";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@InjectMock
|
||||
MwaaEnvironmentManager environmentManager;
|
||||
|
||||
@Inject
|
||||
MwaaService mwaaService;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void dagSyncOfANonDefaultAccountsEnvironmentReadsThatAccountsBucket() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String bucket = "mwaa-account-dags-" + suffix;
|
||||
String environment = "mwaa-account-env-" + suffix;
|
||||
byte[] dag = "from airflow import DAG\n".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
s3().when().put("/" + bucket).then().statusCode(200);
|
||||
cleanup.register(() -> s3().when().delete("/" + bucket).then().statusCode(204));
|
||||
s3().body(dag).when().put("/" + bucket + "/dags/hello.py").then().statusCode(200);
|
||||
cleanup.register(() -> s3().when().delete("/" + bucket + "/dags/hello.py").then().statusCode(204));
|
||||
|
||||
given().header("Authorization", auth(ACCOUNT, REGION, "airflow")).contentType("application/json")
|
||||
.body("{\"ExecutionRoleArn\":\"arn:aws:iam::" + ACCOUNT + ":role/mwaa-execution-role\","
|
||||
+ "\"SourceBucketArn\":\"arn:aws:s3:::" + bucket + "\",\"DagS3Path\":\"dags\","
|
||||
+ "\"NetworkConfiguration\":{\"SubnetIds\":[\"subnet-1\",\"subnet-2\"],"
|
||||
+ "\"SecurityGroupIds\":[\"sg-1\"]}}")
|
||||
.when().put("/environments/" + environment)
|
||||
.then().statusCode(200);
|
||||
cleanup.register(() -> given().header("Authorization", auth(ACCOUNT, REGION, "airflow"))
|
||||
.when().delete("/environments/" + environment).then().statusCode(200));
|
||||
|
||||
mwaaService.syncDagsOfAvailableEnvironments();
|
||||
|
||||
ArgumentCaptor<byte[]> content = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(environmentManager).copyDagFile(
|
||||
argThat((Environment synced) -> synced != null && synced.getName().equals(environment)),
|
||||
eq("hello.py"), content.capture());
|
||||
assertArrayEquals(dag, content.getValue());
|
||||
}
|
||||
|
||||
private static RequestSpecification s3() {
|
||||
return given().header("Authorization", auth(ACCOUNT, REGION, "s3"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user