-
Notifications
You must be signed in to change notification settings - Fork 979
/
InfluxMeterRegistry.java
316 lines (265 loc) · 11.9 KB
/
InfluxMeterRegistry.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/*
* Copyright 2017 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micrometer.influx;
import io.micrometer.common.util.StringUtils;
import io.micrometer.core.instrument.*;
import io.micrometer.core.instrument.step.StepMeterRegistry;
import io.micrometer.core.instrument.util.DoubleFormat;
import io.micrometer.core.instrument.util.MeterPartition;
import io.micrometer.core.instrument.util.NamedThreadFactory;
import io.micrometer.core.ipc.http.HttpSender;
import io.micrometer.core.ipc.http.HttpUrlConnectionSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining;
/**
* {@link MeterRegistry} for InfluxDB. Since Micrometer 1.7, this supports InfluxDB v2 and
* v1.
*
* @author Jon Schneider
* @author Johnny Lim
*/
public class InfluxMeterRegistry extends StepMeterRegistry {
private static final ThreadFactory DEFAULT_THREAD_FACTORY = new NamedThreadFactory("influx-metrics-publisher");
private final InfluxConfig config;
private final HttpSender httpClient;
private final Logger logger = LoggerFactory.getLogger(InfluxMeterRegistry.class);
private boolean databaseExists = false;
@SuppressWarnings("deprecation")
public InfluxMeterRegistry(InfluxConfig config, Clock clock) {
this(config, clock, DEFAULT_THREAD_FACTORY,
new HttpUrlConnectionSender(config.connectTimeout(), config.readTimeout()));
}
/**
* @param config Configuration options for the registry that are describable as
* properties.
* @param clock The clock to use for timings.
* @param threadFactory The thread factory to use to create the publishing thread.
* @deprecated Use {@link #builder(InfluxConfig)} instead.
*/
@Deprecated
public InfluxMeterRegistry(InfluxConfig config, Clock clock, ThreadFactory threadFactory) {
this(config, clock, threadFactory, new HttpUrlConnectionSender(config.connectTimeout(), config.readTimeout()));
}
private InfluxMeterRegistry(InfluxConfig config, Clock clock, ThreadFactory threadFactory, HttpSender httpClient) {
super(config, clock);
config().namingConvention(new InfluxNamingConvention());
this.config = config;
this.httpClient = httpClient;
start(threadFactory);
}
@Override
public void start(ThreadFactory threadFactory) {
super.start(threadFactory);
if (config.enabled()) {
logger.info("Using InfluxDB API version {} to write metrics", config.apiVersion());
}
}
public static Builder builder(InfluxConfig config) {
return new Builder(config);
}
private void createDatabaseIfNecessary() {
if (!config.autoCreateDb() || databaseExists || config.apiVersion() == InfluxApiVersion.V2)
return;
try {
String createDatabaseQuery = new CreateDatabaseQueryBuilder(config.db())
.setRetentionDuration(config.retentionDuration())
.setRetentionPolicyName(config.retentionPolicy())
.setRetentionReplicationFactor(config.retentionReplicationFactor())
.setRetentionShardDuration(config.retentionShardDuration())
.build();
HttpSender.Request.Builder requestBuilder = httpClient
.post(config.uri() + "/query?q=" + URLEncoder.encode(createDatabaseQuery, "UTF-8"))
.withBasicAuthentication(config.userName(), config.password());
config.apiVersion().addHeaderToken(config, requestBuilder);
requestBuilder.send().onSuccess(response -> {
logger.debug("influx database {} is ready to receive metrics", config.db());
databaseExists = true;
}).onError(response -> logger.error("unable to create database '{}': {}", config.db(), response.body()));
}
catch (Throwable e) {
logger.error("unable to create database '{}'", config.db(), e);
}
}
@Override
protected void publish() {
createDatabaseIfNecessary();
try {
String influxEndpoint = config.apiVersion().writeEndpoint(config);
for (List<Meter> batch : MeterPartition.partition(this, config.batchSize())) {
HttpSender.Request.Builder requestBuilder = httpClient.post(influxEndpoint)
.withBasicAuthentication(config.userName(), config.password());
config.apiVersion().addHeaderToken(config, requestBuilder);
// @formatter:off
requestBuilder
.withPlainText(batch.stream()
.flatMap(m -> m.match(
gauge -> writeGauge(gauge.getId(), gauge.value()),
counter -> writeCounter(counter.getId(), counter.count()),
this::writeTimer,
this::writeSummary,
this::writeLongTaskTimer,
gauge -> writeGauge(gauge.getId(), gauge.value(getBaseTimeUnit())),
counter -> writeCounter(counter.getId(), counter.count()),
this::writeFunctionTimer,
this::writeMeter))
.collect(joining("\n")))
.compressWhen(config::compressed)
.send()
.onSuccess(response -> {
logger.debug("successfully sent {} metrics to InfluxDB.", batch.size());
databaseExists = true;
})
.onError(response -> logger.error("failed to send metrics to influx: {}", response.body()));
// @formatter:on
}
}
catch (MalformedURLException e) {
throw new IllegalArgumentException(
"Malformed InfluxDB publishing endpoint, see '" + config.prefix() + ".uri'", e);
}
catch (Throwable e) {
logger.error("failed to send metrics to influx", e);
}
}
// VisibleForTesting
Stream<String> writeMeter(Meter m) {
List<Field> fields = new ArrayList<>();
for (Measurement measurement : m.measure()) {
double value = measurement.getValue();
if (!Double.isFinite(value)) {
continue;
}
String fieldKey = measurement.getStatistic()
.getTagValueRepresentation()
.replaceAll("(.)(\\p{Upper})", "$1_$2")
.toLowerCase();
fields.add(new Field(fieldKey, value));
}
if (fields.isEmpty()) {
return Stream.empty();
}
Meter.Id id = m.getId();
return Stream.of(influxLineProtocol(id, id.getType().name().toLowerCase(), fields.stream()));
}
private Stream<String> writeLongTaskTimer(LongTaskTimer timer) {
Stream<Field> fields = Stream.of(new Field("active_tasks", timer.activeTasks()),
new Field("duration", timer.duration(getBaseTimeUnit())));
return Stream.of(influxLineProtocol(timer.getId(), "long_task_timer", fields));
}
// VisibleForTesting
Stream<String> writeCounter(Meter.Id id, double count) {
if (Double.isFinite(count)) {
return Stream.of(influxLineProtocol(id, "counter", Stream.of(new Field("value", count))));
}
return Stream.empty();
}
// VisibleForTesting
Stream<String> writeGauge(Meter.Id id, Double value) {
if (Double.isFinite(value)) {
return Stream.of(influxLineProtocol(id, "gauge", Stream.of(new Field("value", value))));
}
return Stream.empty();
}
// VisibleForTesting
Stream<String> writeFunctionTimer(FunctionTimer timer) {
double sum = timer.totalTime(getBaseTimeUnit());
if (Double.isFinite(sum)) {
Stream.Builder<Field> builder = Stream.builder();
builder.add(new Field("sum", sum));
builder.add(new Field("count", timer.count()));
double mean = timer.mean(getBaseTimeUnit());
if (Double.isFinite(mean)) {
builder.add(new Field("mean", mean));
}
return Stream.of(influxLineProtocol(timer.getId(), "histogram", builder.build()));
}
return Stream.empty();
}
private Stream<String> writeTimer(Timer timer) {
final Stream<Field> fields = Stream.of(new Field("sum", timer.totalTime(getBaseTimeUnit())),
new Field("count", timer.count()), new Field("mean", timer.mean(getBaseTimeUnit())),
new Field("upper", timer.max(getBaseTimeUnit())));
return Stream.of(influxLineProtocol(timer.getId(), "histogram", fields));
}
private Stream<String> writeSummary(DistributionSummary summary) {
final Stream<Field> fields = Stream.of(new Field("sum", summary.totalAmount()),
new Field("count", summary.count()), new Field("mean", summary.mean()),
new Field("upper", summary.max()));
return Stream.of(influxLineProtocol(summary.getId(), "histogram", fields));
}
private String influxLineProtocol(Meter.Id id, String metricType, Stream<Field> fields) {
String tags = getConventionTags(id).stream()
.filter(t -> StringUtils.isNotBlank(t.getValue()))
.map(t -> "," + t.getKey() + "=" + t.getValue())
.collect(joining(""));
return getConventionName(id) + tags + ",metric_type=" + metricType + " "
+ fields.map(Field::toString).collect(joining(",")) + " " + clock.wallTime();
}
@Override
protected final TimeUnit getBaseTimeUnit() {
return TimeUnit.MILLISECONDS;
}
public static class Builder {
private final InfluxConfig config;
private Clock clock = Clock.SYSTEM;
private ThreadFactory threadFactory = DEFAULT_THREAD_FACTORY;
private HttpSender httpClient;
@SuppressWarnings("deprecation")
Builder(InfluxConfig config) {
this.config = config;
this.httpClient = new HttpUrlConnectionSender(config.connectTimeout(), config.readTimeout());
}
public Builder clock(Clock clock) {
this.clock = clock;
return this;
}
public Builder threadFactory(ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
return this;
}
public Builder httpClient(HttpSender httpClient) {
this.httpClient = httpClient;
return this;
}
public InfluxMeterRegistry build() {
return new InfluxMeterRegistry(config, clock, threadFactory, httpClient);
}
}
static class Field {
final String key;
final double value;
Field(String key, double value) {
// `time` cannot be a field key or tag key
if (key.equals("time")) {
throw new IllegalArgumentException("'time' is an invalid field key in InfluxDB");
}
this.key = key;
this.value = value;
}
@Override
public String toString() {
return key + "=" + DoubleFormat.decimalOrNan(value);
}
}
}