feat(rds): publish native stop and start lifecycle events (#8614) (#8622)

This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-16 15:34:03 -04:00
1 parent 024162483c
commit 7331a6b1ce
8 files changed
+586 -20

No files matched your search

+21
View File
@@ -257,6 +257,27 @@ flags leave the subscription and its topic, source type and event categories unc
Malformed restore flags are rejected before starting an instance or cluster restore.
## Native EventBridge lifecycle notifications
Completed `StopDBInstance`, `StartDBInstance`, `StopDBCluster` and `StartDBCluster`
operations publish `aws.rds` notifications on the resource account and Region's default
EventBridge bus. Cluster operations also notify their member instances. Instance events
use `RDS DB Instance Event` and IDs `RDS-EVENT-0087` (stopped) and `RDS-EVENT-0088`
(started); cluster events use `RDS DB Cluster Event` and `RDS-EVENT-0150` / `0151`.
The resource ARN appears in both `resources` and `detail.SourceArn`, alongside
`SourceType` (`DB_INSTANCE` for instances, `CLUSTER` for clusters),
`SourceIdentifier`, `Date`, `Message`, `EventID` and
`EventCategories: ["notification"]`, following the
[AWS event examples](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Events.overview.html).
The [Aurora cluster example](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_Events.overview.html)
documents the cluster-specific source type.
Events are emitted after the backend and proxies finish the operation. Rejected or failed
operations do not emit success notifications. Delivery is best effort, with no replay after
a restart; other RDS lifecycle events are not yet emitted. Metadata-only mock mode emits
the same notifications. EventBridge rules can route these events independently of the
SNS subscription actions below.
## Event notification subscriptions
The four subscription actions manage the resource itself. **Nothing is published to the topic.**
@@ -0,0 +1,79 @@
package io.floci.aws.services.rds;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.eventbridge.EventBridgeService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
/** Native lifecycle notifications on the resource account and Region's default EventBridge bus. */
@ApplicationScoped
public class RdsEventPublisher {
private static final Logger LOG = Logger.getLogger(RdsEventPublisher.class);
private record Event(String detailType, String detail, String arn, String accountId, String region) {}
private final EventBridgeService eventBridgeService;
private final ObjectMapper objectMapper;
private final Queue<Event> queued = new ConcurrentLinkedQueue<>();
private final AtomicBoolean publishing = new AtomicBoolean();
@Inject
public RdsEventPublisher(EventBridgeService eventBridgeService, ObjectMapper objectMapper) {
this.eventBridgeService = eventBridgeService;
this.objectMapper = objectMapper;
}
/** Snapshot the completed transition while RDS still holds the resource. */
void queue(String arn, String identifier, boolean cluster, boolean started) {
AwsArnUtils.Arn resource = AwsArnUtils.parse(arn);
ObjectNode detail = objectMapper.createObjectNode();
detail.putArray("EventCategories").add("notification");
detail.put("SourceType", cluster ? "CLUSTER" : "DB_INSTANCE");
detail.put("SourceArn", arn);
detail.put("SourceIdentifier", identifier);
detail.put("Date", Instant.now().toString());
detail.put("Message", "DB " + (cluster ? "cluster" : "instance") + (started ? " started." : " stopped."));
detail.put("EventID", cluster ? (started ? "RDS-EVENT-0151" : "RDS-EVENT-0150")
: (started ? "RDS-EVENT-0088" : "RDS-EVENT-0087"));
queued.add(new Event(cluster ? "RDS DB Cluster Event" : "RDS DB Instance Event",
detail.toString(), arn, resource.accountId(), resource.region()));
}
/**
* Called after releasing RDS locks, since a rule's target can call RDS again. A reentrant or
* concurrent call leaves its events for the active publisher, preserving transition order.
*/
void publishQueued() {
while (!queued.isEmpty() && publishing.compareAndSet(false, true)) {
try {
Event event;
while ((event = queued.poll()) != null) {
publish(event);
}
} finally {
publishing.set(false);
}
}
}
private void publish(Event event) {
try {
RequestScopes.runAs(event.accountId(), event.region(), () -> eventBridgeService.publishServiceEvent(
"aws.rds", event.detailType(), event.detail(), event.arn(), event.region()));
} catch (RuntimeException e) {
// The RDS transition has already committed. Even an unexpected delivery defect must
// not report a failed stop/start after it succeeded; retain its cause in the warning.
LOG.warnv(e, "Could not publish RDS lifecycle event for {0}", event.arn());
}
}
}
@@ -216,6 +216,7 @@ public class RdsService implements Resettable, ResourceProvider {
private final ResourceGroupsTaggingService taggingService;
// Null when a test constructs the service without CloudWatch; auto-pause then reports no metrics.
private final CloudWatchMetricsService metricsService;
private final RdsEventPublisher eventPublisher;
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private final Set<String> reportedMemberRelayFailures = ConcurrentHashMap.newKeySet();
private static final Pattern IMAGE_TAG_VERSION_PATTERN = Pattern.compile("^(\\d+(?:\\.\\d+)*)(.*)$");
@@ -242,7 +243,6 @@ public class RdsService implements Resettable, ResourceProvider {
"MYSQL_NATIVE_PASSWORD", "MYSQL_CACHING_SHA2_PASSWORD",
"POSTGRES_SCRAM_SHA_256", "POSTGRES_MD5", "SQL_SERVER_AUTHENTICATION");
@Inject
public RdsService(RdsContainerManager containerManager,
RdsProxyManager proxyManager,
Ec2Service ec2Service,
@@ -255,6 +255,25 @@ public class RdsService implements Resettable, ResourceProvider {
ResourceGroupsTaggingService taggingService,
KmsService kmsService,
CloudWatchMetricsService metricsService) {
this(containerManager, proxyManager, ec2Service, regionResolver, config, storageFactory,
secretsManagerService, dockerHostResolver, currentContainerNetworkResolver, taggingService,
kmsService, metricsService, null);
}
@Inject
public RdsService(RdsContainerManager containerManager,
RdsProxyManager proxyManager,
Ec2Service ec2Service,
RegionResolver regionResolver,
EmulatorConfig config,
StorageFactory storageFactory,
SecretsManagerService secretsManagerService,
DockerHostResolver dockerHostResolver,
CurrentContainerNetworkResolver currentContainerNetworkResolver,
ResourceGroupsTaggingService taggingService,
KmsService kmsService,
CloudWatchMetricsService metricsService,
RdsEventPublisher eventPublisher) {
this.containerManager = containerManager;
this.proxyManager = proxyManager;
this.ec2Service = ec2Service;
@@ -266,6 +285,7 @@ public class RdsService implements Resettable, ResourceProvider {
this.currentContainerNetworkResolver = currentContainerNetworkResolver;
this.taggingService = taggingService;
this.metricsService = metricsService;
this.eventPublisher = eventPublisher;
this.instances = storageFactory.create("rds", "rds-instances.json",
new TypeReference<Map<String, DbInstance>>() {});
this.eventSubscriptions = storageFactory.create("rds", "rds-event-subscriptions.json",
@@ -419,6 +439,31 @@ public class RdsService implements Resettable, ResourceProvider {
StorageBackend<String, OptionGroup> optionGroups,
ResourceGroupsTaggingService taggingService,
KmsService kmsService) {
this(containerManager, proxyManager, ec2Service, regionResolver, config, instances, clusters,
parameterGroups, clusterParameterGroups, subnetGroups, secretsManagerService, dockerHostResolver,
currentContainerNetworkResolver, proxies, proxyTargetGroups, optionGroups, taggingService,
kmsService, null);
}
RdsService(RdsContainerManager containerManager,
RdsProxyManager proxyManager,
Ec2Service ec2Service,
RegionResolver regionResolver,
EmulatorConfig config,
StorageBackend<String, DbInstance> instances,
StorageBackend<String, DbCluster> clusters,
StorageBackend<String, DbParameterGroup> parameterGroups,
StorageBackend<String, DbClusterParameterGroup> clusterParameterGroups,
StorageBackend<String, DbSubnetGroup> subnetGroups,
SecretsManagerService secretsManagerService,
DockerHostResolver dockerHostResolver,
CurrentContainerNetworkResolver currentContainerNetworkResolver,
StorageBackend<String, DbProxy> proxies,
StorageBackend<String, DbProxyTargetGroup> proxyTargetGroups,
StorageBackend<String, OptionGroup> optionGroups,
ResourceGroupsTaggingService taggingService,
KmsService kmsService,
RdsEventPublisher eventPublisher) {
this.containerManager = containerManager;
this.proxyManager = proxyManager;
this.ec2Service = ec2Service;
@@ -438,6 +483,7 @@ public class RdsService implements Resettable, ResourceProvider {
this.proxyTargetGroups = proxyTargetGroups;
this.taggingService = taggingService;
this.metricsService = null;
this.eventPublisher = eventPublisher;
this.globalClusters = new InMemoryStorage<>();
this.snapshots = new InMemoryStorage<>();
this.clusterSnapshots = new InMemoryStorage<>();
@@ -4589,7 +4635,17 @@ public class RdsService implements Resettable, ResourceProvider {
return stopDbInstance(id, snapshotId, regionResolver.getDefaultRegion());
}
public synchronized DbInstance stopDbInstance(String id, String snapshotId, String region) {
public DbInstance stopDbInstance(String id, String snapshotId, String region) {
try {
synchronized (this) {
return doStopDbInstance(id, snapshotId, region);
}
} finally {
publishLifecycleEvents();
}
}
private DbInstance doStopDbInstance(String id, String snapshotId, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
DbInstance instance = getDbInstance(id, effectiveRegion);
@@ -4629,6 +4685,7 @@ public class RdsService implements Resettable, ResourceProvider {
}
instance.setStatus(DbInstanceStatus.STOPPED);
putInstanceForScope(accountId, effectiveRegion, id, instance);
queueLifecycleEvent(instance.getDbInstanceArn(), id, false, false);
LOG.infov("DB instance {0} stopped", id);
return response;
}
@@ -4638,7 +4695,17 @@ public class RdsService implements Resettable, ResourceProvider {
return startDbInstance(id, regionResolver.getDefaultRegion());
}
public synchronized DbInstance startDbInstance(String id, String region) {
public DbInstance startDbInstance(String id, String region) {
try {
synchronized (this) {
return doStartDbInstance(id, region);
}
} finally {
publishLifecycleEvents();
}
}
private DbInstance doStartDbInstance(String id, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
DbInstance instance = getDbInstance(id, effectiveRegion);
@@ -4659,6 +4726,7 @@ public class RdsService implements Resettable, ResourceProvider {
}
instance.setStatus(DbInstanceStatus.AVAILABLE);
putInstanceForScope(accountId, effectiveRegion, id, instance);
queueLifecycleEvent(instance.getDbInstanceArn(), id, false, true);
LOG.infov("DB instance {0} started", id);
return response;
}
@@ -4716,7 +4784,11 @@ public class RdsService implements Resettable, ResourceProvider {
* every member's proxy with them, and all of them report "stopped" until StartDBCluster.
*/
public DbCluster stopDbCluster(String id, String region) {
return withClusterPublication(id, region, () -> doStopDbCluster(id, region));
try {
return withClusterPublication(id, region, () -> doStopDbCluster(id, region));
} finally {
publishLifecycleEvents();
}
}
private DbCluster doStopDbCluster(String id, String region) {
@@ -4762,13 +4834,18 @@ public class RdsService implements Resettable, ResourceProvider {
}
cluster.setStatus(DbInstanceStatus.STOPPED);
putClusterForScope(accountId, effectiveRegion, id, cluster);
queueClusterLifecycleEvents(cluster, effectiveRegion, false);
LOG.infov("DB cluster {0} stopped", id);
return response;
}
/** Starts a stopped cluster and its members on the cluster's kept volume. */
public DbCluster startDbCluster(String id, String region) {
return withClusterPublication(id, region, () -> doStartDbCluster(id, region));
try {
return withClusterPublication(id, region, () -> doStartDbCluster(id, region));
} finally {
publishLifecycleEvents();
}
}
private DbCluster doStartDbCluster(String id, String region) {
@@ -4789,10 +4866,35 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.setStatus(DbInstanceStatus.AVAILABLE);
putClusterForScope(accountId, effectiveRegion, id, cluster);
restoreClusterMemberBackends(cluster, effectiveRegion, true);
queueClusterLifecycleEvents(cluster, effectiveRegion, true);
LOG.infov("DB cluster {0} started", id);
return response;
}
private void queueClusterLifecycleEvents(DbCluster cluster, String region, boolean started) {
String accountId = accountIdFromArn(cluster.getDbClusterArn());
DbInstanceStatus completed = started ? DbInstanceStatus.AVAILABLE : DbInstanceStatus.STOPPED;
for (String memberId : cluster.getDbClusterMembers()) {
DbInstance member = findInstanceForScope(accountId, region, memberId);
if (member != null && member.getStatus() == completed) {
queueLifecycleEvent(member.getDbInstanceArn(), memberId, false, started);
}
}
queueLifecycleEvent(cluster.getDbClusterArn(), cluster.getDbClusterIdentifier(), true, started);
}
private void queueLifecycleEvent(String arn, String id, boolean cluster, boolean started) {
if (eventPublisher != null) {
eventPublisher.queue(arn, id, cluster, started);
}
}
private void publishLifecycleEvents() {
if (eventPublisher != null) {
eventPublisher.publishQueued();
}
}
/** Reboots a cluster: its container and proxies go down and come back on the same volume. */
public DbCluster rebootDbCluster(String id, String region) {
return withClusterPublication(id, region, () -> doRebootDbCluster(id, region));
@@ -0,0 +1,80 @@
package io.floci.aws.services.rds;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.testutil.LogCapture;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
class RdsEventPublisherTest {
@Test
void reentrantDeliveryPreservesSnapshotsAndDrainsWithoutRecursing() {
EventBridgeService eventBridge = mock(EventBridgeService.class);
RdsEventPublisher publisher = new RdsEventPublisher(eventBridge, new ObjectMapper());
String arn = "arn:aws-cn:rds:cn-north-1:111122223333:db:one";
List<String> details = new ArrayList<>();
AtomicBoolean delivering = new AtomicBoolean();
doAnswer(invocation -> {
assertTrue(delivering.compareAndSet(false, true));
details.add(invocation.getArgument(2));
assertEquals(arn, invocation.getArgument(3));
assertEquals("cn-north-1", invocation.getArgument(4));
if (details.size() == 1) {
publisher.queue(arn, "one", false, true);
publisher.publishQueued();
assertEquals(1, details.size());
}
delivering.set(false);
return null;
}).when(eventBridge).publishServiceEvent(anyString(), anyString(), anyString(), anyString(), anyString());
publisher.queue(arn, "one", false, false);
verifyNoInteractions(eventBridge);
publisher.publishQueued();
publisher.publishQueued();
assertEquals(2, details.size());
assertTrue(details.getFirst().contains("RDS-EVENT-0087"));
assertTrue(details.getLast().contains("RDS-EVENT-0088"));
assertFalse(delivering.get());
}
@Test
void aDeliveryFailureDoesNotLoseLaterEventsOrEscapeToTheRdsCaller() {
EventBridgeService eventBridge = mock(EventBridgeService.class);
RdsEventPublisher publisher = new RdsEventPublisher(eventBridge, new ObjectMapper());
List<String> details = new ArrayList<>();
IllegalStateException failure = new IllegalStateException("target unavailable");
doAnswer(invocation -> {
details.add(invocation.getArgument(2));
if (details.size() == 1) {
throw failure;
}
return null;
}).when(eventBridge).publishServiceEvent(anyString(), anyString(), anyString(), anyString(), anyString());
String arn = "arn:aws:rds:eu-west-2:111122223333:cluster:one";
publisher.queue(arn, "one", true, false);
publisher.queue(arn, "one", true, true);
List<LogRecord> records = LogCapture.capture(RdsEventPublisher.class, publisher::publishQueued);
assertEquals(2, details.size());
assertTrue(details.getFirst().contains("RDS-EVENT-0150"));
assertTrue(details.getLast().contains("RDS-EVENT-0151"));
assertEquals(1, records.size());
assertEquals(Level.WARNING.intValue(), records.getFirst().getLevel().intValue());
assertSame(failure, records.getFirst().getThrown());
assertTrue(LogCapture.formatted(records.getFirst()).contains(arn));
}
}
@@ -0,0 +1,154 @@
package io.floci.aws.services.rds;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EventRuleQueue;
import io.floci.aws.testing.RdsMockProfile;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.RdsException;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** SDK control-plane calls through an EventBridge rule to SQS; only database containers are mocked. */
@QuarkusTest
@TestProfile(RdsMockProfile.class)
class RdsLifecycleEventIntegrationTest {
private final ObjectMapper mapper = new ObjectMapper();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void standaloneStopAndStartEmitNativeEventsAndRejectedCallsDoNot() throws Exception {
String account = "111122223333";
Region region = Region.US_WEST_2;
String id = "rds-events-" + Long.toUnsignedString(System.nanoTime(), 36);
try (RdsClient rds = AwsTestClients.create(RdsClient.builder(), account, region);
EventRuleQueue queue = EventRuleQueue.route(account, region.id(), id, "{\"source\":[\"aws.rds\"]}")) {
String arn = rds.createDBInstance(r -> r.dbInstanceIdentifier(id).engine("postgres")
.masterUsername("admin").masterUserPassword("password123")
.dbInstanceClass("db.t3.micro").allocatedStorage(5)).dbInstance().dbInstanceArn();
try {
assertThrows(RdsException.class, () -> rds.startDBInstance(r -> r.dbInstanceIdentifier(id)));
assertTrue(queue.drain().isEmpty());
assertEquals("stopping", rds.stopDBInstance(r -> r.dbInstanceIdentifier(id))
.dbInstance().dbInstanceStatus());
assertEquals("starting", rds.startDBInstance(r -> r.dbInstanceIdentifier(id))
.dbInstance().dbInstanceStatus());
List<JsonNode> events = queue.drain();
assertEquals(2, events.size());
assertEvent(events.get(0), account, region, arn, id, false, false);
assertEvent(events.get(1), account, region, arn, id, false, true);
assertTrue(queue.drain().isEmpty());
} finally {
rds.deleteDBInstance(r -> r.dbInstanceIdentifier(id).skipFinalSnapshot(true));
}
}
}
@Test
void clusterTransitionsNotifyTheClusterAndItsMemberInTheirOwnScope() throws Exception {
String account = "444455556666";
Region region = Region.CN_NORTH_1;
String cluster = "rds-events-" + Long.toUnsignedString(System.nanoTime(), 36);
String member = cluster + "-member";
String pattern = "{\"source\":[\"aws.rds\"]}";
try (RdsClient rds = AwsTestClients.create(RdsClient.builder(), account, region);
EventRuleQueue queue = EventRuleQueue.route(account, region.id(), cluster, pattern);
EventRuleQueue foreignAccount = EventRuleQueue.route("777788889999", region.id(), cluster, pattern);
EventRuleQueue foreignRegion = EventRuleQueue.route(account, Region.CN_NORTHWEST_1.id(), cluster, pattern)) {
String clusterArn = rds.createDBCluster(r -> r.dbClusterIdentifier(cluster)
.engine("aurora-postgresql").masterUsername("admin").masterUserPassword("password123"))
.dbCluster().dbClusterArn();
String memberArn = rds.createDBInstance(r -> r.dbInstanceIdentifier(member)
.dbClusterIdentifier(cluster).engine("aurora-postgresql").dbInstanceClass("db.r6g.large"))
.dbInstance().dbInstanceArn();
try {
rds.stopDBCluster(r -> r.dbClusterIdentifier(cluster));
rds.startDBCluster(r -> r.dbClusterIdentifier(cluster));
List<JsonNode> events = queue.drain();
assertEquals(4, events.size());
for (boolean started : List.of(false, true)) {
String instanceEvent = started ? "RDS-EVENT-0088" : "RDS-EVENT-0087";
String clusterEvent = started ? "RDS-EVENT-0151" : "RDS-EVENT-0150";
assertEvent(find(events, instanceEvent), account, region, memberArn, member, false, started);
assertEvent(find(events, clusterEvent), account, region, clusterArn, cluster, true, started);
}
assertTrue(foreignAccount.drain().isEmpty());
assertTrue(foreignRegion.drain().isEmpty());
} finally {
rds.deleteDBInstance(r -> r.dbInstanceIdentifier(member).skipFinalSnapshot(true));
rds.deleteDBCluster(r -> r.dbClusterIdentifier(cluster).skipFinalSnapshot(true));
}
}
}
@Test
void awsClusterSourceTypePatternReceivesClusterLifecycleEvents() throws Exception {
String name = "rds-cluster-filter-" + Long.toUnsignedString(System.nanoTime(), 36);
String pattern = """
{"source":["aws.rds"],"detail-type":["RDS DB Cluster Event"],
"detail":{"SourceType":["CLUSTER"]}}
""";
String account = "222233334444";
Region region = Region.EU_WEST_2;
try (RdsClient rds = AwsTestClients.create(RdsClient.builder(), account, region);
EventRuleQueue queue = EventRuleQueue.route(account, region.id(), name, pattern)) {
String arn = rds.createDBCluster(r -> r.dbClusterIdentifier(name)
.engine("aurora-postgresql").masterUsername("admin").masterUserPassword("password123"))
.dbCluster().dbClusterArn();
try {
rds.stopDBCluster(r -> r.dbClusterIdentifier(name));
rds.startDBCluster(r -> r.dbClusterIdentifier(name));
List<JsonNode> events = queue.drain();
assertEquals(2, events.size());
assertEvent(find(events, "RDS-EVENT-0150"), account, region, arn, name, true, false);
assertEvent(find(events, "RDS-EVENT-0151"), account, region, arn, name, true, true);
} finally {
rds.deleteDBCluster(r -> r.dbClusterIdentifier(name).skipFinalSnapshot(true));
}
}
}
private JsonNode find(List<JsonNode> events, String eventId) {
return events.stream().filter(e -> eventId.equals(e.path("detail").path("EventID").asText()))
.findFirst().orElseThrow();
}
private void assertEvent(JsonNode event, String account, Region region, String arn, String id,
boolean cluster, boolean started) {
assertEquals("aws.rds", event.path("source").asText());
assertEquals(cluster ? "RDS DB Cluster Event" : "RDS DB Instance Event",
event.path("detail-type").asText());
assertEquals(account, event.path("account").asText());
assertEquals(region.id(), event.path("region").asText());
assertEquals(mapper.valueToTree(List.of(arn)), event.path("resources"));
JsonNode detail = event.path("detail");
assertEquals(mapper.valueToTree(List.of("notification")), detail.path("EventCategories"));
assertEquals(cluster ? "CLUSTER" : "DB_INSTANCE", detail.path("SourceType").asText());
assertEquals(arn, detail.path("SourceArn").asText());
assertEquals(id, detail.path("SourceIdentifier").asText());
assertEquals("DB " + (cluster ? "cluster" : "instance") + (started ? " started." : " stopped."),
detail.path("Message").asText());
assertEquals(cluster ? (started ? "RDS-EVENT-0151" : "RDS-EVENT-0150")
: (started ? "RDS-EVENT-0088" : "RDS-EVENT-0087"), detail.path("EventID").asText());
assertFalse(Instant.parse(detail.path("Date").asText()).isAfter(Instant.now()));
}
}
@@ -19,6 +19,7 @@ import io.floci.aws.services.ec2.model.SecurityGroup;
import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.services.ec2.model.Vpc;
import io.floci.aws.services.ec2.model.VpcIpv6CidrBlockAssociation;
import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.kms.model.KmsKey;
import io.floci.aws.services.rds.container.AutoPauseListener;
@@ -164,6 +165,8 @@ class RdsServiceTest {
"docdb8.0");
private RdsService rdsService;
private EventBridgeService eventBridgeService;
private RdsEventPublisher eventPublisher;
private RdsContainerManager containerManager;
private RdsProxyManager proxyManager;
private Ec2Service ec2Service;
@@ -176,6 +179,8 @@ class RdsServiceTest {
@BeforeEach
void setUp() {
eventBridgeService = mock(EventBridgeService.class);
eventPublisher = new RdsEventPublisher(eventBridgeService, new ObjectMapper());
containerManager = mock(RdsContainerManager.class);
proxyManager = mock(RdsProxyManager.class);
ec2Service = mock(Ec2Service.class);
@@ -6110,6 +6115,71 @@ class RdsServiceTest {
assertNotEquals(a.getEndpoint().port(), b.getEndpoint().port());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void failedStopsDoNotPublishSuccessfulLifecycleEvents(boolean cluster) {
String id = "failed-stop";
createLifecycleResource(id, cluster);
doThrow(new IllegalStateException("backend stop failed")).when(containerManager).stop(any());
assertThrows(IllegalStateException.class, () -> stopLifecycleResource(id, cluster));
verifyNoInteractions(eventBridgeService);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void failedStartsDoNotPublishSuccessfulLifecycleEvents(boolean cluster) {
String id = "failed-start";
createLifecycleResource(id, cluster);
stopLifecycleResource(id, cluster);
clearInvocations(eventBridgeService);
when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("backend start failed"));
assertThrows(IllegalStateException.class, () -> {
if (cluster) {
rdsService.startDbCluster(id, "us-east-1");
} else {
rdsService.startDbInstance(id);
}
});
verifyNoInteractions(eventBridgeService);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void lifecycleDeliveryRunsAfterReleasingResourceAndServiceLocks(boolean cluster) {
String id = "unlocked-delivery";
createLifecycleResource(id, cluster);
Object resource = cluster ? rdsService.getDbCluster(id, "us-east-1") : rdsService.getDbInstance(id);
doAnswer(invocation -> {
assertFalse(Thread.holdsLock(rdsService));
assertFalse(Thread.holdsLock(resource));
return null;
}).when(eventBridgeService).publishServiceEvent(anyString(), anyString(), anyString(), anyString(), anyString());
stopLifecycleResource(id, cluster);
verify(eventBridgeService, times(cluster ? 2 : 1))
.publishServiceEvent(eq("aws.rds"), anyString(), anyString(), anyString(), eq("us-east-1"));
}
private void createLifecycleResource(String id, boolean cluster) {
if (cluster) {
rdsService.createDbCluster(id, "aurora-postgresql", "16.3",
"admin", "password", "dbname", false, null);
rdsService.createDbInstance(id + "-member", "aurora-postgresql", "16.3",
null, null, null, "db.r6g.large", 20, false, null, null, id);
} else {
rdsService.createDbInstance(id, "postgres", "16", "admin", "password", "dbname",
"db.t3.micro", 20, false, null, null, null);
}
}
private void stopLifecycleResource(String id, boolean cluster) {
if (cluster) {
rdsService.stopDbCluster(id, "us-east-1");
} else {
rdsService.stopDbInstance(id, null);
}
}
@Test
void stopAndStartDbInstanceReleaseAndRestoreTheContainerOnTheSameVolume() {
DbInstance created = rdsService.createDbInstance("standalone", "postgres", "16",
@@ -11343,7 +11413,7 @@ class RdsServiceTest {
return new RdsService(containerManager, proxyManager, ec2Service, regionResolver, config,
instances, clusters, parameterGroups, clusterParameterGroups, subnetGroups,
null, null, null, new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), null, kmsService);
new InMemoryStorage<>(), null, kmsService, eventPublisher);
}
private RdsService newService(RdsContainerManager containerManager,
@@ -11356,7 +11426,7 @@ class RdsServiceTest {
return new RdsService(containerManager, proxyManager, ec2Service, regionResolver, config,
instances, clusters, parameterGroups, clusterParameterGroups, new InMemoryStorage<>(),
secretsManager, null, null, new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), null, kmsService);
new InMemoryStorage<>(), null, kmsService, eventPublisher);
}
private RdsService proxyStoreService(
@@ -1,29 +1,38 @@
package io.floci.aws.services.rds;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import io.floci.aws.services.rds.model.DbCluster;
import io.floci.aws.services.rds.model.DbInstance;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EventRuleQueue;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static io.restassured.http.ContentType.URLENC;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -49,6 +58,11 @@ class RdsStopStartIntegrationTest {
@Inject
RdsService rdsService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void checkDocker() {
try {
@@ -65,6 +79,44 @@ class RdsStopStartIntegrationTest {
.formParam("Version", "2014-10-31");
}
@Test
void realClusterRecoveryEmitsMemberEventsAndKeepsSqlData() throws Exception {
String id = "native-events-" + Long.toUnsignedString(System.nanoTime(), 36);
String member = id + "-member";
String account = "000000000000";
String memberArn = "arn:aws:rds:us-east-1:" + account + ":db:" + member;
String pattern = "{\"source\":[\"aws.rds\"],\"resources\":[\"" + memberArn + "\"]}";
try (RdsClient rds = AwsTestClients.create(RdsClient.builder(), account, Region.US_EAST_1);
EventRuleQueue queue = EventRuleQueue.route(account, Region.US_EAST_1.id(), id, pattern)) {
rds.createDBCluster(r -> r.dbClusterIdentifier(id).engine("aurora-postgresql").engineVersion("16.3")
.masterUsername("admin").masterUserPassword("password123").databaseName("appdb"));
rds.createDBInstance(r -> r.dbInstanceIdentifier(member).dbClusterIdentifier(id)
.engine("aurora-postgresql").dbInstanceClass("db.r6g.large"));
try {
psql(rdsService.getDbCluster(id).getContainerId(),
"CREATE TABLE marker(v text); INSERT INTO marker VALUES ('native-event-row');");
rds.stopDBCluster(r -> r.dbClusterIdentifier(id));
assertEquals("stopped", rds.describeDBClusters(r -> r.dbClusterIdentifier(id))
.dbClusters().getFirst().status());
rds.startDBCluster(r -> r.dbClusterIdentifier(id));
assertTrue(psql(rdsService.getDbCluster(id).getContainerId(), "SELECT v FROM marker;")
.contains("native-event-row"));
List<JsonNode> messages = queue.drain();
assertEquals(2, messages.size());
for (int i = 0; i < messages.size(); i++) {
JsonNode event = messages.get(i);
assertEquals("RDS DB Instance Event", event.path("detail-type").asText());
assertEquals(memberArn, event.path("resources").get(0).asText());
assertEquals(i == 0 ? "RDS-EVENT-0087" : "RDS-EVENT-0088",
event.path("detail").path("EventID").asText());
}
} finally {
rds.deleteDBInstance(r -> r.dbInstanceIdentifier(member).skipFinalSnapshot(true));
rds.deleteDBCluster(r -> r.dbClusterIdentifier(id).skipFinalSnapshot(true));
}
}
}
@Test
void stoppedInstanceKeepsItsDataAndEndpointForTheStart() throws Exception {
String id = "stop-db-" + Long.toString(System.nanoTime(), 36);
@@ -24,11 +24,13 @@ public final class EventRuleQueue implements AutoCloseable {
private static final String TARGET_ID = "1";
private static final ObjectMapper MAPPER = new ObjectMapper();
private final String account;
private final String region;
private final String name;
private final String url;
private EventRuleQueue(String region, String name, String url) {
private EventRuleQueue(String account, String region, String name, String url) {
this.account = account;
this.region = region;
this.name = name;
this.url = url;
@@ -36,18 +38,23 @@ public final class EventRuleQueue implements AutoCloseable {
/** A queue named {@code name}, and a rule of the same name sending it the events {@code pattern} matches. */
public static EventRuleQueue route(String region, String name, String pattern) {
String url = call(region, "sqs", "AmazonSQS.CreateQueue", SQS_CONTENT_TYPE,
return route("AKID", region, name, pattern);
}
/** The same route in the selected {@code account}, including reads and cleanup. */
public static EventRuleQueue route(String account, String region, String name, String pattern) {
String url = call(account, region, "sqs", "AmazonSQS.CreateQueue", SQS_CONTENT_TYPE,
MAPPER.createObjectNode().put("QueueName", name)).jsonPath().getString("QueueUrl");
ObjectNode attributes = MAPPER.createObjectNode().put("QueueUrl", url);
attributes.putArray("AttributeNames").add("QueueArn");
String arn = call(region, "sqs", "AmazonSQS.GetQueueAttributes", SQS_CONTENT_TYPE, attributes)
String arn = call(account, region, "sqs", "AmazonSQS.GetQueueAttributes", SQS_CONTENT_TYPE, attributes)
.jsonPath().getString("Attributes.QueueArn");
call(region, "events", "AWSEvents.PutRule", EVENTS_CONTENT_TYPE,
call(account, region, "events", "AWSEvents.PutRule", EVENTS_CONTENT_TYPE,
MAPPER.createObjectNode().put("Name", name).put("EventPattern", pattern));
ObjectNode targets = MAPPER.createObjectNode().put("Rule", name);
targets.putArray("Targets").addObject().put("Id", TARGET_ID).put("Arn", arn);
call(region, "events", "AWSEvents.PutTargets", EVENTS_CONTENT_TYPE, targets);
return new EventRuleQueue(region, name, url);
call(account, region, "events", "AWSEvents.PutTargets", EVENTS_CONTENT_TYPE, targets);
return new EventRuleQueue(account, region, name, url);
}
/**
@@ -60,14 +67,14 @@ public final class EventRuleQueue implements AutoCloseable {
ObjectNode receive = MAPPER.createObjectNode().put("QueueUrl", url).put("MaxNumberOfMessages", 10)
.put("WaitTimeSeconds", 0);
while (true) {
Response response = call(region, "sqs", "AmazonSQS.ReceiveMessage", SQS_CONTENT_TYPE, receive);
Response response = call(account, region, "sqs", "AmazonSQS.ReceiveMessage", SQS_CONTENT_TYPE, receive);
JsonNode messages = MAPPER.readTree(response.asString()).path("Messages");
if (messages.isEmpty()) {
return events;
}
for (JsonNode message : messages) {
events.add(MAPPER.readTree(message.path("Body").asText()));
call(region, "sqs", "AmazonSQS.DeleteMessage", SQS_CONTENT_TYPE, MAPPER.createObjectNode()
call(account, region, "sqs", "AmazonSQS.DeleteMessage", SQS_CONTENT_TYPE, MAPPER.createObjectNode()
.put("QueueUrl", url).put("ReceiptHandle", message.path("ReceiptHandle").asText()));
}
}
@@ -78,16 +85,17 @@ public final class EventRuleQueue implements AutoCloseable {
public void close() {
ObjectNode targets = MAPPER.createObjectNode().put("Rule", name);
targets.putArray("Ids").add(TARGET_ID);
call(region, "events", "AWSEvents.RemoveTargets", EVENTS_CONTENT_TYPE, targets);
call(region, "events", "AWSEvents.DeleteRule", EVENTS_CONTENT_TYPE,
call(account, region, "events", "AWSEvents.RemoveTargets", EVENTS_CONTENT_TYPE, targets);
call(account, region, "events", "AWSEvents.DeleteRule", EVENTS_CONTENT_TYPE,
MAPPER.createObjectNode().put("Name", name));
call(region, "sqs", "AmazonSQS.DeleteQueue", SQS_CONTENT_TYPE,
call(account, region, "sqs", "AmazonSQS.DeleteQueue", SQS_CONTENT_TYPE,
MAPPER.createObjectNode().put("QueueUrl", url));
}
private static Response call(String region, String service, String target, String contentType, JsonNode body) {
private static Response call(String account, String region, String service, String target,
String contentType, JsonNode body) {
Response response = given()
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260215/" + region + "/" + service
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + account + "/20260215/" + region + "/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc")
.header("X-Amz-Target", target)
.contentType(contentType)