|
| 1 | +/* |
| 2 | + * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"). |
| 5 | + * You may not use this file except in compliance with the License. |
| 6 | + * A copy of the License is located at |
| 7 | + * |
| 8 | + * http://aws.amazon.com/apache2.0 |
| 9 | + * |
| 10 | + * or in the "license" file accompanying this file. This file is distributed |
| 11 | + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
| 12 | + * express or implied. See the License for the specific language governing |
| 13 | + * permissions and limitations under the License. |
| 14 | + */ |
| 15 | + |
1 | 16 | package software.amazon.awssdk.metrics.publishers.cloudwatch;
|
2 | 17 |
|
| 18 | +import java.time.Duration; |
| 19 | +import java.util.ArrayList; |
| 20 | +import java.util.List; |
| 21 | +import java.util.concurrent.BlockingQueue; |
3 | 22 | import java.util.concurrent.CompletableFuture;
|
| 23 | +import java.util.concurrent.ExecutorService; |
| 24 | +import java.util.concurrent.Executors; |
| 25 | +import java.util.concurrent.LinkedBlockingQueue; |
| 26 | +import java.util.concurrent.ScheduledExecutorService; |
| 27 | +import java.util.concurrent.TimeUnit; |
| 28 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 29 | +import software.amazon.awssdk.annotations.SdkPublicApi; |
4 | 30 | import software.amazon.awssdk.metrics.publisher.MetricPublisher;
|
| 31 | +import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.Consumer; |
| 32 | +import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.Producer; |
5 | 33 | import software.amazon.awssdk.metrics.registry.MetricRegistry;
|
| 34 | +import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient; |
| 35 | +import software.amazon.awssdk.services.cloudwatch.model.MetricDatum; |
| 36 | +import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataResponse; |
| 37 | +import software.amazon.awssdk.utils.Logger; |
| 38 | +import software.amazon.awssdk.utils.ThreadFactoryBuilder; |
| 39 | +import software.amazon.awssdk.utils.Validate; |
| 40 | + |
| 41 | +/** |
| 42 | + * An implementation of the {@link MetricPublisher} that uploads metrics to Amazon CloudWatch. |
| 43 | + */ |
| 44 | +@SdkPublicApi |
| 45 | +public final class CloudWatchPublisher implements MetricPublisher { |
| 46 | + |
| 47 | + private static final Logger log = Logger.loggerFor(CloudWatchPublisher.class); |
6 | 48 |
|
7 |
| -public class CloudWatchPublisher implements MetricPublisher { |
| 49 | + /** |
| 50 | + * Limit max number of service calls to CloudWatch in a single {@link #publish()} method call |
| 51 | + */ |
| 52 | + private static final int MAX_SERVICE_CALLS_PER_PUBLISH = 10; |
| 53 | + |
| 54 | + private final CloudWatchAsyncClient client; |
| 55 | + private final Duration publishFrequency; |
| 56 | + private String namespace; |
| 57 | + private final int metricQueueSize; |
| 58 | + private final BlockingQueue<MetricDatum> queue; |
| 59 | + private final Producer producer; |
| 60 | + private final ExecutorService producerExecutorService; |
| 61 | + private final Consumer consumer; |
| 62 | + private final ScheduledExecutorService consumerExecutorService; |
| 63 | + private final AtomicBoolean publishStarted = new AtomicBoolean(false); |
| 64 | + |
| 65 | + private CloudWatchPublisher(Builder builder) { |
| 66 | + this.client = resolveClient(builder.client); |
| 67 | + this.publishFrequency = Validate.notNull(builder.publishFrequency, "Publish frequency cannot be null."); |
| 68 | + this.namespace = Validate.notEmpty(builder.namespace, "Namespace cannot be null or empty."); |
| 69 | + this.metricQueueSize = Validate.isPositive(builder.metricQueueSize, "Metric queue size should be positive."); |
| 70 | + this.queue = new LinkedBlockingQueue<>(this.metricQueueSize); |
| 71 | + this.producer = Producer.builder().queue(queue).build(); |
| 72 | + this.producerExecutorService = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder() |
| 73 | + .threadNamePrefix("sdk-cloudwatch-producer") |
| 74 | + .build()); |
| 75 | + this.consumer= Consumer.builder() |
| 76 | + .cloudWatchClient(client) |
| 77 | + .queue(queue) |
| 78 | + .namespace(namespace) |
| 79 | + .build(); |
| 80 | + this.consumerExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder() |
| 81 | + .threadNamePrefix("sdk-cloudwatch-consumer") |
| 82 | + .build()); |
| 83 | + } |
8 | 84 |
|
| 85 | + /** |
| 86 | + * CloudWatch publisher converts the given metrics into {@link MetricDatum} instances and add them |
| 87 | + * to a queue for publishing. |
| 88 | + * |
| 89 | + * @param metricsRegistry registry containing the collected metrics |
| 90 | + */ |
9 | 91 | @Override
|
10 | 92 | public void registerMetrics(MetricRegistry metricsRegistry) {
|
| 93 | + try { |
| 94 | + if (publishStarted.compareAndSet(false, true)) { |
| 95 | + consumerExecutorService.scheduleAtFixedRate(this::publish, 0L,publishFrequency.toMillis(), TimeUnit.MILLISECONDS); |
| 96 | + } |
11 | 97 |
|
| 98 | + producerExecutorService.execute(() -> producer.addMetrics(metricsRegistry)); |
| 99 | + } catch (Throwable throwable) { |
| 100 | + log.debug(() -> "An error occurred when registering metrics in the publisher", throwable); |
| 101 | + } |
12 | 102 | }
|
13 | 103 |
|
14 | 104 | @Override
|
15 | 105 | public CompletableFuture<Void> publish() {
|
16 |
| - return null; |
| 106 | + List<CompletableFuture<PutMetricDataResponse>> futures = new ArrayList<>(); |
| 107 | + int count = 0; |
| 108 | + |
| 109 | + try { |
| 110 | + while (queue.peek() != null && ++count <= MAX_SERVICE_CALLS_PER_PUBLISH) { |
| 111 | + futures.add(consumer.call()); |
| 112 | + } |
| 113 | + } catch (Throwable throwable) { |
| 114 | + log.debug(() -> "An error occurred when uploading metrics to CloudWatch.", throwable); |
| 115 | + } |
| 116 | + |
| 117 | + return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); |
17 | 118 | }
|
18 | 119 |
|
19 | 120 | @Override
|
20 | 121 | public void close() throws Exception {
|
| 122 | + if (producerExecutorService != null) { |
| 123 | + producerExecutorService.shutdown(); |
| 124 | + } |
| 125 | + |
| 126 | + if (client != null) { |
| 127 | + client.close(); |
| 128 | + } |
| 129 | + |
| 130 | + if (consumerExecutorService != null) { |
| 131 | + consumerExecutorService.shutdown(); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + private CloudWatchAsyncClient resolveClient(CloudWatchAsyncClient builderClient) { |
| 136 | + return builderClient != null ? builderClient : CloudWatchAsyncClient.create(); |
| 137 | + } |
| 138 | + |
| 139 | + /** |
| 140 | + * @return A {@link Builder} object to build {@link CloudWatchPublisher}. |
| 141 | + */ |
| 142 | + public static Builder builder() { |
| 143 | + return new Builder(); |
| 144 | + } |
| 145 | + |
| 146 | + /** |
| 147 | + * @return A new instance of {@link CloudWatchPublisher} with all defaults. |
| 148 | + */ |
| 149 | + public static CloudWatchPublisher create() { |
| 150 | + return builder().build(); |
| 151 | + } |
| 152 | + |
| 153 | + /** |
| 154 | + * Builder class to construct {@link CloudWatchPublisher} instances. |
| 155 | + */ |
| 156 | + public static final class Builder { |
| 157 | + private static final String DEFAULT_NAMESPACE = "AwsSdk/JavaSdk2x"; |
| 158 | + private static final int QUEUE_SIZE = 100; |
| 159 | + private static final Duration DEFAULT_PUBLISH_FREQUENCY = Duration.ofMinutes(1); |
| 160 | + |
| 161 | + private CloudWatchAsyncClient client; |
| 162 | + private Duration publishFrequency = DEFAULT_PUBLISH_FREQUENCY; |
| 163 | + private String namespace = DEFAULT_NAMESPACE; |
| 164 | + private int metricQueueSize = QUEUE_SIZE; |
| 165 | + |
| 166 | + /** |
| 167 | + * @param client async client to use for uploads metrics to Amazon CloudWatch |
| 168 | + * @return This object for method chaining |
| 169 | + */ |
| 170 | + Builder cloudWatchClient(CloudWatchAsyncClient client) { |
| 171 | + this.client = client; |
| 172 | + return this; |
| 173 | + } |
| 174 | + |
| 175 | + /** |
| 176 | + * @param publishFrequency the timeout between consecutive {@link CloudWatchPublisher#publish()} calls |
| 177 | + * @return This object for method chaining |
| 178 | + */ |
| 179 | + Builder publishFrequency(Duration publishFrequency) { |
| 180 | + this.publishFrequency = publishFrequency; |
| 181 | + return this; |
| 182 | + } |
| 183 | + |
| 184 | + /** |
| 185 | + * @param metricQueueSize max number of metrics to store in queue. If the queue is full, new metrics are dropped |
| 186 | + * @return This object for method chaining |
| 187 | + */ |
| 188 | + Builder metricQueueSize(int metricQueueSize) { |
| 189 | + this.metricQueueSize = metricQueueSize; |
| 190 | + return this; |
| 191 | + } |
| 192 | + |
| 193 | + /** |
| 194 | + * @param namespace The CloudWatch namespace for the metric data |
| 195 | + * @return This object for method chaining |
| 196 | + */ |
| 197 | + Builder namespace(String namespace) { |
| 198 | + this.namespace = namespace; |
| 199 | + return this; |
| 200 | + } |
21 | 201 |
|
| 202 | + /** |
| 203 | + * @return an instance of {@link CloudWatchPublisher} |
| 204 | + */ |
| 205 | + CloudWatchPublisher build() { |
| 206 | + return new CloudWatchPublisher(this); |
| 207 | + } |
22 | 208 | }
|
23 | 209 | }
|
0 commit comments