-
Notifications
You must be signed in to change notification settings - Fork 8
/
MainModule.java
489 lines (450 loc) · 20.9 KB
/
MainModule.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
/*
* Copyright The Cryostat Authors.
*
* 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
*
* http://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.cryostat.agent;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import io.cryostat.agent.harvest.HarvestModule;
import io.cryostat.agent.remote.RemoteContext;
import io.cryostat.agent.remote.RemoteModule;
import io.cryostat.agent.triggers.TriggerModule;
import io.cryostat.libcryostat.JvmIdentifier;
import io.cryostat.libcryostat.net.IDException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsParameters;
import com.sun.net.httpserver.HttpsServer;
import dagger.Lazy;
import dagger.Module;
import dagger.Provides;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Module(
includes = {
RemoteModule.class,
HarvestModule.class,
TriggerModule.class,
ConfigModule.class,
})
public abstract class MainModule {
// one for outbound HTTP requests, one for incoming HTTP requests, and one as a general worker
private static final int NUM_WORKER_THREADS = 3;
private static final String JVM_ID = "JVM_ID";
private static final String HTTP_CLIENT_SSL_CTX = "HTTP_CLIENT_SSL_CTX";
private static final String HTTP_SERVER_SSL_CTX = "HTTP_SERVER_SSL_CTX";
@Provides
@Singleton
public static AtomicInteger provideThreadId() {
return new AtomicInteger(0);
}
@Provides
@Singleton
public static ScheduledExecutorService provideExecutor(AtomicInteger threadId) {
return Executors.newScheduledThreadPool(
NUM_WORKER_THREADS,
r -> {
Thread thread = new Thread(r);
thread.setName("cryostat-agent-worker-" + threadId.getAndIncrement());
thread.setDaemon(true);
return thread;
});
}
@Provides
@Singleton
public static WebServer provideWebServer(
Lazy<Set<RemoteContext>> remoteContexts,
Lazy<CryostatClient> cryostat,
HttpServer http,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_CREDENTIALS_PASS_HASH_FUNCTION)
MessageDigest digest,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_CREDENTIALS_USER) String user,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_CREDENTIALS_PASS_LENGTH) int passLength,
@Named(ConfigModule.CRYOSTAT_AGENT_CALLBACK) URI callback,
Lazy<Registration> registration) {
return new WebServer(
remoteContexts, cryostat, http, digest, user, passLength, callback, registration);
}
@Provides
@Singleton
@Named(HTTP_CLIENT_SSL_CTX)
public static SSLContext provideClientSslContext(
@Named(ConfigModule.CRYOSTAT_AGENT_WEBCLIENT_TLS_VERSION) String clientTlsVersion,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBCLIENT_TLS_TRUST_ALL) boolean trustAll,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBCLIENT_TLS_TRUSTSTORE_CERTS)
List<TruststoreConfig> truststores) {
try {
if (trustAll) {
SSLContext sslCtx = SSLContext.getInstance(clientTlsVersion);
sslCtx.init(
null,
new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(
X509Certificate[] chain, String authType)
throws CertificateException {}
@Override
public void checkServerTrusted(
X509Certificate[] chain, String authType)
throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
},
null);
return sslCtx;
}
SSLContext sslCtx = SSLContext.getInstance(clientTlsVersion);
// set up trust manager factory
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init((KeyStore) null);
X509TrustManager defaultTrustManager = null;
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
defaultTrustManager = (X509TrustManager) tm;
break;
}
}
// initialize truststore
KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
ts.load(null, null);
for (TruststoreConfig truststore : truststores) {
// load truststore with certificatesCertificate
InputStream certFile = new FileInputStream(truststore.getPath());
CertificateFactory cf = CertificateFactory.getInstance(truststore.getType());
Certificate cert = cf.generateCertificate(certFile);
if (ts.containsAlias(truststore.getType())) {
throw new IllegalStateException(
String.format(
"truststore already contains a certificate with alias"
+ " \"%s\"",
truststore.getAlias()));
}
ts.setCertificateEntry(truststore.getAlias(), cert);
certFile.close();
}
// set up trust manager factory
tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);
X509TrustManager customTrustManager = null;
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
customTrustManager = (X509TrustManager) tm;
break;
}
}
final X509TrustManager finalDefaultTM = defaultTrustManager;
final X509TrustManager finalCustomTM = customTrustManager;
X509TrustManager mergedTrustManager =
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
finalCustomTM.checkClientTrusted(chain, authType);
} catch (CertificateException e) {
finalDefaultTM.checkClientTrusted(chain, authType);
}
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
finalCustomTM.checkServerTrusted(chain, authType);
} catch (CertificateException e) {
finalDefaultTM.checkServerTrusted(chain, authType);
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return finalDefaultTM.getAcceptedIssuers();
}
};
// set up HTTPS context
sslCtx.init(null, new TrustManager[] {mergedTrustManager}, null);
return sslCtx;
} catch (NoSuchAlgorithmException
| KeyManagementException
| KeyStoreException
| CertificateException
| IOException e) {
throw new RuntimeException(e);
}
}
@Provides
@Singleton
@Named(HTTP_SERVER_SSL_CTX)
public static Optional<SSLContext> provideServerSslContext(
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_TLS_VERSION) String serverTlsVersion,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_TLS_KEYSTORE_PASS)
Optional<String> keyStorePassFile,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_TLS_KEYSTORE_PASS_CHARSET)
String passFileCharset,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_TLS_KEYSTORE_FILE)
Optional<String> keyStoreFilePath,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_TLS_KEYSTORE_TYPE) String keyStoreType,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_TLS_CERT_ALIAS) String certAlias,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_TLS_CERT_FILE)
Optional<String> certFilePath,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_TLS_CERT_TYPE) String certType) {
boolean ssl =
keyStorePassFile.isPresent()
&& keyStoreFilePath.isPresent()
&& certFilePath.isPresent();
if (!ssl) {
if (keyStorePassFile.isPresent()
|| keyStoreFilePath.isPresent()
|| certFilePath.isPresent()) {
throw new IllegalArgumentException(
"The file paths for the keystore, keystore password, and certificate must"
+ " ALL be provided to set up HTTPS connections. Otherwise, make sure"
+ " they are all unset to use an HTTP server.");
}
return Optional.empty();
}
try (InputStream pass = new FileInputStream(keyStorePassFile.get());
InputStream keystore = new FileInputStream(keyStoreFilePath.get());
InputStream certFile = new FileInputStream(certFilePath.get())) {
SSLContext sslContext = SSLContext.getInstance(serverTlsVersion);
// initialize keystore
String password = IOUtils.toString(pass, Charset.forName(passFileCharset));
password = password.substring(0, password.length() - 1);
KeyStore ks = KeyStore.getInstance(keyStoreType);
ks.load(keystore, password.toCharArray());
// set up certificate factory
CertificateFactory cf = CertificateFactory.getInstance(certType);
Certificate cert = cf.generateCertificate(certFile);
if (ks.containsAlias(certAlias)) {
throw new IllegalStateException(
String.format(
"%s keystore at %s already contains a certificate with alias"
+ " \"%s\"",
keyStoreType, keyStoreFilePath, certAlias));
}
ks.setCertificateEntry(certAlias, cert);
// set up key manager factory
KeyManagerFactory kmf =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, password.toCharArray());
// set up trust manager factory
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
// set up HTTPS context
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return Optional.of(sslContext);
} catch (KeyStoreException
| CertificateException
| UnrecoverableKeyException
| KeyManagementException
| IOException
| NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
@Provides
@Singleton
public static HttpClient provideHttpClient(
@Named(HTTP_CLIENT_SSL_CTX) SSLContext sslContext,
AuthorizationType authorizationType,
@Named(ConfigModule.CRYOSTAT_AGENT_AUTHORIZATION) Optional<String> authorization,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBCLIENT_TLS_VERIFY_HOSTNAME)
boolean verifyHostname,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBCLIENT_CONNECT_TIMEOUT_MS) int connectTimeout,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBCLIENT_RESPONSE_TIMEOUT_MS) int responseTimeout) {
Set<Header> headers = new HashSet<>();
authorization
.filter(Objects::nonNull)
.map(v -> new BasicHeader("Authorization", v))
.ifPresent(headers::add);
HttpClientBuilder builder =
HttpClients.custom()
.setDefaultHeaders(headers)
.setSSLContext(sslContext)
.setDefaultRequestConfig(
RequestConfig.custom()
.setAuthenticationEnabled(true)
.setExpectContinueEnabled(true)
.setConnectTimeout(connectTimeout)
.setSocketTimeout(responseTimeout)
.build());
if (!verifyHostname) {
builder = builder.setSSLHostnameVerifier((hostname, session) -> true);
}
return builder.build();
}
@Provides
@Singleton
public static HttpServer provideHttpServer(
ScheduledExecutorService executor,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_HOST) String host,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBSERVER_PORT) int port,
@Named(HTTP_SERVER_SSL_CTX) Optional<SSLContext> sslContext) {
try {
HttpServer http;
if (sslContext.isEmpty()) {
http = HttpServer.create(new InetSocketAddress(host, port), 0);
} else {
http = HttpsServer.create(new InetSocketAddress(host, port), 0);
((HttpsServer) http)
.setHttpsConfigurator(
new HttpsConfigurator(sslContext.get()) {
public void configure(HttpsParameters params) {
try {
SSLContext context = getSSLContext();
SSLEngine engine = context.createSSLEngine();
params.setNeedClientAuth(false);
params.setCipherSuites(engine.getEnabledCipherSuites());
params.setProtocols((engine.getEnabledProtocols()));
params.setSSLParameters(
context.getDefaultSSLParameters());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
http.setExecutor(executor);
return http;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Provides
public static ObjectMapper provideObjectMapper() {
return new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Provides
@Singleton
public static CryostatClient provideCryostatClient(
ScheduledExecutorService executor,
ObjectMapper objectMapper,
HttpClient http,
@Named(ConfigModule.CRYOSTAT_AGENT_INSTANCE_ID) String instanceId,
@Named(JVM_ID) String jvmId,
@Named(ConfigModule.CRYOSTAT_AGENT_APP_NAME) String appName,
@Named(ConfigModule.CRYOSTAT_AGENT_BASEURI) URI baseUri,
@Named(ConfigModule.CRYOSTAT_AGENT_REALM) String realm) {
return new CryostatClient(
executor, objectMapper, http, instanceId, jvmId, appName, baseUri, realm);
}
@Provides
@Singleton
public static Registration provideRegistration(
ScheduledExecutorService executor,
CryostatClient cryostat,
@Named(ConfigModule.CRYOSTAT_AGENT_CALLBACK) URI callback,
WebServer webServer,
@Named(ConfigModule.CRYOSTAT_AGENT_INSTANCE_ID) String instanceId,
@Named(JVM_ID) String jvmId,
@Named(ConfigModule.CRYOSTAT_AGENT_APP_NAME) String appName,
@Named(ConfigModule.CRYOSTAT_AGENT_REALM) String realm,
@Named(ConfigModule.CRYOSTAT_AGENT_HOSTNAME) String hostname,
@Named(ConfigModule.CRYOSTAT_AGENT_APP_JMX_PORT) int jmxPort,
@Named(ConfigModule.CRYOSTAT_AGENT_REGISTRATION_RETRY_MS) int registrationRetryMs,
@Named(ConfigModule.CRYOSTAT_AGENT_REGISTRATION_CHECK_MS) int registrationCheckMs,
@Named(ConfigModule.CRYOSTAT_AGENT_REGISTRATION_JMX_IGNORE)
boolean registrationJmxIgnore,
@Named(ConfigModule.CRYOSTAT_AGENT_REGISTRATION_JMX_USE_CALLBACK_HOST)
boolean registrationJmxUseCallbackHost) {
Logger log = LoggerFactory.getLogger(Registration.class);
return new Registration(
Executors.newSingleThreadScheduledExecutor(
r -> {
Thread t = new Thread(r);
t.setDaemon(true);
t.setName("cryostat-agent-registration");
t.setUncaughtExceptionHandler(
(thread, err) ->
log.error(
"[{}] Uncaught exception: {}",
thread.getName(),
ExceptionUtils.getStackTrace(err)));
return t;
}),
cryostat,
callback,
webServer,
instanceId,
jvmId,
appName,
realm,
hostname,
jmxPort,
registrationRetryMs,
registrationCheckMs,
registrationJmxIgnore,
registrationJmxUseCallbackHost);
}
@Provides
@Singleton
public static FlightRecorderHelper provideFlightRecorderHelper() {
return new FlightRecorderHelper();
}
@Provides
@Singleton
@Named(JVM_ID)
public static String provideJvmId() {
try {
return JvmIdentifier.getLocal().getHash();
} catch (IDException e) {
throw new RuntimeException(e);
}
}
}