/
MetricsRegistrationService.java
318 lines (287 loc) · 16 KB
/
MetricsRegistrationService.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
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.metrics;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TYPE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.UNIT;
import static org.wildfly.extension.microprofile.config.smallrye.ServiceNames.CONFIG_PROVIDER;
import static org.wildfly.extension.microprofile.metrics.MicroProfileMetricsSubsystemDefinition.CLIENT_FACTORY_CAPABILITY;
import static org.wildfly.extension.microprofile.metrics.MicroProfileMetricsSubsystemDefinition.MANAGEMENT_EXECUTOR;
import static org.wildfly.extension.microprofile.metrics.MicroProfileMetricsSubsystemDefinition.WILDFLY_REGISTRATION_SERVICE;
import static org.wildfly.extension.microprofile.metrics._private.MicroProfileMetricsLogger.LOGGER;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.function.Supplier;
import io.smallrye.metrics.ExtendedMetadata;
import io.smallrye.metrics.MetricRegistries;
import io.smallrye.metrics.setup.JmxRegistrar;
import org.eclipse.microprofile.metrics.Gauge;
import org.eclipse.microprofile.metrics.Metadata;
import org.eclipse.microprofile.metrics.Metric;
import org.eclipse.microprofile.metrics.MetricRegistry;
import org.eclipse.microprofile.metrics.MetricType;
import org.eclipse.microprofile.metrics.MetricUnits;
import org.jboss.as.controller.LocalModelControllerClient;
import org.jboss.as.controller.ModelControllerClientFactory;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.DescriptionProvider;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
public class MetricsRegistrationService implements Service<MetricsRegistrationService> {
private final ImmutableManagementResourceRegistration rootResourceRegistration;
private final Resource rootResource;
private final Supplier<ModelControllerClientFactory> modelControllerClientFactory;
private final Supplier<Executor> managementExecutor;
private final List<String> exposedSubsystems;
private final boolean exposeAnySubsystem;
private JmxRegistrar jmxRegistrar;
private LocalModelControllerClient modelControllerClient;
static void install(OperationContext context, List<String> exposedSubsystems) {
ImmutableManagementResourceRegistration rootResourceRegistration = context.getRootResourceRegistration();
Resource rootResource = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS);
ServiceBuilder<?> serviceBuilder = context.getServiceTarget().addService(WILDFLY_REGISTRATION_SERVICE);
Supplier<ModelControllerClientFactory> modelControllerClientFactory = serviceBuilder.requires(context.getCapabilityServiceName(CLIENT_FACTORY_CAPABILITY, ModelControllerClientFactory.class));
Supplier<Executor> managementExecutor = serviceBuilder.requires(context.getCapabilityServiceName(MANAGEMENT_EXECUTOR, Executor.class));
serviceBuilder.requires(CONFIG_PROVIDER);
MetricsRegistrationService service = new MetricsRegistrationService(rootResourceRegistration, rootResource, modelControllerClientFactory, managementExecutor, exposedSubsystems);
serviceBuilder.setInstance(service)
.install();
}
public MetricsRegistrationService(ImmutableManagementResourceRegistration rootResourceRegistration, Resource rootResource, Supplier<ModelControllerClientFactory> modelControllerClientFactory, Supplier<Executor> managementExecutor, List<String> exposedSubsystems) {
this.rootResourceRegistration = rootResourceRegistration;
this.rootResource = rootResource;
this.modelControllerClientFactory = modelControllerClientFactory;
this.managementExecutor = managementExecutor;
this.exposedSubsystems = exposedSubsystems;
this.exposeAnySubsystem = exposedSubsystems.remove("*");
}
@Override
public void start(StartContext context) throws StartException {
jmxRegistrar = new JmxRegistrar();
try {
jmxRegistrar.init();
} catch (IOException e) {
throw LOGGER.failedInitializeJMXRegistrar(e);
}
modelControllerClient = modelControllerClientFactory.get().createClient(managementExecutor.get());
// register metrics from WildFly subsystems in the VENDOR metric registry
registerMetrics(rootResource,
rootResourceRegistration,
MetricRegistries.get(MetricRegistry.Type.VENDOR),
Function.identity());
}
@Override
public void stop(StopContext context) {
for (MetricRegistry registry : new MetricRegistry[]{
MetricRegistries.get(MetricRegistry.Type.BASE),
MetricRegistries.get(MetricRegistry.Type.VENDOR)}) {
for (String name : registry.getNames()) {
registry.remove(name);
}
}
modelControllerClient.close();
jmxRegistrar = null;
}
@Override
public MetricsRegistrationService getValue() {
return this;
}
public Set<String> registerMetrics(Resource rootResource,
ImmutableManagementResourceRegistration managementResourceRegistration,
MetricRegistry metricRegistry,
Function<PathAddress, PathAddress> resourceAddressResolver) {
Map<PathAddress, Map<String, ModelNode>> metrics = findMetrics(rootResource, managementResourceRegistration);
Set<String> registeredMetrics = registerMetrics(metrics, metricRegistry, resourceAddressResolver);
return registeredMetrics;
}
private Map<PathAddress, Map<String, ModelNode>> findMetrics(Resource rootResource, ImmutableManagementResourceRegistration managementResourceRegistration) {
Map<PathAddress, Map<String, ModelNode>> metrics = new HashMap<>();
collectMetrics(rootResource, managementResourceRegistration, PathAddress.EMPTY_ADDRESS, metrics);
return metrics;
}
private void collectMetrics(final Resource current, ImmutableManagementResourceRegistration managementResourceRegistration, final PathAddress address, Map<PathAddress, Map<String, ModelNode>> collectedMetrics) {
if (!isExposingMetrics(address)) {
return;
}
Map<String, AttributeAccess> attributes = managementResourceRegistration.getAttributes(address);
ModelNode description = null;
for (Map.Entry<String, AttributeAccess> entry : attributes.entrySet()) {
String attributeName = entry.getKey();
AttributeAccess attributeAccess = entry.getValue();
if (attributeAccess.getAccessType() == AttributeAccess.AccessType.METRIC
&& attributeAccess.getStorageType() == AttributeAccess.Storage.RUNTIME) {
if (description == null) {
DescriptionProvider modelDescription = managementResourceRegistration.getModelDescription(address);
description = modelDescription.getModelDescription(Locale.getDefault());
}
Map<String, ModelNode> metricsForResource = collectedMetrics.get(address);
if (metricsForResource == null) {
metricsForResource = new HashMap<>();
}
metricsForResource.put(attributeName, description.get(ATTRIBUTES, attributeName));
collectedMetrics.put(address, metricsForResource);
}
}
for (String type : current.getChildTypes()) {
if (current.hasChildren(type)) {
for (Resource.ResourceEntry entry : current.getChildren(type)) {
final PathElement pathElement = entry.getPathElement();
final PathAddress childAddress = address.append(pathElement);
collectMetrics(entry, managementResourceRegistration, childAddress, collectedMetrics);
}
}
}
}
public Set<String> registerMetrics(Map<PathAddress, Map<String, ModelNode>> metrics, MetricRegistry registry, Function<PathAddress, PathAddress> resourceAddressResolver) {
Set<String> registeredMetricNames = new HashSet<>();
for (Map.Entry<PathAddress, Map<String, ModelNode>> entry : metrics.entrySet()) {
PathAddress resourceAddress = resourceAddressResolver.apply(entry.getKey());
for (Map.Entry<String, ModelNode> wildflyMetric : entry.getValue().entrySet()) {
String attributeName = wildflyMetric.getKey();
ModelNode attributeDescription = wildflyMetric.getValue();
String metricName = resourceAddress.toPathStyleString().substring(1) + "/" + attributeName;
String unit = attributeDescription.get(UNIT).asString(MetricUnits.NONE).toLowerCase();
String description = attributeDescription.get(DESCRIPTION).asStringOrNull();
// fill the MP Metric tags with the address key/value pairs (that will be not preserve order)
// and an attribute=<attributeName> tag
HashMap<String, String> tags = new HashMap<>();
for (PathElement element: resourceAddress) {
tags.put(element.getKey(), element.getValue());
}
tags.put(ATTRIBUTE, attributeName);
Metadata metadata = new ExtendedMetadata(metricName, attributeName + " for " + resourceAddress.toHttpStyleString(), description, MetricType.GAUGE, unit);
metadata.setTags(tags);
ModelType type = attributeDescription.get(TYPE).asType();
switch (type) {
// simple numerical type
case BIG_DECIMAL:
case BIG_INTEGER:
case DOUBLE:
case INT:
case LONG:
break;
case BYTES:
case LIST:
case OBJECT:
case PROPERTY:
case EXPRESSION:
case BOOLEAN:
case STRING:
case TYPE:
case UNDEFINED:
default:
LOGGER.debugf("Type %s is not supported for MicroProfile Metrics, the attribute %s on %s will not be registered.", type, attributeName, resourceAddress);
continue;
}
Metric metric = new Gauge() {
@Override
public Number getValue() {
final ModelNode readAttributeOp = new ModelNode();
readAttributeOp.get(OP).set(READ_ATTRIBUTE_OPERATION);
readAttributeOp.get(OP_ADDR).set(resourceAddress.toModelNode());
readAttributeOp.get(ModelDescriptionConstants.INCLUDE_UNDEFINED_METRIC_VALUES).set(true);
readAttributeOp.get(NAME).set(attributeName);
ModelNode response = modelControllerClient.execute(readAttributeOp);
String error = getFailureDescription(response);
if (error != null) {
registry.remove(metricName);
throw LOGGER.unableToReadAttribute(attributeName, resourceAddress, error);
}
ModelNode result = response.get(RESULT);
if (result.isDefined()) {
try {
switch (type) {
case INT:
return result.asInt();
case LONG:
return result.asLong();
default:
// handle other numerical types as Double
return result.asDouble();
}
} catch (Exception e) {
throw LOGGER.unableToConvertAttribute(attributeName, resourceAddress, e);
}
} else {
registry.remove(metricName);
throw LOGGER.undefinedMetric(attributeName, resourceAddress);
}
}
};
registry.register(metadata, metric);
registeredMetricNames.add(metadata.getName());
}
}
return registeredMetricNames;
}
private boolean isExposingMetrics(PathAddress address) {
// root resource
if (address.size() == 0) {
return true;
}
if (address.getElement(0).getKey().equals(SUBSYSTEM)) {
String subsystemName = address.getElement(0).getValue();
return exposeAnySubsystem || exposedSubsystems.contains(subsystemName);
}
// do not expose metrics for resources outside the subsystems.
return false;
}
private boolean isMetric(AttributeAccess attributeAccess) {
if (attributeAccess.getAccessType() == AttributeAccess.AccessType.METRIC && attributeAccess.getStorageType() == AttributeAccess.Storage.RUNTIME) {
return true;
}
return false;
}
private String getFailureDescription(ModelNode result) {
if (result.hasDefined(FAILURE_DESCRIPTION)) {
return result.get(FAILURE_DESCRIPTION).toString();
}
return null;
}
}