-
Notifications
You must be signed in to change notification settings - Fork 96
/
JmxScraper.java
402 lines (344 loc) · 18.3 KB
/
JmxScraper.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package com.criteo.nosql.cassandra.exporter;
import io.prometheus.client.Gauge;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeType;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.rmi.RMIConnectorServer;
import javax.naming.Context;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class JmxScraper {
static final Gauge STATS = Gauge.build()
.name("cassandra_stats")
.help("node stats")
.labelNames("cluster", "datacenter", "keyspace", "table", "name")
.register();
private static final Logger logger = LoggerFactory.getLogger(JmxScraper.class);
private static final double[] offsetPercentiles = new double[]{0.5, 0.75, 0.95, 0.98, 0.99};
private static final String metricSeparator = ":";
private static final Map<String, MBeanAttributeInfo[]> mBeansAttributesCache = new HashMap<>();
private final String jmxUrl;
private final Pattern PATTERN = Pattern.compile("(:type=|,[^=]+=|\\.)");
private final List<Pattern> blacklist;
private final TreeMap<Integer, List<Pattern>> scrapFrequencies;
private final Map<Integer, Long> lastScrapes;
private final Map<String, Object> jmxEnv;
public JmxScraper(String jmxUrl, Optional<String> username, Optional<String> password, boolean ssl, List<String> blacklist, SortedMap<Integer, List<String>> scrapFrequencies) {
this.jmxUrl = jmxUrl;
this.blacklist = blacklist.stream().map(Pattern::compile).collect(toList());
this.scrapFrequencies = new TreeMap<>();
this.lastScrapes = new HashMap<>(scrapFrequencies.size());
scrapFrequencies.forEach((k, v) -> {
this.scrapFrequencies.put(k * 1000, v.stream().map(Pattern::compile).collect(toList()));
this.lastScrapes.put(k * 1000, 0L);
});
jmxEnv = new HashMap<>();
username.ifPresent(user -> {
String[] credential = new String[]{user, password.orElse("")};
jmxEnv.put(javax.management.remote.JMXConnector.CREDENTIALS, credential);
});
if (ssl) {
jmxEnv.put(Context.SECURITY_PROTOCOL, "ssl");
SslRMIClientSocketFactory clientSocketFactory = new SslRMIClientSocketFactory();
jmxEnv.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, clientSocketFactory);
jmxEnv.put("com.sun.jndi.rmi.factory.socket", clientSocketFactory);
}
}
/**
* Convert a Cassandra EstimatedHistogram value into known percentiles histogram
*
* @param counts the serialized value of the estimatedhistrogram
* @return Percentiles of the histogram in the given order double[]{0.5, 0.75, 0.95, 0.98, 0.99};
*/
private static double[] metricPercentilesAsArray(long[] counts) {
// Copy-pasted mostly from https://github.com/apache/cassandra/blob/f59df2893b66b3a8715b9792679e51815982a542/src/java/org/apache/cassandra/tools/NodeProbe.java#L1223
double[] result = new double[7];
if (counts == null || counts.length == 0) {
Arrays.fill(result, Double.NaN);
return result;
}
long[] offsets = EstimatedHistogram.newOffsets(counts.length, false);
EstimatedHistogram metric = new EstimatedHistogram(offsets, counts);
if (metric.isOverflowed()) {
logger.error("EstimatedHistogram overflowed larger than {}, unable to calculate percentiles", offsets[offsets.length - 1]);
for (int i = 0; i < result.length; i++)
result[i] = Double.NaN;
} else {
for (int i = 0; i < offsetPercentiles.length; i++)
result[i] = metric.percentile(offsetPercentiles[i]);
}
result[5] = metric.min();
result[6] = metric.max();
return result;
}
private static void updateStats(NodeInfo nodeInfo, String metricName, Double value) {
if (metricName.startsWith("org:apache:cassandra:metrics:keyspace:")) {
int pathLength = "org:apache:cassandra:metrics:keyspace:".length();
int pos = metricName.indexOf(':', pathLength);
String keyspaceName = metricName.substring(pathLength, pos);
STATS.labels(nodeInfo.clusterName, nodeInfo.datacenterName,
nodeInfo.keyspaces.contains(keyspaceName) ? keyspaceName : "", "", metricName).set(value);
return;
}
// Cassandra 3.x path style to get table info
if (metricName.startsWith("org:apache:cassandra:metrics:table:")) {
int pathLength = "org:apache:cassandra:metrics:table:".length();
int keyspacePos = metricName.indexOf(':', pathLength);
int tablePos = metricName.indexOf(':', keyspacePos + 1);
String keyspaceName = metricName.substring(pathLength, keyspacePos);
String tableName = tablePos > 0 ? metricName.substring(keyspacePos + 1, tablePos) : "";
if (nodeInfo.keyspaces.contains(keyspaceName) && nodeInfo.tables.contains(tableName)) {
STATS.labels(nodeInfo.clusterName, nodeInfo.datacenterName, keyspaceName, tableName, metricName).set(value);
return;
}
}
// Cassandra 2.x path style to get table info
if (metricName.startsWith("org:apache:cassandra:metrics:columnfamily:")) {
int pathLength = "org:apache:cassandra:metrics:columnfamily:".length();
int keyspacePos = metricName.indexOf(':', pathLength);
int tablePos = metricName.indexOf(':', keyspacePos + 1);
String keyspaceName = metricName.substring(pathLength, keyspacePos);
String tableName = tablePos > 0 ? metricName.substring(keyspacePos + 1, tablePos) : "";
if (nodeInfo.keyspaces.contains(keyspaceName) && nodeInfo.tables.contains(tableName)) {
STATS.labels(nodeInfo.clusterName, nodeInfo.datacenterName, keyspaceName, tableName, metricName).set(value);
return;
}
}
STATS.labels(nodeInfo.clusterName, nodeInfo.datacenterName, "", "", metricName).set(value);
}
public void run(final boolean forever) throws Exception {
STATS.clear();
try (JMXConnector jmxc = JMXConnectorFactory.connect(new JMXServiceURL(jmxUrl), jmxEnv)) {
final MBeanServerConnection beanConn = jmxc.getMBeanServerConnection();
do {
final long now = System.currentTimeMillis();
// If we can't get the node info, exit the run early in order to avoid creating stale metrics
// that will never be cleaned after that
// This situation can appear if the node start to be unresponsive and that some jmx operation timeouts
final Optional<NodeInfo> nodeInfo = NodeInfo.getNodeInfo(beanConn);
if (!nodeInfo.isPresent()) return;
MBeanAttributeInfo attr = new MBeanAttributeInfo("", "", "", false, false, false);
beanConn.queryMBeans(null, null).stream()
.map(objectInstance -> new MBeanInfo(getMetricPath(objectInstance.getObjectName(), attr), objectInstance.getObjectName(), attr))
.filter(mbean -> blacklist.stream().noneMatch(pattern -> pattern.matcher(mbean.metricName).matches()))
.flatMap(mBeanInfo -> toMBeanInfos(beanConn, mBeanInfo))
.filter(m -> shouldScrap(m, now))
.forEach(mBean -> updateMetric(beanConn, mBean, nodeInfo.get()));
lastScrapes.forEach((k, lastScrape) -> {
if (now - lastScrape >= k) lastScrapes.put(k, now);
});
final long duration = System.currentTimeMillis() - now;
logger.info("Scrap took {}ms for the whole run", duration);
// don't go lower than 10 sec
if (forever) Thread.sleep(Math.max(scrapFrequencies.firstKey() - duration, 10 * 1000));
} while (forever);
}
}
/**
* Return if we should scrap this MBean at a given point in time
*
* @param mBeanInfo Should we scrap this MBean
* @param now timestamp representing the point in time
* @return True if we should scrap it, False if not
*/
private boolean shouldScrap(final MBeanInfo mBeanInfo, final long now) {
if (blacklist.stream().anyMatch(pattern -> pattern.matcher(mBeanInfo.metricName).matches())) {
return false;
}
for (Map.Entry<Integer, List<Pattern>> e : scrapFrequencies.descendingMap().entrySet()) {
for (Pattern p : e.getValue()) {
if (p.matcher(mBeanInfo.metricName).matches()) {
return now - lastScrapes.get(e.getKey()) >= e.getKey();
}
}
}
return false;
}
/**
* Return all possible MbeanInfo from a MBean path.
* The main interest is to unroll of the attributes of an Mbeans in order to filter on it
*
* @param beanConn The JMX connexion
*/
private Stream<MBeanInfo> toMBeanInfos(MBeanServerConnection beanConn, MBeanInfo mBeanInfo) {
try {
ObjectName mbeanName = mBeanInfo.mBeanName;
String name = "" + mbeanName.getKeyPropertyList().size() + mbeanName.getKeyProperty("type") + mbeanName.getKeyProperty("name");
MBeanAttributeInfo[] info = mBeansAttributesCache.computeIfAbsent(name, xx -> {
try {
return beanConn.getMBeanInfo(mbeanName).getAttributes();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
return Arrays.stream(info)
.filter(MBeanAttributeInfo::isReadable)
//TODO: Refactor get MetricPath
.map(mBeanAttributeInfo -> new MBeanInfo(mBeanInfo.metricName + mBeanAttributeInfo.getName().toLowerCase(), mbeanName, mBeanAttributeInfo));
} catch (Exception e) {
logger.error(" Error when scraping mbean {}", mBeanInfo.mBeanName, e);
return Stream.empty();
}
}
/**
* Return the formatted metric for a given MBean and attribute
*
* @param mbeanName Mbean object
* @param attr Specific attribute of this Mbean
* @return the formatted metric name
*/
private String getMetricPath(ObjectName mbeanName, MBeanAttributeInfo attr) {
String properties = PATTERN.matcher(mbeanName.toString())
.replaceAll(metricSeparator)
.replace(' ', '_') + metricSeparator + attr.getName();
return properties.toLowerCase();
}
/**
* Update the metrics registry for a given MBeanInfo
*
* @param beanConn
* @param mBeanInfo
*/
private void updateMetric(MBeanServerConnection beanConn, MBeanInfo mBeanInfo, NodeInfo nodeInfo) {
long start = System.currentTimeMillis();
Object value = null;
try {
value = beanConn.getAttribute(mBeanInfo.mBeanName, mBeanInfo.attribute.getName());
} catch (Exception e) {
logger.error("Cannot get value for {} {}", mBeanInfo.metricName, mBeanInfo.attribute.getName(), e);
}
if (value == null) {
return;
}
// Converting attribute to double
switch (mBeanInfo.attribute.getType()) {
case "long":
case "int":
case "double":
updateStats(nodeInfo, mBeanInfo.metricName, ((Number) value).doubleValue());
break;
case "boolean":
updateStats(nodeInfo, mBeanInfo.metricName, ((Boolean) value) ? 1.0 : 0.0);
break;
case "javax.management.openmbean.CompositeData":
CompositeData data = ((CompositeData) value);
CompositeType types = ((CompositeData) value).getCompositeType();
for (String itemName : types.keySet()) {
switch (types.getType(itemName).getTypeName()) {
case "java.lang.Long":
case "java.lang.Double":
case "java.lang.Integer":
updateStats(nodeInfo, mBeanInfo.metricName + metricSeparator + itemName.toLowerCase(), ((Number) data.get(itemName)).doubleValue());
break;
}
}
break;
case "java.lang.Object":
String str = value.toString();
Character first = str.charAt(0);
//Most beans declared as Object are Double in disguise
if (first >= '0' && first <= '9') {
updateStats(nodeInfo, mBeanInfo.metricName, Double.valueOf(str));
// https://books.google.fr/books?id=BvsVuph6ehMC&pg=PA82
// EstimatedHistogram are object for JMX but are long[] behind
} else if (str.startsWith(long[].class.getName())) {
// This is ugly to redo the shouldScrap and metricName formating this late
// but EstimatedHistogram in cassandra are special case that we cannot detect before :(
double[] percentiles = metricPercentilesAsArray((long[]) value);
for (int i = 0; i < offsetPercentiles.length; i++) {
final String metricName = mBeanInfo.metricName.replace(":value", ":" + (int) (offsetPercentiles[i] * 100) + "thpercentile");
MBeanInfo info = new MBeanInfo(metricName, mBeanInfo.mBeanName, mBeanInfo.attribute);
if (shouldScrap(info, start)) {
updateStats(nodeInfo, metricName, percentiles[i]);
}
}
final String minMetricName = mBeanInfo.metricName.replace(":value", ":min");
MBeanInfo info = new MBeanInfo(minMetricName, mBeanInfo.mBeanName, mBeanInfo.attribute);
if (shouldScrap(info, start)) {
updateStats(nodeInfo, minMetricName, percentiles[5]);
}
final String metricName = mBeanInfo.metricName.replace(":value", ":max");
info = new MBeanInfo(metricName, mBeanInfo.mBeanName, mBeanInfo.attribute);
if (shouldScrap(info, start)) {
updateStats(nodeInfo, metricName, percentiles[6]);
}
} else {
logger.debug("Cannot parse {} as it as an unknown type {} with value {}", mBeanInfo.mBeanName, mBeanInfo.attribute.getType(), value);
}
break;
default:
logger.debug("Cannot parse {} as it as an unknown type {} with value {}", mBeanInfo.mBeanName, mBeanInfo.attribute.getType(), value);
break;
}
logger.trace("Scrapping took {}ms for {}", (System.currentTimeMillis() - start), mBeanInfo.metricName);
}
/**
* POJO to hold information regarding a metric
*/
private static class MBeanInfo {
final String metricName;
final ObjectName mBeanName;
final MBeanAttributeInfo attribute;
MBeanInfo(String name, ObjectName mBeanName, MBeanAttributeInfo attribute) {
this.metricName = name;
this.attribute = attribute;
this.mBeanName = mBeanName;
}
}
private static class NodeInfo {
final String clusterName;
final String datacenterName;
final Set<String> keyspaces;
final Set<String> tables;
private NodeInfo(String clusterName, String datacenterName, Set<String> keyspaces, Set<String> tables) {
this.clusterName = clusterName;
this.datacenterName = datacenterName;
this.keyspaces = keyspaces;
this.tables = tables;
}
static Optional<NodeInfo> getNodeInfo(MBeanServerConnection beanConn) {
String clusterName;
String datacenterName;
Set<String> keyspaces = new HashSet<>();
Set<String> tables = new HashSet<>();
try {
clusterName = beanConn.getAttribute(ObjectName.getInstance("org.apache.cassandra.db:type=StorageService"), "ClusterName").toString();
} catch (Exception e) {
logger.error("Cannot retrieve the cluster name information for the node", e);
return Optional.empty();
}
try {
String hostID = beanConn.getAttribute(ObjectName.getInstance("org.apache.cassandra.db:type=StorageService"), "LocalHostId").toString();
Map<String, String> hostIdToEndpoint = (Map<String, String>) beanConn.getAttribute(ObjectName.getInstance("org.apache.cassandra.db:type=StorageService"), "HostIdToEndpoint");
Object opParams[] = {hostIdToEndpoint.get(hostID)};
String opSig[] = {String.class.getName()};
datacenterName = beanConn.invoke(ObjectName.getInstance("org.apache.cassandra.db:type=EndpointSnitchInfo"), "getDatacenter", opParams, opSig).toString();
} catch (Exception e) {
logger.error("Cannot retrieve the datacenter name information for the node", e);
return Optional.empty();
}
try {
Set<ObjectName> names = beanConn.queryNames(ObjectName.getInstance("org.apache.cassandra.db:type=ColumnFamilies,keyspace=*,columnfamily=*"), null);
for (ObjectName name : names) {
String[] values = name.toString().split("[=,]");
keyspaces.add(values[3].toLowerCase());
tables.add(values[5].toLowerCase());
}
} catch (Exception e) {
logger.error("Cannot retrieve keyspaces/tables information", e);
return Optional.empty();
}
return Optional.of(new NodeInfo(clusterName, datacenterName, keyspaces, tables));
}
}
}