mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(sqs): publish AWS/SQS queue metrics to CloudWatch (#6280)
* feat(sqs): publish AWS/SQS queue metrics to CloudWatch Every active queue now reports the AWS/SQS metrics once a minute on the QueueName dimension: the depth gauges, ApproximateAgeOfOldestMessage, the send, receive, delete and empty-receive counters, SentMessageSize, and for FIFO queues the in-flight groups and deduplicated sends. The samples follow what SQS sends on AWS, so alarms, GetMetricData and GetMetricStatistics see queue metrics without PutMetricData. The CloudWatch metric store is now journaled under persistent mode, as the CloudWatch Logs event store is, since it takes a write per metric per active queue every minute. Closes #6275 * fix(sqs): stamp queue metrics with the minute that ended The publisher now ticks just after each minute boundary and stamps its samples with the minute that ended, so a call counts in the minute it was made instead of the minute of a startup-relative tick. A queue whose write fails no longer stops the others, and the log names it. A queue deleted and created again between the snapshot and the lookup is skipped instead of reporting the old queue's depth under the new one. * fix(sqs): bound AWS/SQS metric history and finish the tick on shutdown The publisher now drops AWS/SQS datapoints older than the 15 days AWS keeps one-minute data, once an hour, so the history it generates for an active queue stays bounded. On shutdown it stops before the storage flush and waits for a running tick, so the last minute is not written after the store closed. * test(sqs): keep the scheduled metrics tick out of the test run The acceptance test publishes its own ticks, but the scheduled one could still stamp the test queue's depth into a complete period newer than them, since a tick stamps the minute that just ended. floci.services.sqs. cloudwatch-metrics-enabled now turns the tick off, and the test configuration does, as it does for the S3 lifecycle sweep. It also lets a user opt out of the AWS/SQS metric volume. * test(sqs): build the metrics test's queue service with SqsServiceFactory
This commit is contained in:
1 parent
151cf30476
commit
ba353021e1
18 files changed
+893
-48
No files matched your search
@@ -1384,6 +1384,13 @@ public interface EmulatorConfig {
|
||||
@WithDefault("local-emulator-secret")
|
||||
String receiptHandleSecret();
|
||||
|
||||
/**
|
||||
* Publish the AWS/SQS CloudWatch metrics of every active queue once a minute, as SQS does.
|
||||
* Env: FLOCI_SERVICES_SQS_CLOUDWATCH_METRICS_ENABLED
|
||||
*/
|
||||
@WithDefault("true")
|
||||
boolean cloudwatchMetricsEnabled();
|
||||
|
||||
/**
|
||||
* Shape of the QueueUrl returned by CreateQueue, GetQueueUrl, ListQueues and
|
||||
* ListDeadLetterSourceQueues.
|
||||
|
||||
+21
-1
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.core.storage.WriteProfile;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
@@ -20,6 +21,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ApplicationScoped
|
||||
@@ -39,8 +41,10 @@ public class CloudWatchMetricsService {
|
||||
@Inject
|
||||
public CloudWatchMetricsService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
AlarmSnsNotifier alarmSnsNotifier) {
|
||||
// Services publish into this store every minute, SQS for every active queue, so under
|
||||
// persistent mode it is journaled rather than rewritten in full on every datum.
|
||||
this.metricStore = storageFactory.create("cloudwatchmetrics", "cwmetrics.json",
|
||||
new TypeReference<Map<String, MetricDatum>>() {});
|
||||
new TypeReference<Map<String, MetricDatum>>() {}, WriteProfile.APPEND_HEAVY);
|
||||
this.alarmStore = storageFactory.create("cloudwatchmetrics", "cwalarms.json",
|
||||
new TypeReference<Map<String, MetricAlarm>>() {});
|
||||
this.regionResolver = regionResolver;
|
||||
@@ -130,6 +134,22 @@ public class CloudWatchMetricsService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the {@code namespace} datapoints stamped before {@code cutoff}, in every account. A service
|
||||
* that writes its own metrics each minute, such as SQS, calls it so that history stays bounded.
|
||||
*/
|
||||
public void deleteMetricDataBefore(String namespace, Instant cutoff) {
|
||||
long cutoffSeconds = cutoff.getEpochSecond();
|
||||
Predicate<MetricDatum> expired = d -> namespace.equals(d.getNamespace()) && d.getTimestamp() < cutoffSeconds;
|
||||
if (metricStore instanceof AccountAwareStorageBackend<MetricDatum> aware) {
|
||||
aware.deleteAllAccountsMatching(expired);
|
||||
return;
|
||||
}
|
||||
for (String key : List.copyOf(metricStore.keys())) {
|
||||
metricStore.get(key).filter(expired).ifPresent(ignored -> metricStore.delete(key));
|
||||
}
|
||||
}
|
||||
|
||||
public record MetricIdentity(String namespace, String metricName, List<Dimension> dimensions) {}
|
||||
|
||||
public List<MetricIdentity> listMetrics(String namespace, String metricName,
|
||||
|
||||
@@ -4,8 +4,10 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.sqs.model.Message;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
@@ -24,6 +26,7 @@ class GuardedMessageQueue {
|
||||
private final StorageBackend<String, List<Message>> messageStore;
|
||||
private final String storageKey;
|
||||
private final String receiptHandleSecret;
|
||||
private final SqsQueueActivity activity = new SqsQueueActivity();
|
||||
private volatile boolean closed;
|
||||
|
||||
@FunctionalInterface
|
||||
@@ -300,6 +303,42 @@ class GuardedMessageQueue {
|
||||
}
|
||||
}
|
||||
|
||||
record Gauges(MessageCounts counts, long ageOfOldestMessageSeconds, long groupsWithInflightMessages) {
|
||||
boolean isEmpty() {
|
||||
return counts.visible() + counts.inFlight() + counts.delayed() == 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The queue contents AWS/SQS reports each minute. The age is that of the oldest message by the
|
||||
* time its retention started, so a message moved to a FIFO dead-letter queue or by a move task
|
||||
* counts from the move.
|
||||
*/
|
||||
Gauges gauges(Instant now) {
|
||||
try (Guard _ = hold()) {
|
||||
Instant oldest = null;
|
||||
Set<String> groupsInFlight = new HashSet<>();
|
||||
for (Message m : messages) {
|
||||
if (!m.isVisible() && m.getReceiptHandle() != null && m.getMessageGroupId() != null) {
|
||||
groupsInFlight.add(m.getMessageGroupId());
|
||||
}
|
||||
// ponytail: AWS also leaves out a standard-queue message received 3+ times in this queue;
|
||||
// that needs a per-queue receive count, since a redriven message keeps its total.
|
||||
Instant enqueued = m.getRetentionStartTimestamp() != null
|
||||
? m.getRetentionStartTimestamp() : m.getSentTimestamp();
|
||||
if (enqueued != null && (oldest == null || enqueued.isBefore(oldest))) {
|
||||
oldest = enqueued;
|
||||
}
|
||||
}
|
||||
long age = oldest == null ? 0 : Math.max(0, Duration.between(oldest, now).toSeconds());
|
||||
return new Gauges(messageCounts(), age, groupsInFlight.size());
|
||||
}
|
||||
}
|
||||
|
||||
SqsQueueActivity activity() {
|
||||
return activity;
|
||||
}
|
||||
|
||||
List<Message> peekAll() {
|
||||
try (Guard _ = hold()) {
|
||||
return new ArrayList<>(messages);
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
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.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
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.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
|
||||
* 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.
|
||||
*/
|
||||
@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;
|
||||
|
||||
@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()
|
||||
&& config.services().cloudwatchmetrics().enabled();
|
||||
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "sqs-metrics-publisher");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/** 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");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
|
||||
private static List<MetricDatum> datums(SqsService.QueueMetrics queue, long timestamp) {
|
||||
List<Dimension> dimensions = List.of(new Dimension("QueueName", queue.queueName()));
|
||||
GuardedMessageQueue.MessageCounts counts = queue.gauges().counts();
|
||||
SqsQueueActivity.Snapshot activity = queue.activity();
|
||||
List<MetricDatum> datums = new ArrayList<>(List.of(
|
||||
MetricDatum.of("ApproximateNumberOfMessagesVisible", COUNT, counts.visible(), dimensions, timestamp),
|
||||
MetricDatum.of("ApproximateNumberOfMessagesNotVisible", COUNT, counts.inFlight(), dimensions,
|
||||
timestamp),
|
||||
MetricDatum.of("ApproximateNumberOfMessagesDelayed", COUNT, counts.delayed(), dimensions, timestamp),
|
||||
MetricDatum.of("ApproximateAgeOfOldestMessage", "Seconds",
|
||||
queue.gauges().ageOfOldestMessageSeconds(), dimensions, timestamp),
|
||||
counter("NumberOfMessagesSent", activity.sent(), dimensions, timestamp),
|
||||
counter("NumberOfMessagesReceived", activity.received(), dimensions, timestamp),
|
||||
counter("NumberOfMessagesDeleted", activity.deleted(), dimensions, timestamp),
|
||||
counter("NumberOfEmptyReceives", activity.emptyReceives(), dimensions, timestamp)));
|
||||
if (activity.sentSize().count() > 0) {
|
||||
datums.add(samples("SentMessageSize", "Bytes", activity.sentSize(), dimensions, timestamp));
|
||||
}
|
||||
if (queue.fifo()) {
|
||||
datums.add(MetricDatum.of("ApproximateNumberOfGroupsWithInflightMessages", COUNT,
|
||||
queue.gauges().groupsWithInflightMessages(), dimensions, timestamp));
|
||||
datums.add(counter("NumberOfDeduplicatedSentMessages", activity.deduplicated(), dimensions, timestamp));
|
||||
}
|
||||
return datums;
|
||||
}
|
||||
|
||||
private static MetricDatum counter(String metricName, SqsQueueActivity.Samples calls,
|
||||
List<Dimension> dimensions, long timestamp) {
|
||||
return samples(metricName, COUNT, calls.add(0), dimensions, timestamp);
|
||||
}
|
||||
|
||||
private static MetricDatum samples(String metricName, String unit, SqsQueueActivity.Samples samples,
|
||||
List<Dimension> dimensions, long timestamp) {
|
||||
MetricDatum datum = MetricDatum.of(metricName, unit, samples.sum(), dimensions, timestamp);
|
||||
datum.setSampleCount(samples.count());
|
||||
datum.setSum(samples.sum());
|
||||
datum.setMinimum(samples.minimum());
|
||||
datum.setMaximum(samples.maximum());
|
||||
return datum;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package io.github.hectorvent.floci.services.sqs;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* What a queue's API calls did since the last AWS/SQS metrics tick, and when the queue was last
|
||||
* acted on, which decides whether CloudWatch still considers it active.
|
||||
*/
|
||||
final class SqsQueueActivity {
|
||||
|
||||
/** The samples of one metric within one tick. */
|
||||
record Samples(long count, double sum, double minimum, double maximum) {
|
||||
|
||||
static final Samples NONE = new Samples(0, 0, 0, 0);
|
||||
|
||||
Samples add(double value) {
|
||||
if (count == 0) {
|
||||
return new Samples(1, value, value, value);
|
||||
}
|
||||
return new Samples(count + 1, sum + value, Math.min(minimum, value), Math.max(maximum, value));
|
||||
}
|
||||
}
|
||||
|
||||
record Snapshot(Samples sent, Samples sentSize, Samples deduplicated, Samples received,
|
||||
Samples emptyReceives, Samples deleted, Instant lastActivity) {
|
||||
}
|
||||
|
||||
private Samples sent = Samples.NONE;
|
||||
private Samples sentSize = Samples.NONE;
|
||||
private Samples deduplicated = Samples.NONE;
|
||||
private Samples received = Samples.NONE;
|
||||
private Samples emptyReceives = Samples.NONE;
|
||||
private Samples deleted = Samples.NONE;
|
||||
private Instant lastActivity;
|
||||
|
||||
synchronized void accessed() {
|
||||
lastActivity = Instant.now();
|
||||
}
|
||||
|
||||
/** A FIFO send that was deduplicated still counts as sent, as on AWS. */
|
||||
synchronized void sent(int size, boolean wasDeduplicated) {
|
||||
sent = sent.add(1);
|
||||
sentSize = sentSize.add(size);
|
||||
deduplicated = deduplicated.add(wasDeduplicated ? 1 : 0);
|
||||
lastActivity = Instant.now();
|
||||
}
|
||||
|
||||
synchronized void received(int messages) {
|
||||
if (messages == 0) {
|
||||
emptyReceives = emptyReceives.add(1);
|
||||
} else {
|
||||
received = received.add(messages);
|
||||
}
|
||||
lastActivity = Instant.now();
|
||||
}
|
||||
|
||||
synchronized void deleted() {
|
||||
deleted = deleted.add(1);
|
||||
lastActivity = Instant.now();
|
||||
}
|
||||
|
||||
/** Hands over the samples gathered since the previous call and starts the next tick empty. */
|
||||
synchronized Snapshot drain() {
|
||||
Snapshot snapshot = new Snapshot(sent, sentSize, deduplicated, received, emptyReceives, deleted, lastActivity);
|
||||
sent = Samples.NONE;
|
||||
sentSize = Samples.NONE;
|
||||
deduplicated = Samples.NONE;
|
||||
received = Samples.NONE;
|
||||
emptyReceives = Samples.NONE;
|
||||
deleted = Samples.NONE;
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,8 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
private static final int DEFAULT_MESSAGE_RETENTION_PERIOD_SECONDS = 345600;
|
||||
private static final int MIN_MESSAGE_RETENTION_PERIOD_SECONDS = 60;
|
||||
private static final int MAX_MESSAGE_RETENTION_PERIOD_SECONDS = 1209600;
|
||||
/** CloudWatch keeps reporting a queue for six hours after its last action, or while it holds a message. */
|
||||
private static final Duration METRICS_ACTIVE_WINDOW = Duration.ofHours(6);
|
||||
|
||||
private final StorageBackend<String, Queue> queueStore;
|
||||
private final StorageBackend<String, List<Message>> messageStore;
|
||||
@@ -773,6 +775,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
}
|
||||
getOrCreateQueue(storageKey).activity().accessed();
|
||||
return withCurrentQueueUrl(existing, region);
|
||||
}
|
||||
|
||||
@@ -799,8 +802,10 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
|
||||
queueStore.put(storageKey, queue);
|
||||
messagesByQueue.put(storageKey,
|
||||
new GuardedMessageQueue(new ArrayList<>(), messageStore, storageKey, receiptHandleSecret));
|
||||
GuardedMessageQueue messages = new GuardedMessageQueue(new ArrayList<>(), messageStore, storageKey,
|
||||
receiptHandleSecret);
|
||||
messages.activity().accessed();
|
||||
messagesByQueue.put(storageKey, messages);
|
||||
LOG.infov("Created {0} queue: {1} in region {2}", queue.isFifo() ? "FIFO" : "standard", queueName, region);
|
||||
return queue;
|
||||
}
|
||||
@@ -904,7 +909,10 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
attrs.put("CreatedTimestamp", String.valueOf(queue.getCreatedTimestamp().getEpochSecond()));
|
||||
attrs.put("LastModifiedTimestamp", String.valueOf(queue.getLastModifiedTimestamp().getEpochSecond()));
|
||||
|
||||
GuardedMessageQueue.MessageCounts counts = unexpiredMessages(storageKey, queue).messageCounts();
|
||||
GuardedMessageQueue messages = unexpiredMessages(storageKey, queue);
|
||||
// AWS: a GetQueueAttributes call activates the queue, so CloudWatch reports it again.
|
||||
messages.activity().accessed();
|
||||
GuardedMessageQueue.MessageCounts counts = messages.messageCounts();
|
||||
attrs.put("ApproximateNumberOfMessages", String.valueOf(counts.visible()));
|
||||
attrs.put("ApproximateNumberOfMessagesNotVisible", String.valueOf(counts.inFlight()));
|
||||
attrs.put("ApproximateNumberOfMessagesDelayed", String.valueOf(counts.delayed()));
|
||||
@@ -1119,6 +1127,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
response.getMessageAttributes().putAll(messageAttributes);
|
||||
response.updateMd5OfMessageAttributes();
|
||||
}
|
||||
getOrCreateQueue(storageKey).activity().sent(totalSize, true);
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -1138,7 +1147,9 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
message.updateMd5OfMessageAttributes();
|
||||
}
|
||||
|
||||
getOrCreateQueue(storageKey).addMessage(message);
|
||||
GuardedMessageQueue messages = getOrCreateQueue(storageKey);
|
||||
messages.addMessage(message);
|
||||
messages.activity().sent(totalSize, false);
|
||||
deduplicationIdentityCache.computeIfAbsent(storageKey, k -> new ConcurrentHashMap<>())
|
||||
.putIfAbsent(dedupCacheKey,
|
||||
new DeduplicationIdentity(message.getMessageId(), message.getSequenceNumber()));
|
||||
@@ -1166,7 +1177,9 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
message.updateMd5OfMessageAttributes();
|
||||
}
|
||||
|
||||
getOrCreateQueue(storageKey).addMessage(message);
|
||||
GuardedMessageQueue messages = getOrCreateQueue(storageKey);
|
||||
messages.addMessage(message);
|
||||
messages.activity().sent(totalSize, false);
|
||||
notifyReceivers(storageKey);
|
||||
LOG.debugv("Sent message {0} to queue {1}", message.getMessageId(), queueUrl);
|
||||
LOG.tracev("Sent message {0} to queue {1} body={2} attributes={3}",
|
||||
@@ -1405,11 +1418,11 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
m.getMessageId(), queueUrl, m.getBody(), m.getMessageAttributes());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
return recordReceive(polledQueue, result);
|
||||
}
|
||||
long elapsed = System.currentTimeMillis() - start;
|
||||
if (elapsed >= maxWait) {
|
||||
return result;
|
||||
return recordReceive(polledQueue, result);
|
||||
}
|
||||
try {
|
||||
synchronized (lock) {
|
||||
@@ -1417,11 +1430,17 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return result;
|
||||
return recordReceive(polledQueue, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** AWS takes one sample per ReceiveMessage call, however long it polled. */
|
||||
private static List<Message> recordReceive(GuardedMessageQueue polledQueue, List<Message> received) {
|
||||
polledQueue.activity().received(received.size());
|
||||
return received;
|
||||
}
|
||||
|
||||
private int resolveWaitTimeSeconds(Queue queue, Integer requestedWaitTimeSeconds) {
|
||||
if (requestedWaitTimeSeconds != null) {
|
||||
return requestedWaitTimeSeconds;
|
||||
@@ -1533,9 +1552,11 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
"The specified queue does not exist.", 400));
|
||||
ReceiptHandle handle = checkReceiptHandle(storageKey, receiptHandle, inBatch);
|
||||
|
||||
GuardedMessageQueue.Removal removal =
|
||||
getOrCreateQueue(storageKey).removeByReceiptHandle(handle, queue.isFifo());
|
||||
GuardedMessageQueue messages = getOrCreateQueue(storageKey);
|
||||
GuardedMessageQueue.Removal removal = messages.removeByReceiptHandle(handle, queue.isFifo());
|
||||
rejectUnusableHandle(removal.result(), receiptHandle, inBatch);
|
||||
// AWS counts every delete with a valid handle, including a repeat for a message already gone.
|
||||
messages.activity().deleted();
|
||||
// AWS reports success for a message that is already gone.
|
||||
if (removal.result() == GuardedMessageQueue.HandleResult.MESSAGE_GONE) {
|
||||
LOG.debugv("No message for receipt handle {0}", receiptHandle);
|
||||
@@ -1561,8 +1582,9 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
"The specified queue does not exist.", 400));
|
||||
ReceiptHandle handle = checkReceiptHandle(storageKey, receiptHandle, inBatch);
|
||||
|
||||
GuardedMessageQueue.HandleResult result =
|
||||
getOrCreateQueue(storageKey).changeVisibility(handle, visibilityTimeout, queue.isFifo());
|
||||
GuardedMessageQueue messages = getOrCreateQueue(storageKey);
|
||||
messages.activity().accessed();
|
||||
GuardedMessageQueue.HandleResult result = messages.changeVisibility(handle, visibilityTimeout, queue.isFifo());
|
||||
rejectUnusableHandle(result, receiptHandle, inBatch);
|
||||
if (result == GuardedMessageQueue.HandleResult.MESSAGE_GONE) {
|
||||
throw invalidReceiptHandle(receiptHandle,
|
||||
@@ -1609,7 +1631,9 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
public void purgeQueue(String queueUrl, String region) {
|
||||
String storageKey = regionKey(region, queueUrl);
|
||||
ensureQueueExists(storageKey);
|
||||
getOrCreateQueue(storageKey).purge();
|
||||
GuardedMessageQueue messages = getOrCreateQueue(storageKey);
|
||||
messages.purge();
|
||||
messages.activity().accessed();
|
||||
if (clearFifoDeduplicationCacheOnPurge) {
|
||||
deduplicationCache.remove(storageKey);
|
||||
deduplicationIdentityCache.remove(storageKey);
|
||||
@@ -1646,6 +1670,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
queue.setLastModifiedTimestamp(Instant.now());
|
||||
queueStore.put(storageKey, queue);
|
||||
getOrCreateQueue(storageKey).activity().accessed();
|
||||
LOG.infov("Updated attributes for queue: {0}", queueUrl);
|
||||
}
|
||||
|
||||
@@ -2208,6 +2233,40 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/** One active queue's AWS/SQS metrics for one publication. */
|
||||
record QueueMetrics(String accountId, String region, String queueName, boolean fifo,
|
||||
GuardedMessageQueue.Gauges gauges, SqsQueueActivity.Snapshot activity) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The AWS/SQS metrics of every queue CloudWatch considers active: one that holds a message or
|
||||
* was acted on in the last six hours. Each queue's activity since the previous call is handed
|
||||
* over, so every call starts the next sample window.
|
||||
*/
|
||||
List<QueueMetrics> collectQueueMetrics(Instant now) {
|
||||
Instant activeSince = now.minus(METRICS_ACTIVE_WINDOW);
|
||||
List<QueueMetrics> metrics = new ArrayList<>();
|
||||
messagesByQueue.forEach((storageKey, messages) -> {
|
||||
int separator = storageKey.indexOf("::");
|
||||
String queueUrl = baseUrl + storageKey.substring(separator + 2);
|
||||
Queue queue = getQueueByUrl(storageKey, queueUrl).orElse(null);
|
||||
// A queue deleted and created again meanwhile has a new message queue; this one is gone.
|
||||
if (queue == null || messagesByQueue.get(storageKey) != messages) {
|
||||
return;
|
||||
}
|
||||
messages.removeExpired(retentionCutoff(queue));
|
||||
GuardedMessageQueue.Gauges gauges = messages.gauges(now);
|
||||
SqsQueueActivity.Snapshot activity = messages.activity().drain();
|
||||
Instant lastActivity = activity.lastActivity();
|
||||
if (gauges.isEmpty() && (lastActivity == null || lastActivity.isBefore(activeSince))) {
|
||||
return;
|
||||
}
|
||||
metrics.add(new QueueMetrics(accountFromQueueUrl(queueUrl), storageKey.substring(0, separator),
|
||||
queue.getQueueName(), queue.isFifo(), gauges, activity));
|
||||
});
|
||||
return metrics;
|
||||
}
|
||||
|
||||
private void removeExpiredMessages(String storageKey) {
|
||||
GuardedMessageQueue messages = messagesByQueue.get(storageKey);
|
||||
if (messages == null) {
|
||||
|
||||
Reference in new issue
Block a user