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:
Vũ Thế Huy authored and GitHub committed 2026-10-27 22:03:23 -04:00
1 parent f4ace9ebbe
commit 5bd4bd481a
22 files changed
+1061 -77

No files matched your search

@@ -1725,6 +1725,13 @@ public interface EmulatorConfig {
interface RedshiftServiceConfig {
@WithDefault("true")
boolean automatedSnapshotsEnabled();
/**
* Publish the AWS/Redshift CloudWatch metrics of every available cluster once a minute.
* Env: FLOCI_SERVICES_REDSHIFT_CLOUDWATCH_METRICS_ENABLED
*/
@WithDefault("true")
boolean cloudwatchMetricsEnabled();
@WithDefault("60")
long snapshotSweepIntervalSeconds();
@WithDefault("true")
@@ -0,0 +1,127 @@
package io.github.hectorvent.floci.services.cloudwatch.metrics;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
import org.jboss.logging.Logger;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Shared scheduling, minute claims and retention for service-generated CloudWatch metrics. A tick
* runs just after each minute boundary and stamps its samples with the minute that ended, so a call
* lands in the minute it was made, as on AWS. Once an hour it drops the namespace's datapoints older
* than the 15 days AWS keeps one-minute data, so the generated history stays bounded.
*/
public abstract class MinuteMetricsPublisher<T> {
private static final Logger LOG = Logger.getLogger(MinuteMetricsPublisher.class);
private static final long MINUTE_MILLIS = 60_000;
private static final long TICK_OFFSET_MILLIS = 1_000;
private static final Duration RETENTION = Duration.ofDays(15);
private final CloudWatchMetricsService metricsService;
private final String namespace;
private final boolean enabled;
private final Clock clock;
private final ScheduledExecutorService scheduler;
private long lastAttemptedMinute = Long.MIN_VALUE;
protected MinuteMetricsPublisher(CloudWatchMetricsService metricsService, String namespace, boolean enabled) {
this(metricsService, namespace, enabled, Clock.systemUTC(), Executors.newSingleThreadScheduledExecutor(task -> {
Thread thread = new Thread(task, namespace + "-metrics-publisher");
thread.setDaemon(true);
return thread;
}));
}
protected MinuteMetricsPublisher(CloudWatchMetricsService metricsService, String namespace, boolean enabled,
Clock clock, ScheduledExecutorService scheduler) {
this.metricsService = metricsService;
this.namespace = namespace;
this.enabled = enabled;
this.clock = clock;
this.scheduler = scheduler;
}
public void start() {
if (!enabled) {
return;
}
long untilNextMinute = MINUTE_MILLIS - clock.millis() % MINUTE_MILLIS;
scheduler.scheduleAtFixedRate(() -> publish(clock.instant()), untilNextMinute + TICK_OFFSET_MILLIS,
MINUTE_MILLIS, TimeUnit.MILLISECONDS);
}
/** Finish a running tick before EmulatorLifecycle shuts down storage. */
public void stop() {
scheduler.shutdown();
try {
if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
LOG.warnv("The {0} metrics publisher did not finish its tick within 5 seconds", namespace);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.warnv(e, "Interrupted while stopping the {0} metrics publisher", namespace);
}
}
/**
* Nothing may escape: the scheduler stops for good after a tick throws. One target's failed write
* drops only that target's samples for the minute.
*/
public synchronized void publish(Instant now) {
long minute = endedMinute(now);
if (minute <= lastAttemptedMinute) {
return;
}
// Collection can drain counters, and a failed write may already have stored some samples.
lastAttemptedMinute = minute;
List<T> targets;
try {
targets = collectTargets(now);
} catch (RuntimeException e) {
LOG.warnv(e, "Collecting {0} metric targets failed; this minute's samples are dropped", namespace);
return;
}
for (T target : targets) {
try {
List<MetricDatum> datums = collectDatums(target, minute);
if (!datums.isEmpty()) {
metricsService.putMetricDataForAccount(accountId(target), namespace, datums, region(target));
}
} catch (RuntimeException e) {
LOG.warnv(e, "Publishing {0} metrics for {1} of account {2} in {3} failed; its samples are dropped",
namespace, targetName(target), accountId(target), region(target));
}
}
if (minute % 3600 == 0) {
try {
metricsService.deleteMetricDataBefore(namespace, Instant.ofEpochSecond(minute).minus(RETENTION));
} catch (RuntimeException e) {
LOG.warnv(e, "Dropping {0} datapoints older than {1} failed; the next hour tries again",
namespace, RETENTION);
}
}
}
/** Reading half a minute back absorbs drift of the fixed-rate schedule away from the boundary. */
private static long endedMinute(Instant tick) {
return tick.minusSeconds(30).truncatedTo(ChronoUnit.MINUTES).getEpochSecond();
}
protected abstract List<T> collectTargets(Instant now);
protected abstract List<MetricDatum> collectDatums(T target, long timestampSeconds);
protected abstract String accountId(T target);
protected abstract String region(T target);
protected abstract String targetName(T target);
}
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.redshift.RedshiftEventCatalog.EventInfo;
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.AutomatedSnapshotState;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
@@ -788,6 +789,15 @@ public class RedshiftService implements ManagedSecretRotator {
return clusters.scanForAccount(accountId, k -> true);
}
/** The available clusters of every account, for the AWS/Redshift metrics publisher. */
public List<RedshiftMetricTarget> availableMetricTargets() {
return clusters.scanAllAccountEntries(k -> true).stream()
.filter(entry -> "available".equals(entry.value().getClusterStatus()))
.map(entry -> new RedshiftMetricTarget(entry.accountId(), snapshotRegion(entry.value()),
entry.value(), relayKey(entry.accountId(), entry.value().getClusterIdentifier())))
.toList();
}
/** Internal deletion used by provisioner cleanup, which explicitly skips the final snapshot. */
public Cluster deleteCluster(String identifier) {
return deleteCluster(identifier, true, null, null);
@@ -0,0 +1,47 @@
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.proxy.RedshiftProxyManager;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalInt;
/**
* The metrics Floci can report from its own state: health and maintenance follow the cluster status, and
* DatabaseConnections is the number of clients open on the cluster's auth proxy. Data API connections
* reach the database around that proxy and are not counted.
*/
@ApplicationScoped
public class RedshiftClusterStateMetricCollector implements RedshiftMetricCollector {
private static final String COUNT = "Count";
private final RedshiftProxyManager proxyManager;
@Inject
public RedshiftClusterStateMetricCollector(RedshiftProxyManager proxyManager) {
this.proxyManager = proxyManager;
}
@Override
public List<MetricDatum> collect(RedshiftMetricTarget target, long timestampSeconds) {
if (!"available".equals(target.cluster().getClusterStatus())) {
return List.of();
}
String identifier = target.cluster().getClusterIdentifier();
List<Dimension> dimensions = List.of(new Dimension("ClusterIdentifier", identifier));
List<MetricDatum> datums = new ArrayList<>(List.of(
MetricDatum.of("HealthStatus", COUNT, 1, dimensions, timestampSeconds),
MetricDatum.of("MaintenanceMode", COUNT, 0, dimensions, timestampSeconds)));
OptionalInt connections = proxyManager.activeConnections(target.proxyKey());
if (connections.isPresent()) {
datums.add(MetricDatum.of("DatabaseConnections", COUNT, connections.getAsInt(), dimensions,
timestampSeconds));
}
return datums;
}
}
@@ -0,0 +1,15 @@
package io.github.hectorvent.floci.services.redshift.metrics;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
import java.util.List;
/**
* Supplies AWS/Redshift samples for one cluster each minute. Every CDI bean of this type is asked by
* {@link RedshiftMetricsPublisher}; a collector returns nothing for a cluster it has no real value for.
*/
public interface RedshiftMetricCollector {
/** {@code timestampSeconds} is the epoch second of the minute that ended; stamp every sample with it. */
List<MetricDatum> collect(RedshiftMetricTarget target, long timestampSeconds);
}
@@ -0,0 +1,6 @@
package io.github.hectorvent.floci.services.redshift.metrics;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
/** One cluster to publish metrics for, with the account and region its samples belong to. */
public record RedshiftMetricTarget(String accountId, String region, Cluster cluster, String proxyKey) { }
@@ -0,0 +1,85 @@
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.MinuteMetricsPublisher;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/** Supplies available clusters and collector samples to the shared minute publisher. */
@ApplicationScoped
public class RedshiftMetricsPublisher {
static final String NAMESPACE = "AWS/Redshift";
private final MinuteMetricsPublisher<RedshiftMetricTarget> publisher;
@Inject
public RedshiftMetricsPublisher(RedshiftService redshiftService, CloudWatchMetricsService metricsService,
Instance<RedshiftMetricCollector> collectors, EmulatorConfig config) {
this(redshiftService, metricsService, collectors, isEnabled(config));
}
RedshiftMetricsPublisher(RedshiftService redshiftService, CloudWatchMetricsService metricsService,
Iterable<RedshiftMetricCollector> collectors, boolean enabled) {
this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled) {
@Override
protected List<RedshiftMetricTarget> collectTargets(Instant now) {
return redshiftService.availableMetricTargets();
}
@Override
protected List<MetricDatum> collectDatums(RedshiftMetricTarget target, long timestampSeconds) {
List<MetricDatum> datums = new ArrayList<>();
for (RedshiftMetricCollector collector : collectors) {
datums.addAll(collector.collect(target, timestampSeconds));
}
return datums;
}
@Override
protected String accountId(RedshiftMetricTarget target) {
return target.accountId();
}
@Override
protected String region(RedshiftMetricTarget target) {
return target.region();
}
@Override
protected String targetName(RedshiftMetricTarget target) {
return target.cluster().getClusterIdentifier();
}
};
}
static boolean isEnabled(EmulatorConfig config) {
return config.services().redshift().enabled() && config.services().redshift().cloudwatchMetricsEnabled()
&& config.services().cloudwatchmetrics().enabled();
}
void onStart(@Observes StartupEvent ignored) {
publisher.start();
}
void onStop(@Observes @Priority(1000) ShutdownEvent ignored) {
publisher.stop();
}
void publish(Instant now) {
publisher.publish(now);
}
}
@@ -52,6 +52,7 @@ public class RedshiftAuthProxy {
}
private final int handshakeTimeoutMillis;
private final int backendConnectTimeoutMillis;
private final int maxConnections;
private final Semaphore connectionPermits;
private volatile boolean running;
@@ -125,7 +126,13 @@ public class RedshiftAuthProxy {
this.roleConfiguration = new RoleConfiguration(iamRoleArns, null);
this.handshakeTimeoutMillis = handshakeTimeoutMillis;
this.backendConnectTimeoutMillis = backendConnectTimeoutMillis;
this.connectionPermits = new Semaphore(Math.max(1, maxConnections));
this.maxConnections = Math.max(1, maxConnections);
this.connectionPermits = new Semaphore(this.maxConnections);
}
/** Client connections currently open on this proxy: each holds one permit from accept to close. */
public int activeConnections() {
return maxConnections - connectionPermits.availablePermits();
}
public void start(int proxyPort) throws IOException {
@@ -16,6 +16,7 @@ import org.jboss.logging.Logger;
import java.io.IOException;
import java.util.List;
import java.util.OptionalInt;
import java.util.concurrent.ConcurrentHashMap;
/**
@@ -151,6 +152,12 @@ public class RedshiftProxyManager {
}
}
/** Open client connections of the proxy registered under {@code relayKey}; empty when none runs. */
public OptionalInt activeConnections(String relayKey) {
RedshiftAuthProxy proxy = proxies.get(relayKey);
return proxy == null ? OptionalInt.empty() : OptionalInt.of(proxy.activeConnections());
}
public synchronized void stopProxy(String relayKey) {
// Retry any listener a previous failed start/replace could not close. If it still
// cannot be closed this throws, and the entry stays for the next retry.
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.sqs;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.MinuteMetricsPublisher;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
import io.quarkus.runtime.ShutdownEvent;
@@ -10,110 +11,67 @@ import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Sends the AWS/SQS metrics of every active queue to CloudWatch once a minute, shaped as SQS sends
* Supplies the AWS/SQS metrics of every active queue to the minute publisher, shaped as SQS sends
* them: one sample of each depth gauge, and for each counter one sample per call in the minute plus
* the zero sample AWS adds to every minute. SentMessageSize has one sample per message and no zero
* sample. A tick runs just after each minute boundary and stamps its samples with the minute that
* ended, so a call lands in the minute it was made, as on AWS. Once an hour it drops the AWS/SQS
* datapoints older than the 15 days AWS keeps one-minute data, so the generated history stays bounded.
* sample.
*/
@ApplicationScoped
public class SqsMetricsPublisher {
static final String NAMESPACE = "AWS/SQS";
private static final Logger LOG = Logger.getLogger(SqsMetricsPublisher.class);
private static final long MINUTE_MILLIS = 60_000;
private static final long TICK_OFFSET_MILLIS = 1_000;
private static final Duration RETENTION = Duration.ofDays(15);
private static final String COUNT = "Count";
private final SqsService sqsService;
private final CloudWatchMetricsService metricsService;
private final boolean enabled;
private final ScheduledExecutorService scheduler;
private final MinuteMetricsPublisher<SqsService.QueueMetrics> publisher;
@Inject
public SqsMetricsPublisher(SqsService sqsService, CloudWatchMetricsService metricsService, EmulatorConfig config) {
this.sqsService = sqsService;
this.metricsService = metricsService;
this.enabled = config.services().sqs().enabled() && config.services().sqs().cloudwatchMetricsEnabled()
boolean enabled = config.services().sqs().enabled() && config.services().sqs().cloudwatchMetricsEnabled()
&& config.services().cloudwatchmetrics().enabled();
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "sqs-metrics-publisher");
t.setDaemon(true);
return t;
});
this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled) {
@Override
protected List<SqsService.QueueMetrics> collectTargets(Instant now) {
return sqsService.collectQueueMetrics(now);
}
@Override
protected List<MetricDatum> collectDatums(SqsService.QueueMetrics target, long timestampSeconds) {
return datums(target, timestampSeconds);
}
@Override
protected String accountId(SqsService.QueueMetrics target) {
return target.accountId();
}
@Override
protected String region(SqsService.QueueMetrics target) {
return target.region();
}
@Override
protected String targetName(SqsService.QueueMetrics target) {
return target.queueName();
}
};
}
void onStart(@Observes StartupEvent ignored) {
if (!enabled) {
return;
}
long untilNextMinute = MINUTE_MILLIS - System.currentTimeMillis() % MINUTE_MILLIS;
scheduler.scheduleAtFixedRate(() -> publish(Instant.now()), untilNextMinute + TICK_OFFSET_MILLIS,
MINUTE_MILLIS, TimeUnit.MILLISECONDS);
publisher.start();
}
/** Before EmulatorLifecycle's default-priority storage shutdown, letting a running tick finish its writes. */
void onStop(@Observes @Priority(1000) ShutdownEvent ignored) {
scheduler.shutdown();
try {
if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
LOG.warn("The AWS/SQS metrics publisher did not finish its tick within 5 seconds");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.warnv(e, "Interrupted while stopping the AWS/SQS metrics publisher");
}
publisher.stop();
}
/**
* Nothing may escape: the scheduler stops for good after a tick throws. One queue's failed write
* drops only that queue's samples for the minute.
*/
void publish(Instant now) {
List<SqsService.QueueMetrics> queues;
try {
queues = sqsService.collectQueueMetrics(now);
} catch (RuntimeException e) {
LOG.warnv(e, "Collecting AWS/SQS queue metrics failed; this minute's samples are dropped");
return;
}
long minute = endedMinute(now);
for (SqsService.QueueMetrics queue : queues) {
try {
metricsService.putMetricDataForAccount(queue.accountId(), NAMESPACE, datums(queue, minute),
queue.region());
} catch (RuntimeException e) {
LOG.warnv(e, "Publishing AWS/SQS metrics for queue {0} of account {1} in {2} failed; its samples "
+ "for this minute are dropped", queue.queueName(), queue.accountId(), queue.region());
}
}
if (minute % 3600 == 0) {
try {
metricsService.deleteMetricDataBefore(NAMESPACE, Instant.ofEpochSecond(minute).minus(RETENTION));
} catch (RuntimeException e) {
LOG.warnv(e, "Dropping AWS/SQS datapoints older than {0} failed; the next hour tries again", RETENTION);
}
}
}
/** The minute a tick's samples belong to. Reading it half a minute back absorbs any drift of the
* fixed-rate schedule away from the minute boundary. */
private static long endedMinute(Instant tick) {
return tick.minusSeconds(30).truncatedTo(ChronoUnit.MINUTES).getEpochSecond();
publisher.publish(now);
}
private static List<MetricDatum> datums(SqsService.QueueMetrics queue, long timestamp) {