/
ExecutorServiceMetrics.java
370 lines (335 loc) · 17.9 KB
/
ExecutorServiceMetrics.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/**
* Copyright 2017 VMware, Inc.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.core.instrument.binder.jvm;
import io.micrometer.core.instrument.*;
import io.micrometer.core.instrument.binder.BaseUnits;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.instrument.internal.TimedExecutor;
import io.micrometer.core.instrument.internal.TimedExecutorService;
import io.micrometer.core.instrument.internal.TimedScheduledExecutorService;
import io.micrometer.core.instrument.util.StringUtils;
import io.micrometer.core.lang.NonNullApi;
import io.micrometer.core.lang.NonNullFields;
import io.micrometer.core.lang.Nullable;
import io.micrometer.core.util.internal.logging.InternalLogger;
import io.micrometer.core.util.internal.logging.InternalLoggerFactory;
import java.lang.reflect.Field;
import java.util.concurrent.*;
import static java.util.Arrays.asList;
/**
* Monitors the status of executor service pools. Does not record timings on operations executed in the {@link ExecutorService},
* as this requires the instance to be wrapped. Timings are provided separately by wrapping the executor service
* with {@link TimedExecutorService}.
* <p>
* Supports {@link ThreadPoolExecutor} and {@link ForkJoinPool} types of {@link ExecutorService}. Some libraries may provide
* a wrapper type for {@link ExecutorService}, like {@link TimedExecutorService}. Make sure to pass the underlying,
* unwrapped ExecutorService to this MeterBinder, if it is wrapped in another type.
*
* @author Jon Schneider
* @author Clint Checketts
* @author Johnny Lim
*/
@NonNullApi
@NonNullFields
public class ExecutorServiceMetrics implements MeterBinder {
private static final InternalLogger log = InternalLoggerFactory.getInstance(ExecutorServiceMetrics.class);
static final String DEFAULT_EXECUTOR_METRIC_PREFIX = "";
@Nullable
private final ExecutorService executorService;
private final Iterable<Tag> tags;
private final String metricPrefix;
public ExecutorServiceMetrics(@Nullable ExecutorService executorService, String executorServiceName, Iterable<Tag> tags) {
this(executorService, executorServiceName, DEFAULT_EXECUTOR_METRIC_PREFIX, tags);
}
/**
* Create an {@code ExecutorServiceMetrics} instance.
*
* @param executorService executor service
* @param executorServiceName executor service name which will be used as {@literal name} tag
* @param metricPrefix metrics prefix which will be used to prefix metric name
* @param tags additional tags
* @since 1.5.0
*/
public ExecutorServiceMetrics(@Nullable ExecutorService executorService, String executorServiceName,
String metricPrefix, Iterable<Tag> tags) {
this.executorService = executorService;
this.tags = Tags.concat(tags, "name", executorServiceName);
this.metricPrefix = sanitizePrefix(metricPrefix);
}
/**
* Record metrics on the use of an {@link Executor}.
*
* @param registry The registry to bind metrics to.
* @param executor The executor to instrument.
* @param executorName Will be used to tag metrics with "name".
* @param tags Tags to apply to all recorded metrics.
* @return The instrumented executor, proxied.
*/
public static Executor monitor(MeterRegistry registry, Executor executor, String executorName, Iterable<Tag> tags) {
return monitor(registry, executor, executorName, DEFAULT_EXECUTOR_METRIC_PREFIX, tags);
}
/**
* Record metrics on the use of an {@link Executor}.
*
* @param registry The registry to bind metrics to.
* @param executor The executor to instrument.
* @param executorName Will be used to tag metrics with "name".
* @param metricPrefix The prefix to use with meter names. This differentiates executor metrics that may have different tag sets.
* @param tags Tags to apply to all recorded metrics.
* @return The instrumented executor, proxied.
* @since 1.5.0
*/
public static Executor monitor(MeterRegistry registry, Executor executor, String executorName,
String metricPrefix, Iterable<Tag> tags) {
if (executor instanceof ExecutorService) {
return monitor(registry, (ExecutorService) executor, executorName, metricPrefix, tags);
}
return new TimedExecutor(registry, executor, executorName, sanitizePrefix(metricPrefix), tags);
}
/**
* Record metrics on the use of an {@link Executor}.
*
* @param registry The registry to bind metrics to.
* @param executor The executor to instrument.
* @param executorName Will be used to tag metrics with "name".
* @param tags Tags to apply to all recorded metrics.
* @return The instrumented executor, proxied.
*/
public static Executor monitor(MeterRegistry registry, Executor executor, String executorName, Tag... tags) {
return monitor(registry, executor, executorName, DEFAULT_EXECUTOR_METRIC_PREFIX, tags);
}
/**
* Record metrics on the use of an {@link Executor}.
*
* @param registry The registry to bind metrics to.
* @param executor The executor to instrument.
* @param executorName Will be used to tag metrics with "name".
* @param metricPrefix The prefix to use with meter names. This differentiates executor metrics that may have different tag sets.
* @param tags Tags to apply to all recorded metrics.
* @return The instrumented executor, proxied.
* @since 1.5.0
*/
public static Executor monitor(MeterRegistry registry, Executor executor, String executorName,
String metricPrefix, Tag... tags) {
return monitor(registry, executor, executorName, metricPrefix, asList(tags));
}
/**
* Record metrics on the use of an {@link ExecutorService}.
*
* @param registry The registry to bind metrics to.
* @param executor The executor to instrument.
* @param executorServiceName Will be used to tag metrics with "name".
* @param tags Tags to apply to all recorded metrics.
* @return The instrumented executor, proxied.
*/
public static ExecutorService monitor(MeterRegistry registry, ExecutorService executor, String executorServiceName, Iterable<Tag> tags) {
return monitor(registry, executor, executorServiceName, DEFAULT_EXECUTOR_METRIC_PREFIX, tags);
}
/**
* Record metrics on the use of an {@link ExecutorService}.
*
* @param registry The registry to bind metrics to.
* @param executor The executor to instrument.
* @param executorServiceName Will be used to tag metrics with "name".
* @param metricPrefix The prefix to use with meter names. This differentiates executor metrics that may have different tag sets.
* @param tags Tags to apply to all recorded metrics.
* @return The instrumented executor, proxied.
* @since 1.5.0
*/
public static ExecutorService monitor(MeterRegistry registry, ExecutorService executor, String executorServiceName,
String metricPrefix, Iterable<Tag> tags) {
if (executor instanceof ScheduledExecutorService) {
return monitor(registry, (ScheduledExecutorService) executor, executorServiceName, metricPrefix, tags);
}
new ExecutorServiceMetrics(executor, executorServiceName, metricPrefix, tags).bindTo(registry);
return new TimedExecutorService(registry, executor, executorServiceName, sanitizePrefix(metricPrefix), tags);
}
/**
* Record metrics on the use of an {@link ExecutorService}.
*
* @param registry The registry to bind metrics to.
* @param executor The executor to instrument.
* @param executorServiceName Will be used to tag metrics with "name".
* @param tags Tags to apply to all recorded metrics.
* @return The instrumented executor, proxied.
*/
public static ExecutorService monitor(MeterRegistry registry, ExecutorService executor, String executorServiceName, Tag... tags) {
return monitor(registry, executor, executorServiceName, DEFAULT_EXECUTOR_METRIC_PREFIX, tags);
}
/**
* Record metrics on the use of an {@link ExecutorService}.
*
* @param registry The registry to bind metrics to.
* @param executor The executor to instrument.
* @param executorServiceName Will be used to tag metrics with "name".
* @param metricPrefix The prefix to use with meter names. This differentiates executor metrics that may have different tag sets.
* @param tags Tags to apply to all recorded metrics.
* @since 1.5.0
* @return The instrumented executor, proxied.
*/
public static ExecutorService monitor(MeterRegistry registry, ExecutorService executor, String executorServiceName,
String metricPrefix, Tag... tags) {
return monitor(registry, executor, executorServiceName, metricPrefix, asList(tags));
}
/**
* Record metrics on the use of a {@link ScheduledExecutorService}.
*
* @param registry The registry to bind metrics to.
* @param executor The scheduled executor to instrument.
* @param executorServiceName Will be used to tag metrics with "name".
* @param tags Tags to apply to all recorded metrics.
* @return The instrumented scheduled executor, proxied.
* @since 1.3.0
*/
public static ScheduledExecutorService monitor(MeterRegistry registry, ScheduledExecutorService executor, String executorServiceName, Iterable<Tag> tags) {
return monitor(registry, executor, executorServiceName, DEFAULT_EXECUTOR_METRIC_PREFIX, tags);
}
/**
* Record metrics on the use of a {@link ScheduledExecutorService}.
*
* @param registry The registry to bind metrics to.
* @param executor The scheduled executor to instrument.
* @param executorServiceName Will be used to tag metrics with "name".
* @param metricPrefix The prefix to use with meter names. This differentiates executor metrics that may have different tag sets.
* @param tags Tags to apply to all recorded metrics.
* @return The instrumented scheduled executor, proxied.
* @since 1.5.0
*/
public static ScheduledExecutorService monitor(MeterRegistry registry, ScheduledExecutorService executor, String executorServiceName,
String metricPrefix, Iterable<Tag> tags) {
new ExecutorServiceMetrics(executor, executorServiceName, metricPrefix, tags).bindTo(registry);
return new TimedScheduledExecutorService(registry, executor, executorServiceName, sanitizePrefix(metricPrefix), tags);
}
/**
* Record metrics on the use of a {@link ScheduledExecutorService}.
*
* @param registry The registry to bind metrics to.
* @param executor The scheduled executor to instrument.
* @param executorServiceName Will be used to tag metrics with "name".
* @param tags Tags to apply to all recorded metrics.
* @return The instrumented scheduled executor, proxied.
* @since 1.3.0
*/
public static ScheduledExecutorService monitor(MeterRegistry registry, ScheduledExecutorService executor, String executorServiceName, Tag... tags) {
return monitor(registry, executor, executorServiceName, DEFAULT_EXECUTOR_METRIC_PREFIX, tags);
}
/**
* Record metrics on the use of a {@link ScheduledExecutorService}.
*
* @param registry The registry to bind metrics to.
* @param executor The scheduled executor to instrument.
* @param executorServiceName Will be used to tag metrics with "name".
* @param metricPrefix The prefix to use with meter names. This differentiates executor metrics that may have different tag sets.
* @param tags Tags to apply to all recorded metrics.
* @return The instrumented scheduled executor, proxied.
* @since 1.5.0
*/
public static ScheduledExecutorService monitor(MeterRegistry registry, ScheduledExecutorService executor, String executorServiceName,
String metricPrefix, Tag... tags) {
return monitor(registry, executor, executorServiceName, metricPrefix, asList(tags));
}
private static String sanitizePrefix(String metricPrefix) {
if (StringUtils.isBlank(metricPrefix))
return "";
if (!metricPrefix.endsWith("."))
return metricPrefix + ".";
return metricPrefix;
}
@Override
public void bindTo(MeterRegistry registry) {
if (executorService == null) {
return;
}
String className = executorService.getClass().getName();
if (executorService instanceof ThreadPoolExecutor) {
monitor(registry, (ThreadPoolExecutor) executorService);
} else if (className.equals("java.util.concurrent.Executors$DelegatedScheduledExecutorService")) {
monitor(registry, unwrapThreadPoolExecutor(executorService, executorService.getClass()));
} else if (className.equals("java.util.concurrent.Executors$FinalizableDelegatedExecutorService")) {
monitor(registry, unwrapThreadPoolExecutor(executorService, executorService.getClass().getSuperclass()));
} else if (executorService instanceof ForkJoinPool) {
monitor(registry, (ForkJoinPool) executorService);
} else {
log.warn("Failed to bind as {} is unsupported.", className);
}
}
/**
* Every ScheduledThreadPoolExecutor created by {@link Executors} is wrapped. Also,
* {@link Executors#newSingleThreadExecutor()} wrap a regular {@link ThreadPoolExecutor}.
*/
@Nullable
private ThreadPoolExecutor unwrapThreadPoolExecutor(ExecutorService executor, Class<?> wrapper) {
try {
Field e = wrapper.getDeclaredField("e");
e.setAccessible(true);
return (ThreadPoolExecutor) e.get(executor);
} catch (NoSuchFieldException | IllegalAccessException e) {
// Do nothing. We simply can't get to the underlying ThreadPoolExecutor.
}
return null;
}
private void monitor(MeterRegistry registry, @Nullable ThreadPoolExecutor tp) {
if (tp == null) {
return;
}
FunctionCounter.builder(metricPrefix + "executor.completed", tp, ThreadPoolExecutor::getCompletedTaskCount)
.tags(tags)
.description("The approximate total number of tasks that have completed execution")
.baseUnit(BaseUnits.TASKS)
.register(registry);
Gauge.builder(metricPrefix + "executor.active", tp, ThreadPoolExecutor::getActiveCount)
.tags(tags)
.description("The approximate number of threads that are actively executing tasks")
.baseUnit(BaseUnits.THREADS)
.register(registry);
Gauge.builder(metricPrefix + "executor.queued", tp, tpRef -> tpRef.getQueue().size())
.tags(tags)
.description("The approximate number of tasks that are queued for execution")
.baseUnit(BaseUnits.TASKS)
.register(registry);
Gauge.builder(metricPrefix + "executor.queue.remaining", tp, tpRef -> tpRef.getQueue().remainingCapacity())
.tags(tags)
.description("The number of additional elements that this queue can ideally accept without blocking")
.baseUnit(BaseUnits.TASKS)
.register(registry);
Gauge.builder(metricPrefix + "executor.pool.size", tp, ThreadPoolExecutor::getPoolSize)
.tags(tags)
.description("The current number of threads in the pool")
.baseUnit(BaseUnits.THREADS)
.register(registry);
}
private void monitor(MeterRegistry registry, ForkJoinPool fj) {
FunctionCounter.builder(metricPrefix + "executor.steals", fj, ForkJoinPool::getStealCount)
.tags(tags)
.description("Estimate of the total number of tasks stolen from " +
"one thread's work queue by another. The reported value " +
"underestimates the actual total number of steals when the pool " +
"is not quiescent")
.register(registry);
Gauge.builder(metricPrefix + "executor.queued", fj, ForkJoinPool::getQueuedTaskCount)
.tags(tags)
.description("An estimate of the total number of tasks currently held in queues by worker threads")
.register(registry);
Gauge.builder(metricPrefix + "executor.active", fj, ForkJoinPool::getActiveThreadCount)
.tags(tags)
.description("An estimate of the number of threads that are currently stealing or executing tasks")
.register(registry);
Gauge.builder(metricPrefix + "executor.running", fj, ForkJoinPool::getRunningThreadCount)
.tags(tags)
.description("An estimate of the number of worker threads that are not blocked waiting to join tasks or for other managed synchronization threads")
.register(registry);
}
}