mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift): publish CloudWatch cluster metrics (#6740)
* feat(redshift): publish CloudWatch cluster metrics * fix(redshift): skip duplicate CloudWatch publication minutes * test(redshift): isolate metrics publisher between integration tests * fix(test): use Java 17 list access in Redshift metrics compatibility test * fix(metrics): share minute publishing and prevent duplicate SQS samples Centralize daemon scheduling, minute claims, per-target failures, retention and shutdown for SQS and Redshift. Carry the Redshift proxy key in metric targets and use the shared compatibility await fixture. * docs(metrics): restore publisher class docs after the shared publisher move Keep the SQS sample shape on SqsMetricsPublisher and document minute stamping, 15-day retention and the nothing-may-escape rule on MinuteMetricsPublisher.
This commit is contained in:
1 parent
f4ace9ebbe
commit
5bd4bd481a
22 files changed
+1061
-77
No files matched your search
+99
@@ -0,0 +1,99 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class MinuteMetricsPublisherTest {
|
||||
|
||||
private final CloudWatchMetricsService metrics = mock(CloudWatchMetricsService.class);
|
||||
private final ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);
|
||||
private final Clock clock = Clock.fixed(Instant.parse("2026-10-27T12:34:20Z"), ZoneOffset.UTC);
|
||||
|
||||
@Test
|
||||
void startupAlignsTicksToTheMinuteAndStampsTheEndedMinute() {
|
||||
MinuteMetricsPublisher<String> publisher = publisher(true);
|
||||
publisher.start();
|
||||
ArgumentCaptor<Runnable> tick = ArgumentCaptor.forClass(Runnable.class);
|
||||
verify(scheduler).scheduleAtFixedRate(tick.capture(), eq(41_000L), eq(60_000L), eq(TimeUnit.MILLISECONDS));
|
||||
|
||||
tick.getValue().run();
|
||||
tick.getValue().run();
|
||||
|
||||
ArgumentCaptor<List<MetricDatum>> datums = ArgumentCaptor.forClass(List.class);
|
||||
verify(metrics).putMetricDataForAccount(eq("111111111111"), eq("AWS/Test"), datums.capture(), eq("us-east-1"));
|
||||
assertEquals(Instant.parse("2026-10-27T12:33:00Z").getEpochSecond(),
|
||||
datums.getValue().getFirst().getTimestamp());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledPublisherDoesNotScheduleTicks() {
|
||||
publisher(false).start();
|
||||
|
||||
verifyNoInteractions(scheduler, metrics);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownWaitsFiveSecondsForAnActiveTick() throws Exception {
|
||||
publisher(true).stop();
|
||||
|
||||
verify(scheduler).shutdown();
|
||||
verify(scheduler).awaitTermination(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownRestoresTheInterruptFlag() throws Exception {
|
||||
when(scheduler.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(new InterruptedException("stopping"));
|
||||
try {
|
||||
publisher(true).stop();
|
||||
|
||||
assertTrue(Thread.currentThread().isInterrupted());
|
||||
} finally {
|
||||
Thread.interrupted();
|
||||
}
|
||||
}
|
||||
|
||||
private MinuteMetricsPublisher<String> publisher(boolean enabled) {
|
||||
return new MinuteMetricsPublisher<>(metrics, "AWS/Test", enabled, clock, scheduler) {
|
||||
@Override
|
||||
protected List<String> collectTargets(Instant now) {
|
||||
return List.of("target");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<MetricDatum> collectDatums(String target, long timestampSeconds) {
|
||||
return List.of(MetricDatum.of("Value", "Count", 1, List.of(), timestampSeconds));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String accountId(String target) {
|
||||
return "111111111111";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String region(String target) {
|
||||
return "us-east-1";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String targetName(String target) {
|
||||
return target;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader
|
||||
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
|
||||
import io.github.hectorvent.floci.services.redshift.metrics.RedshiftMetricTarget;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
|
||||
import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
|
||||
@@ -63,6 +64,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.*;
|
||||
@@ -2398,6 +2400,39 @@ class RedshiftServiceTest {
|
||||
assertEquals("0", reloaded.getParameters().getFirst().getParameterValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void availableMetricTargetsListsOnlyAvailableClustersOfEveryAccountWithTheirRegion() {
|
||||
Cluster available = new Cluster();
|
||||
available.setClusterIdentifier("warehouse");
|
||||
available.setClusterStatus("available");
|
||||
available.setSnapshotRegion("eu-west-1");
|
||||
Cluster otherAccount = new Cluster();
|
||||
otherAccount.setClusterIdentifier("warehouse");
|
||||
otherAccount.setClusterStatus("available");
|
||||
Cluster creating = new Cluster();
|
||||
creating.setClusterIdentifier("new");
|
||||
creating.setClusterStatus("creating");
|
||||
Cluster deleting = new Cluster();
|
||||
deleting.setClusterIdentifier("old");
|
||||
deleting.setClusterStatus("deleting");
|
||||
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
|
||||
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "warehouse", available),
|
||||
new AccountAwareStorageBackend.AccountEntry<>("222222222222", "warehouse", otherAccount),
|
||||
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "new", creating),
|
||||
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "old", deleting)));
|
||||
|
||||
List<RedshiftMetricTarget> targets = service.availableMetricTargets();
|
||||
|
||||
assertEquals(2, targets.size());
|
||||
assertEquals("111111111111", targets.get(0).accountId());
|
||||
assertEquals("eu-west-1", targets.get(0).region());
|
||||
assertEquals("111111111111:warehouse", targets.get(0).proxyKey());
|
||||
assertSame(available, targets.get(0).cluster());
|
||||
assertEquals("222222222222", targets.get(1).accountId());
|
||||
assertEquals("222222222222:warehouse", targets.get(1).proxyKey());
|
||||
assertSame(otherAccount, targets.get(1).cluster());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAndListTagsForCluster() {
|
||||
Cluster cluster = new Cluster();
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package io.github.hectorvent.floci.services.redshift.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftClusterStateMetricCollectorTest {
|
||||
|
||||
private static final String KEY = "proxy-key-supplied-by-redshift-service";
|
||||
private static final long TIMESTAMP = 1_793_102_340L;
|
||||
|
||||
private final RedshiftProxyManager proxies = mock(RedshiftProxyManager.class);
|
||||
private final RedshiftClusterStateMetricCollector collector = new RedshiftClusterStateMetricCollector(proxies);
|
||||
|
||||
private static RedshiftMetricTarget target(String status) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("warehouse");
|
||||
cluster.setClusterStatus(status);
|
||||
return new RedshiftMetricTarget("111111111111", "us-east-1", cluster, KEY);
|
||||
}
|
||||
|
||||
private static Map<String, MetricDatum> byName(List<MetricDatum> datums) {
|
||||
return datums.stream().collect(Collectors.toMap(MetricDatum::getMetricName, Function.identity()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void availableClusterReportsHealthMaintenanceAndConnections() {
|
||||
when(proxies.activeConnections(KEY)).thenReturn(OptionalInt.of(3));
|
||||
|
||||
Map<String, MetricDatum> datums = byName(collector.collect(target("available"), TIMESTAMP));
|
||||
|
||||
assertEquals(3, datums.size());
|
||||
assertEquals(1.0, datums.get("HealthStatus").getValue());
|
||||
assertEquals(0.0, datums.get("MaintenanceMode").getValue());
|
||||
assertEquals(3.0, datums.get("DatabaseConnections").getValue());
|
||||
for (MetricDatum datum : datums.values()) {
|
||||
assertEquals("Count", datum.getUnit());
|
||||
assertEquals(TIMESTAMP, datum.getTimestamp());
|
||||
assertEquals(List.of(new Dimension("ClusterIdentifier", "warehouse")), datum.getDimensions());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"creating", "deleting", "failed", "unavailable"})
|
||||
void clusterNotAvailableReportsNothing(String status) {
|
||||
when(proxies.activeConnections(KEY)).thenReturn(OptionalInt.of(3));
|
||||
|
||||
assertTrue(collector.collect(target(status), TIMESTAMP).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingProxyOmitsDatabaseConnections() {
|
||||
when(proxies.activeConnections(KEY)).thenReturn(OptionalInt.empty());
|
||||
|
||||
Map<String, MetricDatum> datums = byName(collector.collect(target("available"), TIMESTAMP));
|
||||
|
||||
assertEquals(2, datums.size());
|
||||
assertTrue(datums.containsKey("HealthStatus"));
|
||||
assertTrue(datums.containsKey("MaintenanceMode"));
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package io.github.hectorvent.floci.services.redshift.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService.Datapoint;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService.MetricIdentity;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class RedshiftMetricsIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String NAMESPACE = "AWS/Redshift";
|
||||
|
||||
@Inject
|
||||
RedshiftService redshift;
|
||||
|
||||
@Inject
|
||||
Instance<RedshiftMetricCollector> collectors;
|
||||
|
||||
@Inject
|
||||
CloudWatchMetricsService cloudWatch;
|
||||
|
||||
private RedshiftMetricsPublisher publisher;
|
||||
private String clusterId;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
publisher = new RedshiftMetricsPublisher(redshift, cloudWatch, collectors, true);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUp() {
|
||||
publisher.onStop(null);
|
||||
if (clusterId != null) {
|
||||
redshift.deleteCluster(clusterId);
|
||||
clusterId = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The minute a tick stamps its samples with, read back alone so the scheduler's own ticks cannot interfere. */
|
||||
private List<Datapoint> statisticsAt(String metricName, String identifier, Instant tick) {
|
||||
Instant minute = tick.minusSeconds(30).truncatedTo(ChronoUnit.MINUTES);
|
||||
return cloudWatch.getMetricStatistics(NAMESPACE, metricName,
|
||||
List.of(new Dimension("ClusterIdentifier", identifier)), minute, minute.plusSeconds(59), 60,
|
||||
List.of("Sum"), null, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createdClusterPublishesItsStateMetricsReadableThroughCloudWatch() {
|
||||
clusterId = "it-metrics-state";
|
||||
redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
|
||||
Instant tick = Instant.now().plusSeconds(100);
|
||||
|
||||
publisher.publish(tick);
|
||||
|
||||
Set<String> names = cloudWatch.listMetrics(NAMESPACE, null,
|
||||
List.of(new Dimension("ClusterIdentifier", clusterId)), REGION).stream()
|
||||
.map(MetricIdentity::metricName).collect(Collectors.toSet());
|
||||
assertEquals(Set.of("HealthStatus", "MaintenanceMode", "DatabaseConnections"), names);
|
||||
|
||||
List<Datapoint> health = statisticsAt("HealthStatus", clusterId, tick);
|
||||
assertEquals(1, health.size());
|
||||
assertEquals(1.0, health.getFirst().sum());
|
||||
assertEquals("Count", health.getFirst().unit());
|
||||
assertEquals(0.0, statisticsAt("DatabaseConnections", clusterId, tick).getFirst().sum());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletedClusterStopsPublishing() {
|
||||
clusterId = "it-metrics-deleted";
|
||||
redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
|
||||
Instant whileAvailable = Instant.now().plusSeconds(100);
|
||||
publisher.publish(whileAvailable);
|
||||
assertEquals(1, statisticsAt("HealthStatus", clusterId, whileAvailable).size());
|
||||
|
||||
redshift.deleteCluster(clusterId);
|
||||
String deleted = clusterId;
|
||||
clusterId = null;
|
||||
Instant afterDelete = whileAvailable.plusSeconds(600);
|
||||
publisher.publish(afterDelete);
|
||||
|
||||
assertTrue(statisticsAt("HealthStatus", deleted, afterDelete).isEmpty(),
|
||||
"a deleted cluster must publish no samples");
|
||||
}
|
||||
}
|
||||
+225
@@ -0,0 +1,225 @@
|
||||
package io.github.hectorvent.floci.services.redshift.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftMetricsPublisherTest {
|
||||
|
||||
private static final String REGION = "eu-west-1";
|
||||
private static final String NAMESPACE = "AWS/Redshift";
|
||||
|
||||
private RedshiftService redshift;
|
||||
private CloudWatchMetricsService cloudWatch;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
redshift = mock(RedshiftService.class);
|
||||
cloudWatch = mock(CloudWatchMetricsService.class);
|
||||
}
|
||||
|
||||
private static RedshiftMetricTarget target(String accountId, String identifier) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier(identifier);
|
||||
cluster.setClusterStatus("available");
|
||||
return new RedshiftMetricTarget(accountId, REGION, cluster, "proxy-for-" + identifier);
|
||||
}
|
||||
|
||||
private static MetricDatum sample(String identifier, long timestamp) {
|
||||
return MetricDatum.of("HealthStatus", "Count", 1, List.of(new Dimension("ClusterIdentifier", identifier)),
|
||||
timestamp);
|
||||
}
|
||||
|
||||
private RedshiftMetricsPublisher publisher(RedshiftMetricCollector... collectors) {
|
||||
return new RedshiftMetricsPublisher(redshift, cloudWatch, List.of(collectors), true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishWritesCollectorSamplesStampedWithTheEndedMinute() {
|
||||
when(redshift.availableMetricTargets()).thenReturn(List.of(target("111111111111", "warehouse")));
|
||||
List<Long> stamps = new ArrayList<>();
|
||||
RedshiftMetricCollector collector = (target, timestamp) -> {
|
||||
stamps.add(timestamp);
|
||||
return List.of(sample(target.cluster().getClusterIdentifier(), timestamp));
|
||||
};
|
||||
|
||||
publisher(collector).publish(Instant.parse("2026-10-27T12:00:20Z"));
|
||||
|
||||
long endedMinute = Instant.parse("2026-10-27T11:59:00Z").getEpochSecond();
|
||||
assertEquals(List.of(endedMinute), stamps);
|
||||
ArgumentCaptor<List<MetricDatum>> written = ArgumentCaptor.forClass(List.class);
|
||||
verify(cloudWatch).putMetricDataForAccount(eq("111111111111"), eq(NAMESPACE), written.capture(), eq(REGION));
|
||||
assertEquals(1, written.getValue().size());
|
||||
assertEquals("HealthStatus", written.getValue().getFirst().getMetricName());
|
||||
assertEquals(endedMinute, written.getValue().getFirst().getTimestamp());
|
||||
}
|
||||
|
||||
@Test
|
||||
void overdueTicksPublishEachMinuteOnlyOnce() {
|
||||
when(redshift.availableMetricTargets()).thenReturn(List.of(target("111111111111", "warehouse")));
|
||||
RedshiftMetricsPublisher publisher = publisher((target, timestamp) -> List.of(sample("warehouse", timestamp)));
|
||||
|
||||
publisher.publish(Instant.parse("2026-10-27T12:04:01Z"));
|
||||
publisher.publish(Instant.parse("2026-10-27T12:04:02Z"));
|
||||
publisher.publish(Instant.parse("2026-10-27T12:04:20Z"));
|
||||
publisher.publish(Instant.parse("2026-10-27T12:05:01Z"));
|
||||
|
||||
ArgumentCaptor<List<MetricDatum>> written = ArgumentCaptor.forClass(List.class);
|
||||
verify(cloudWatch, times(2)).putMetricDataForAccount(eq("111111111111"), eq(NAMESPACE),
|
||||
written.capture(), eq(REGION));
|
||||
assertEquals(List.of(Instant.parse("2026-10-27T12:03:00Z").getEpochSecond(),
|
||||
Instant.parse("2026-10-27T12:04:00Z").getEpochSecond()),
|
||||
written.getAllValues().stream().map(datums -> datums.getFirst().getTimestamp()).toList());
|
||||
verify(redshift, times(2)).availableMetricTargets();
|
||||
}
|
||||
|
||||
@Test
|
||||
void clockMovingBackwardsDoesNotRepublishAnEarlierMinute() {
|
||||
when(redshift.availableMetricTargets()).thenReturn(List.of(target("111111111111", "warehouse")));
|
||||
RedshiftMetricsPublisher publisher = publisher((target, timestamp) -> List.of(sample("warehouse", timestamp)));
|
||||
|
||||
publisher.publish(Instant.parse("2026-10-27T12:04:01Z"));
|
||||
publisher.publish(Instant.parse("2026-10-27T12:03:01Z"));
|
||||
publisher.publish(Instant.parse("2026-10-27T12:04:01Z"));
|
||||
|
||||
verify(cloudWatch).putMetricDataForAccount(eq("111111111111"), eq(NAMESPACE), anyList(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedWriteIsNotRetriedWithinTheMinute() {
|
||||
when(redshift.availableMetricTargets()).thenReturn(List.of(target("111111111111", "warehouse")));
|
||||
doThrow(new IllegalStateException("write may have stored some samples")).when(cloudWatch)
|
||||
.putMetricDataForAccount(anyString(), anyString(), anyList(), anyString());
|
||||
RedshiftMetricsPublisher publisher = publisher((target, timestamp) -> List.of(sample("warehouse", timestamp)));
|
||||
|
||||
publisher.publish(Instant.parse("2026-10-27T12:04:01Z"));
|
||||
publisher.publish(Instant.parse("2026-10-27T12:04:02Z"));
|
||||
|
||||
verify(cloudWatch).putMetricDataForAccount(eq("111111111111"), eq(NAMESPACE), anyList(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aThrowingCollectorDropsOnlyThatClustersSamples() {
|
||||
when(redshift.availableMetricTargets()).thenReturn(List.of(
|
||||
target("111111111111", "broken"), target("111111111111", "healthy")));
|
||||
RedshiftMetricCollector collector = (target, timestamp) -> {
|
||||
if ("broken".equals(target.cluster().getClusterIdentifier())) {
|
||||
throw new IllegalStateException("collector failed");
|
||||
}
|
||||
return List.of(sample(target.cluster().getClusterIdentifier(), timestamp));
|
||||
};
|
||||
|
||||
assertDoesNotThrow(() -> publisher(collector).publish(Instant.parse("2026-10-27T12:00:20Z")));
|
||||
|
||||
ArgumentCaptor<List<MetricDatum>> written = ArgumentCaptor.forClass(List.class);
|
||||
verify(cloudWatch).putMetricDataForAccount(eq("111111111111"), eq(NAMESPACE), written.capture(), eq(REGION));
|
||||
assertEquals("healthy", written.getValue().getFirst().getDimensions().getFirst().value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedWriteForOneClusterDoesNotStopTheNext() {
|
||||
when(redshift.availableMetricTargets()).thenReturn(List.of(
|
||||
target("111111111111", "first"), target("222222222222", "second")));
|
||||
doThrow(new IllegalStateException("store failed")).when(cloudWatch)
|
||||
.putMetricDataForAccount(eq("111111111111"), anyString(), anyList(), anyString());
|
||||
|
||||
assertDoesNotThrow(() -> publisher((target, timestamp) -> List.of(sample("x", timestamp)))
|
||||
.publish(Instant.parse("2026-10-27T12:00:20Z")));
|
||||
|
||||
verify(cloudWatch).putMetricDataForAccount(eq("222222222222"), eq(NAMESPACE), anyList(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameClusterIdentifierInTwoAccountsLandsInEachAccount() {
|
||||
when(redshift.availableMetricTargets()).thenReturn(List.of(
|
||||
target("111111111111", "warehouse"), target("222222222222", "warehouse")));
|
||||
|
||||
publisher((target, timestamp) -> List.of(sample("warehouse", timestamp)))
|
||||
.publish(Instant.parse("2026-10-27T12:00:20Z"));
|
||||
|
||||
verify(cloudWatch).putMetricDataForAccount(eq("111111111111"), eq(NAMESPACE), anyList(), eq(REGION));
|
||||
verify(cloudWatch).putMetricDataForAccount(eq("222222222222"), eq(NAMESPACE), anyList(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWithNoSamplesWritesNothing() {
|
||||
when(redshift.availableMetricTargets()).thenReturn(List.of(target("111111111111", "warehouse")));
|
||||
|
||||
publisher((target, timestamp) -> List.of()).publish(Instant.parse("2026-10-27T12:00:20Z"));
|
||||
|
||||
verify(cloudWatch, never()).putMetricDataForAccount(anyString(), anyString(), anyList(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enumerationFailureDropsTheTickWithoutThrowing() {
|
||||
when(redshift.availableMetricTargets()).thenThrow(new IllegalStateException("storage unavailable"));
|
||||
|
||||
assertDoesNotThrow(() -> publisher((target, timestamp) -> List.of(sample("x", timestamp)))
|
||||
.publish(Instant.parse("2026-10-27T12:00:20Z")));
|
||||
|
||||
verify(cloudWatch, never()).putMetricDataForAccount(anyString(), anyString(), anyList(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishDropsDatapointsOlderThanFifteenDaysOnTheHour() {
|
||||
when(redshift.availableMetricTargets()).thenReturn(List.of());
|
||||
RedshiftMetricsPublisher publisher = publisher();
|
||||
|
||||
publisher.publish(Instant.parse("2026-10-27T12:01:00Z"));
|
||||
|
||||
Instant hour = Instant.parse("2026-10-27T12:00:00Z");
|
||||
verify(cloudWatch).deleteMetricDataBefore(NAMESPACE, hour.minus(Duration.ofDays(15)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishKeepsHistoryBetweenHours() {
|
||||
when(redshift.availableMetricTargets()).thenReturn(List.of());
|
||||
|
||||
publisher().publish(Instant.parse("2026-10-27T12:30:20Z"));
|
||||
|
||||
verify(cloudWatch, never()).deleteMetricDataBefore(anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isDisabledWhenTheFlagOrCloudwatchMetricsIsOff() {
|
||||
assertTrue(RedshiftMetricsPublisher.isEnabled(config(true, true, true)));
|
||||
assertFalse(RedshiftMetricsPublisher.isEnabled(config(true, false, true)));
|
||||
assertFalse(RedshiftMetricsPublisher.isEnabled(config(true, true, false)));
|
||||
assertFalse(RedshiftMetricsPublisher.isEnabled(config(false, true, true)));
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(boolean redshiftEnabled, boolean flag, boolean cloudwatchEnabled) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);
|
||||
when(config.services().redshift().enabled()).thenReturn(redshiftEnabled);
|
||||
when(config.services().redshift().cloudwatchMetricsEnabled()).thenReturn(flag);
|
||||
when(config.services().cloudwatchmetrics().enabled()).thenReturn(cloudwatchEnabled);
|
||||
return config;
|
||||
}
|
||||
}
|
||||
+27
@@ -235,6 +235,33 @@ class RedshiftAuthProxyTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeConnectionsCountsOpenClientsAndFallsOnClose() throws Exception {
|
||||
fakeBackend = new ServerSocket(0);
|
||||
int proxyPort = FreePorts.anyInterfacePort();
|
||||
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
|
||||
"admin", "Secret123", "dev",
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
|
||||
mock(S3Service.class), mock(IamService.class), 5000, 5000, 5);
|
||||
proxy.start(proxyPort);
|
||||
assertEquals(0, proxy.activeConnections());
|
||||
|
||||
try (Socket first = new Socket("localhost", proxyPort); Socket second = new Socket("localhost", proxyPort)) {
|
||||
awaitActiveConnections(2);
|
||||
first.close();
|
||||
awaitActiveConnections(1);
|
||||
}
|
||||
awaitActiveConnections(0);
|
||||
}
|
||||
|
||||
private void awaitActiveConnections(int expected) throws InterruptedException {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
||||
while (proxy.activeConnections() != expected && System.nanoTime() < deadline) {
|
||||
Thread.sleep(25);
|
||||
}
|
||||
assertEquals(expected, proxy.activeConnections());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startRetriesTheBindWhileThePortIsMomentarilyStillInUse() throws Exception {
|
||||
fakeBackend = new ServerSocket(0);
|
||||
|
||||
+14
@@ -14,6 +14,7 @@ import java.lang.reflect.Field;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.List;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
@@ -88,6 +89,19 @@ class RedshiftProxyManagerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeConnectionsIsEmptyWithoutAProxyAndZeroForAnIdleOne() throws Exception {
|
||||
RedshiftProxyManager manager = newManager();
|
||||
int port = FreePorts.anyInterfacePort();
|
||||
try {
|
||||
assertEquals(OptionalInt.empty(), manager.activeConnections(KEY));
|
||||
start(manager, KEY, port);
|
||||
assertEquals(OptionalInt.of(0), manager.activeConnections(KEY));
|
||||
} finally {
|
||||
manager.stopAll();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopProxyRemovesTheKeyAndReleasesThePort() throws Exception {
|
||||
RedshiftProxyManager manager = newManager();
|
||||
|
||||
@@ -39,6 +39,52 @@ class SqsMetricsPublisherTest {
|
||||
private CloudWatchMetricsService cloudWatch;
|
||||
private SqsMetricsPublisher publisher;
|
||||
|
||||
@Test
|
||||
void overdueTicksDoNotDuplicateSamplesOrDrainTheNextMinutesActivity() {
|
||||
String url = sqs.createQueue("overdue", null, REGION).getQueueUrl();
|
||||
sqs.sendMessage(url, "first", null, REGION);
|
||||
Instant tick = Instant.now().truncatedTo(ChronoUnit.MINUTES).plusSeconds(1);
|
||||
publisher.publish(tick);
|
||||
sqs.sendMessage(url, "next", null, REGION);
|
||||
|
||||
publisher.publish(tick.plusSeconds(1));
|
||||
publisher.publish(tick.plusSeconds(60));
|
||||
|
||||
assertSamples(datapoint("overdue", "NumberOfMessagesSent", tick), 2, 1, 0, 1, "Count");
|
||||
assertSamples(datapoint("overdue", "NumberOfMessagesSent", tick.plusSeconds(60)), 2, 1, 0, 1, "Count");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clockRollbackDoesNotRepublishAnEarlierMinute() {
|
||||
sqs.createQueue("rollback", null, REGION);
|
||||
Instant tick = Instant.now().truncatedTo(ChronoUnit.MINUTES).plusSeconds(1);
|
||||
publisher.publish(tick);
|
||||
|
||||
publisher.publish(tick.minusSeconds(60));
|
||||
publisher.publish(tick);
|
||||
|
||||
assertSamples(datapoint("rollback", "NumberOfMessagesSent", tick), 1, 0, 0, 0, "Count");
|
||||
assertNull(datapoint("rollback", "NumberOfMessagesSent", tick.minusSeconds(60)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartiallyFailedWriteIsNotRetriedWithinTheMinute() {
|
||||
sqs.createQueue("partial", null, REGION);
|
||||
CloudWatchMetricsService failing = spy(cloudWatch);
|
||||
doAnswer(invocation -> {
|
||||
invocation.callRealMethod();
|
||||
throw new IllegalStateException("failed after writing samples");
|
||||
}).when(failing).putMetricDataForAccount(any(), any(), any(), any());
|
||||
SqsMetricsPublisher partial = new SqsMetricsPublisher(sqs, failing,
|
||||
mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS));
|
||||
Instant tick = Instant.now().truncatedTo(ChronoUnit.MINUTES).plusSeconds(1);
|
||||
|
||||
partial.publish(tick);
|
||||
partial.publish(tick.plusSeconds(1));
|
||||
|
||||
assertSamples(datapoint("partial", "NumberOfMessagesSent", tick), 1, 0, 0, 0, "Count");
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
RegionResolver resolver = new RegionResolver(REGION, ACCOUNT);
|
||||
|
||||
Reference in new issue
Block a user