-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
ElasticsearchContainerTest.java
491 lines (429 loc) · 20.9 KB
/
ElasticsearchContainerTest.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
490
491
package org.testcontainers.elasticsearch;
import com.github.dockerjava.api.DockerClient;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Test;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.BindMode;
import org.testcontainers.containers.wait.strategy.HttpWaitStrategy;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.images.RemoteDockerImage;
import org.testcontainers.utility.DockerImageName;
import org.testcontainers.utility.MountableFile;
import java.io.IOException;
import javax.net.ssl.SSLHandshakeException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
public class ElasticsearchContainerTest {
/**
* Elasticsearch version which should be used for the Tests
*/
private static final String ELASTICSEARCH_VERSION = "7.9.2";
private static final DockerImageName ELASTICSEARCH_IMAGE = DockerImageName
.parse("docker.elastic.co/elasticsearch/elasticsearch")
.withTag(ELASTICSEARCH_VERSION);
/**
* Elasticsearch default username, when secured
*/
private static final String ELASTICSEARCH_USERNAME = "elastic";
/**
* From 6.8, we can optionally activate security with a default password.
*/
private static final String ELASTICSEARCH_PASSWORD = "changeme";
private RestClient client = null;
private RestClient anonymousClient = null;
@After
public void stopRestClient() throws IOException {
if (client != null) {
client.close();
client = null;
}
if (anonymousClient != null) {
anonymousClient.close();
anonymousClient = null;
}
}
@SuppressWarnings("deprecation") // Using deprecated constructor for verification of backwards compatibility
@Test
@Deprecated // We will remove this test in the future
public void elasticsearchDeprecatedCtorTest() throws IOException {
// Create the elasticsearch container.
try (
ElasticsearchContainer container = new ElasticsearchContainer().withEnv("foo", "bar") // dummy env for compiler checking correct generics usage
) {
// Start the container. This step might take some time...
container.start();
// Do whatever you want with the rest client ...
Response response = getClient(container).performRequest(new Request("GET", "/"));
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(EntityUtils.toString(response.getEntity())).contains(ELASTICSEARCH_VERSION);
// The default image is running with the features under Elastic License
response = getClient(container).performRequest(new Request("GET", "/_xpack/"));
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
// For now we test that we have the monitoring feature available
assertThat(EntityUtils.toString(response.getEntity())).contains("monitoring");
}
}
@Test
public void elasticsearchDefaultTest() throws IOException {
// Create the elasticsearch container.
try (
ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE).withEnv("foo", "bar") // dummy env for compiler checking correct generics usage
) {
// Start the container. This step might take some time...
container.start();
// Do whatever you want with the rest client ...
Response response = getClient(container).performRequest(new Request("GET", "/"));
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(EntityUtils.toString(response.getEntity())).contains(ELASTICSEARCH_VERSION);
// The default image is running with the features under Elastic License
response = getClient(container).performRequest(new Request("GET", "/_xpack/"));
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
// For now we test that we have the monitoring feature available
assertThat(EntityUtils.toString(response.getEntity())).contains("monitoring");
}
}
@Test
public void elasticsearchSecuredTest() throws IOException {
try (
ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)
.withPassword(ELASTICSEARCH_PASSWORD)
) {
container.start();
// The cluster should be secured so it must fail when we try to access / without credentials
assertThat(catchThrowable(() -> getAnonymousClient(container).performRequest(new Request("GET", "/"))))
.as("We should not be able to access / URI with an anonymous client.")
.isInstanceOf(ResponseException.class);
// But it should work when we try to access / with the proper login and password
Response response = getClient(container).performRequest(new Request("GET", "/"));
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(EntityUtils.toString(response.getEntity())).contains(ELASTICSEARCH_VERSION);
}
}
@Test
public void elasticsearchVersion() throws IOException {
try (ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)) {
container.start();
Response response = getClient(container).performRequest(new Request("GET", "/"));
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
String responseAsString = EntityUtils.toString(response.getEntity());
assertThat(responseAsString).contains(ELASTICSEARCH_VERSION);
}
}
@Test
public void elasticsearchVersion83() throws IOException {
try (
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.3.0"
)
) {
container.start();
Response response = getClient(container).performRequest(new Request("GET", "/"));
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(EntityUtils.toString(response.getEntity())).contains("8.3.0");
}
}
@Test
public void elasticsearchOssImage() throws IOException {
try (
// ossContainer {
ElasticsearchContainer container = new ElasticsearchContainer(
DockerImageName
.parse("docker.elastic.co/elasticsearch/elasticsearch-oss")
.withTag(ELASTICSEARCH_VERSION)
)
// }
) {
container.start();
Response response = getClient(container).performRequest(new Request("GET", "/"));
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
// The OSS image does not have any feature under Elastic License
assertThat(catchThrowable(() -> getClient(container).performRequest(new Request("GET", "/_xpack/"))))
.as("We should not have /_xpack endpoint with an OSS License")
.isInstanceOf(ResponseException.class);
}
}
@Test
public void restClientClusterHealth() throws IOException {
// httpClientContainer {
// Create the elasticsearch container.
try (ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)) {
// Start the container. This step might take some time...
container.start();
// Do whatever you want with the rest client ...
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD)
);
client =
RestClient
.builder(HttpHost.create(container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> {
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
})
.build();
Response response = client.performRequest(new Request("GET", "/_cluster/health"));
// }}
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(EntityUtils.toString(response.getEntity())).contains("cluster_name");
// httpClientContainer {{
}
// }
}
@Test
public void restClientSecuredClusterHealth() throws IOException {
// httpClientSecuredContainer {
// Create the elasticsearch container.
try (
ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)
// With a password
.withPassword(ELASTICSEARCH_PASSWORD)
) {
// Start the container. This step might take some time...
container.start();
// Create the secured client.
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD)
);
client =
RestClient
.builder(HttpHost.create(container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> {
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
})
.build();
Response response = client.performRequest(new Request("GET", "/_cluster/health"));
// }}
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(EntityUtils.toString(response.getEntity())).contains("cluster_name");
// httpClientSecuredContainer {{
}
// }
}
@SuppressWarnings("deprecation") // The TransportClient will be removed in Elasticsearch 8.
@Test
public void transportClientClusterHealth() {
// transportClientContainer {
// Create the elasticsearch container.
try (ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)) {
// Start the container. This step might take some time...
container.start();
// Do whatever you want with the transport client
TransportAddress transportAddress = new TransportAddress(container.getTcpHost());
String expectedClusterName = "docker-cluster";
Settings settings = Settings.builder().put("cluster.name", expectedClusterName).build();
try (
TransportClient transportClient = new PreBuiltTransportClient(settings)
.addTransportAddress(transportAddress)
) {
ClusterHealthResponse healths = transportClient.admin().cluster().prepareHealth().get();
String clusterName = healths.getClusterName();
// }}}
assertThat(clusterName).isEqualTo(expectedClusterName);
// transportClientContainer {{{
}
}
// }
}
@Test
public void incompatibleSettingsTest() {
// The OSS image can not use security feature
assertThat(
catchThrowable(() -> {
new ElasticsearchContainer(
DockerImageName
.parse("docker.elastic.co/elasticsearch/elasticsearch-oss")
.withTag(ELASTICSEARCH_VERSION)
)
.withPassword("foo");
})
)
.as("We should not be able to activate security with an OSS License")
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void testElasticsearch8SecureByDefault() throws Exception {
try (
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.1.2"
)
) {
// Start the container. This step might take some time...
container.start();
Response response = getClusterHealth(container);
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(EntityUtils.toString(response.getEntity())).contains("cluster_name");
}
}
@Test
public void testElasticsearch8SecureByDefaultCustomCaCertFails() throws Exception {
final MountableFile mountableFile = MountableFile.forClasspathResource("http_ca.crt");
String caPath = "/tmp/http_ca.crt";
try (
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.1.2"
)
.withCopyToContainer(mountableFile, caPath)
.withCertPath(caPath)
) {
container.start();
// this is expected, as a different cert is used for creating the SSL context
assertThat(catchThrowable(() -> getClusterHealth(container)))
.as(
"PKIX path validation failed: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors"
)
.isInstanceOf(SSLHandshakeException.class);
}
}
@Test
public void testElasticsearch8SecureByDefaultHttpWaitStrategy() throws Exception {
final HttpWaitStrategy httpsWaitStrategy = Wait
.forHttps("/")
.forPort(9200)
.forStatusCode(200)
.withBasicCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD)
// trusting self-signed certificate
.allowInsecure();
try (
ElasticsearchContainer container = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.1.2"
)
.waitingFor(httpsWaitStrategy)
) {
// Start the container. This step might take some time...
container.start();
Response response = getClusterHealth(container);
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(EntityUtils.toString(response.getEntity())).contains("cluster_name");
}
}
@Test
public void testElasticsearch8SecureByDefaultFailsSilentlyOnLatestImages() throws Exception {
// this test exists for custom images by users that use the `latest` tag
// even though the version might be older than version 8
// this tags an old 7.x version as :latest
tagImage("docker.elastic.co/elasticsearch/elasticsearch:7.9.2", "elasticsearch-tc-older-release", "latest");
DockerImageName image = DockerImageName
.parse("elasticsearch-tc-older-release:latest")
.asCompatibleSubstituteFor("docker.elastic.co/elasticsearch/elasticsearch");
try (ElasticsearchContainer container = new ElasticsearchContainer(image)) {
container.start();
Response response = getClient(container).performRequest(new Request("GET", "/_cluster/health"));
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(EntityUtils.toString(response.getEntity())).contains("cluster_name");
}
}
@Test
public void testElasticsearchDefaultMaxHeapSize() throws Exception {
long defaultHeapSize = 2147483648L;
try (ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)) {
container.start();
assertElasticsearchContainerHasHeapSize(container, defaultHeapSize);
}
}
@Test
public void testElasticsearchCustomMaxHeapSizeInEnvironmentVariable() throws Exception {
long customHeapSize = 1574961152;
try (
ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)
.withEnv("ES_JAVA_OPTS", String.format("-Xms%d -Xmx%d", customHeapSize, customHeapSize))
) {
container.start();
assertElasticsearchContainerHasHeapSize(container, customHeapSize);
}
}
@Test
public void testElasticsearchCustomMaxHeapSizeInJvmOptionsFile() throws Exception {
long customHeapSize = 1574961152;
try (
ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)
.withClasspathResourceMapping(
"test-custom-memory-jvm.options",
"/usr/share/elasticsearch/config/jvm.options.d/a-user-defined-jvm.options",
BindMode.READ_ONLY
);
) {
container.start();
assertElasticsearchContainerHasHeapSize(container, customHeapSize);
}
}
private void tagImage(String sourceImage, String targetImage, String targetTag) throws InterruptedException {
DockerClient dockerClient = DockerClientFactory.instance().client();
dockerClient
.tagImageCmd(new RemoteDockerImage(DockerImageName.parse(sourceImage)).get(), targetImage, targetTag)
.exec();
}
private Response getClusterHealth(ElasticsearchContainer container) throws IOException {
// Create the secured client.
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(
ELASTICSEARCH_USERNAME,
ElasticsearchContainer.ELASTICSEARCH_DEFAULT_PASSWORD
)
);
client =
RestClient
.builder(HttpHost.create("https://" + container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
httpClientBuilder.setSSLContext(container.createSslContextFromCa());
return httpClientBuilder;
})
.build();
return client.performRequest(new Request("GET", "/_cluster/health"));
}
private RestClient getClient(ElasticsearchContainer container) {
if (client == null) {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD)
);
String protocol = container.caCertAsBytes().isPresent() ? "https://" : "http://";
client =
RestClient
.builder(HttpHost.create(protocol + container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> {
if (container.caCertAsBytes().isPresent()) {
httpClientBuilder.setSSLContext(container.createSslContextFromCa());
}
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
})
.build();
}
return client;
}
private RestClient getAnonymousClient(ElasticsearchContainer container) {
if (anonymousClient == null) {
anonymousClient = RestClient.builder(HttpHost.create(container.getHttpHostAddress())).build();
}
return anonymousClient;
}
private void assertElasticsearchContainerHasHeapSize(ElasticsearchContainer container, long heapSizeInBytes)
throws Exception {
Response response = getClient(container).performRequest(new Request("GET", "/_nodes/_all/jvm"));
String responseBody = EntityUtils.toString(response.getEntity());
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(responseBody).contains("\"heap_init_in_bytes\":" + heapSizeInBytes);
assertThat(responseBody).contains("\"heap_max_in_bytes\":" + heapSizeInBytes);
}
}