forked from open-telemetry/opentelemetry-java-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJmxScraper.java
More file actions
255 lines (223 loc) · 9.05 KB
/
JmxScraper.java
File metadata and controls
255 lines (223 loc) · 9.05 KB
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
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.contrib.jmxscraper;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.contrib.jmxscraper.config.JmxScraperConfig;
import io.opentelemetry.contrib.jmxscraper.config.PropertiesCustomizer;
import io.opentelemetry.contrib.jmxscraper.config.PropertiesSupplier;
import io.opentelemetry.instrumentation.jmx.engine.JmxMetricInsight;
import io.opentelemetry.instrumentation.jmx.engine.MetricConfiguration;
import io.opentelemetry.instrumentation.jmx.yaml.RuleParser;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
public class JmxScraper {
private static final Logger logger = Logger.getLogger(JmxScraper.class.getName());
private static final String CONFIG_ARG = "-config";
private static final String TEST_ARG = "-test";
private final JmxConnectorBuilder client;
private final JmxMetricInsight service;
private final JmxScraperConfig config;
private final AtomicBoolean running = new AtomicBoolean(false);
/**
* Main method to create and run a {@link JmxScraper} instance.
*
* @param args - must be of the form "-config {jmx_config_path,'-'}"
*/
@SuppressWarnings("SystemExitOutsideMain")
public static void main(String[] args) {
// set log format
System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tF %1$tT %4$s %5$s%n");
List<String> effectiveArgs = new ArrayList<>(Arrays.asList(args));
boolean testMode = effectiveArgs.remove(TEST_ARG);
try {
Properties argsConfig = argsToConfig(effectiveArgs);
propagateToSystemProperties(argsConfig);
// auto-configure and register SDK
PropertiesCustomizer configCustomizer = new PropertiesCustomizer();
AutoConfiguredOpenTelemetrySdk.builder()
.addPropertiesSupplier(new PropertiesSupplier(argsConfig))
.addPropertiesCustomizer(configCustomizer)
.setResultAsGlobal()
.build();
JmxScraperConfig scraperConfig = configCustomizer.getScraperConfig();
long exportSeconds = scraperConfig.getSamplingInterval().toMillis() / 1000;
logger.log(Level.INFO, "metrics export interval (seconds) = " + exportSeconds);
JmxMetricInsight service =
JmxMetricInsight.createService(
GlobalOpenTelemetry.get(), scraperConfig.getSamplingInterval().toMillis());
JmxConnectorBuilder connectorBuilder =
JmxConnectorBuilder.createNew(scraperConfig.getServiceUrl());
Optional.ofNullable(scraperConfig.getUsername()).ifPresent(connectorBuilder::withUser);
Optional.ofNullable(scraperConfig.getPassword()).ifPresent(connectorBuilder::withPassword);
if (scraperConfig.isRegistrySsl()) {
connectorBuilder.withSslRegistry();
}
if (testMode) {
System.exit(testConnection(connectorBuilder) ? 0 : 1);
} else {
JmxScraper jmxScraper = new JmxScraper(connectorBuilder, service, scraperConfig);
jmxScraper.start();
}
} catch (ConfigurationException e) {
logger.log(Level.SEVERE, "invalid configuration ", e);
System.exit(1);
} catch (InvalidArgumentException e) {
logger.log(Level.SEVERE, e.getMessage(), e);
logger.info("Usage: java -jar <path_to_jmxscraper.jar> [-test] [-config <conf>]");
logger.info(" -test test JMX connection with provided configuration and exit");
logger.info(
" -config <conf> provide configuration, where <conf> is - for stdin, or <path_to_config.properties>");
System.exit(1);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unable to connect ", e);
System.exit(2);
} catch (RuntimeException e) {
logger.log(Level.SEVERE, e.getMessage(), e);
System.exit(3);
}
}
private static boolean testConnection(JmxConnectorBuilder connectorBuilder) {
try (JMXConnector connector = connectorBuilder.build()) {
MBeanServerConnection connection = connector.getMBeanServerConnection();
Integer mbeanCount = connection.getMBeanCount();
if (mbeanCount > 0) {
logger.log(Level.INFO, "JMX connection test OK");
return true;
} else {
logger.log(Level.SEVERE, "JMX connection test ERROR");
return false;
}
} catch (IOException e) {
logger.log(Level.SEVERE, "JMX connection test ERROR", e);
return false;
}
}
// package private for testing
static void propagateToSystemProperties(Properties properties) {
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = entry.getKey().toString();
String value = entry.getValue().toString();
if (key.startsWith("javax.net.ssl.keyStore") || key.startsWith("javax.net.ssl.trustStore")) {
if (System.getProperty(key) == null) {
System.setProperty(key, value);
}
}
}
}
/**
* Create {@link Properties} from command line options
*
* @param args application commandline arguments
*/
static Properties argsToConfig(List<String> args) throws InvalidArgumentException {
if (args.isEmpty()) {
// empty properties from stdin or external file
// config could still be provided through JVM system properties
return new Properties();
}
if (args.size() != 2) {
throw new InvalidArgumentException("Unexpected number of arguments");
}
if (!args.get(0).equalsIgnoreCase(CONFIG_ARG)) {
throw new InvalidArgumentException("Unexpected argument must be '" + CONFIG_ARG + "'");
}
String path = args.get(1);
if (path.trim().equals("-")) {
return loadPropertiesFromStdin();
} else {
return loadPropertiesFromPath(path);
}
}
private static Properties loadPropertiesFromStdin() throws InvalidArgumentException {
Properties properties = new Properties();
try (InputStream is = new DataInputStream(System.in)) {
properties.load(is);
return properties;
} catch (IOException e) {
// an IO error is very unlikely here
throw new InvalidArgumentException("Failed to read config properties from stdin", e);
}
}
private static Properties loadPropertiesFromPath(String path) throws InvalidArgumentException {
Properties properties = new Properties();
try (InputStream is = Files.newInputStream(Paths.get(path))) {
properties.load(is);
return properties;
} catch (IOException e) {
throw new InvalidArgumentException("Failed to read config from file: '" + path + "'", e);
}
}
private JmxScraper(
JmxConnectorBuilder client, JmxMetricInsight service, JmxScraperConfig config) {
this.client = client;
this.service = service;
this.config = config;
}
private void start() throws IOException {
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
logger.info("JMX scraping stopped");
running.set(false);
}));
try (JMXConnector connector = client.build()) {
MBeanServerConnection connection = connector.getMBeanServerConnection();
service.startRemote(getMetricConfig(config), () -> Collections.singletonList(connection));
running.set(true);
logger.info("JMX scraping started");
while (running.get()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// silently ignored
}
}
}
}
private static MetricConfiguration getMetricConfig(JmxScraperConfig scraperConfig) {
MetricConfiguration config = new MetricConfiguration();
for (String system : scraperConfig.getTargetSystems()) {
try (InputStream yaml = scraperConfig.getTargetSystemYaml(system)) {
RuleParser.get().addMetricDefsTo(config, yaml, system);
} catch (IOException e) {
throw new IllegalStateException("Error while loading rules for system " + system, e);
}
}
for (String file : scraperConfig.getJmxConfig()) {
addRulesFromFile(file, config);
}
return config;
}
private static void addRulesFromFile(String file, MetricConfiguration conf) {
Path path = Paths.get(file);
if (!Files.isReadable(path)) {
throw new IllegalArgumentException("Unable to read file: " + path);
}
try (InputStream inputStream = Files.newInputStream(path)) {
RuleParser.get().addMetricDefsTo(conf, inputStream, file);
} catch (IOException e) {
throw new IllegalArgumentException("Error while loading rules from file: " + file, e);
}
}
}