forked from testcontainers/testcontainers-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ElasticsearchContainer.java
169 lines (148 loc) · 7.01 KB
/
ElasticsearchContainer.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
package org.testcontainers.elasticsearch;
import com.github.dockerjava.api.command.InspectContainerResponse;
import org.apache.commons.io.IOUtils;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy;
import org.testcontainers.utility.Base58;
import org.testcontainers.utility.ComparableVersion;
import org.testcontainers.utility.DockerImageName;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.ByteArrayInputStream;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Optional;
/**
* Represents an elasticsearch docker instance which exposes by default port 9200 and 9300 (transport.tcp.port)
* The docker image is by default fetched from docker.elastic.co/elasticsearch/elasticsearch
*/
public class ElasticsearchContainer extends GenericContainer<ElasticsearchContainer> {
/**
* Elasticsearch Default Password for Elasticsearch >= 8
*/
public static final String ELASTICSEARCH_DEFAULT_PASSWORD = "changeme";
/**
* Elasticsearch Default HTTP port
*/
private static final int ELASTICSEARCH_DEFAULT_PORT = 9200;
/**
* Elasticsearch Default Transport port
* The TransportClient will be removed in Elasticsearch 8. No need to expose this port anymore in the future.
*/
@Deprecated
private static final int ELASTICSEARCH_DEFAULT_TCP_PORT = 9300;
/**
* Elasticsearch Docker base image
*/
private static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("docker.elastic.co/elasticsearch/elasticsearch");
private static final DockerImageName DEFAULT_OSS_IMAGE_NAME = DockerImageName.parse("docker.elastic.co/elasticsearch/elasticsearch-oss");
/**
* Elasticsearch Default version
*/
@Deprecated
protected static final String DEFAULT_TAG = "7.9.2";
private final boolean isOss;
private final boolean isAtLeastMajorVersion8;
private Optional<byte[]> caCertAsBytes = Optional.empty();
/**
* @deprecated use {@link ElasticsearchContainer(DockerImageName)} instead
*/
@Deprecated
public ElasticsearchContainer() {
this(DEFAULT_IMAGE_NAME.withTag(DEFAULT_TAG));
}
/**
* Create an Elasticsearch Container by passing the full docker image name
* @param dockerImageName Full docker image name as a {@link String}, like: docker.elastic.co/elasticsearch/elasticsearch:7.9.2
*/
public ElasticsearchContainer(String dockerImageName) {
this(DockerImageName.parse(dockerImageName));
}
/**
* Create an Elasticsearch Container by passing the full docker image name
* @param dockerImageName Full docker image name as a {@link DockerImageName}, like: DockerImageName.parse("docker.elastic.co/elasticsearch/elasticsearch:7.9.2")
*/
public ElasticsearchContainer(final DockerImageName dockerImageName) {
super(dockerImageName);
dockerImageName.assertCompatibleWith(DEFAULT_IMAGE_NAME, DEFAULT_OSS_IMAGE_NAME);
this.isOss = dockerImageName.isCompatibleWith(DEFAULT_OSS_IMAGE_NAME);
logger().info("Starting an elasticsearch container using [{}]", dockerImageName);
withNetworkAliases("elasticsearch-" + Base58.randomString(6));
withEnv("discovery.type", "single-node");
addExposedPorts(ELASTICSEARCH_DEFAULT_PORT, ELASTICSEARCH_DEFAULT_TCP_PORT);
this.isAtLeastMajorVersion8 = new ComparableVersion(dockerImageName.getVersionPart()).isGreaterThanOrEqualTo("8.0.0");
// regex that
// matches 8.0 JSON logging with no whitespace between message field and content
// matches 7.x JSON logging with whitespace between message field and content
// matches 6.x text logging with node name in brackets and just a 'started' message till the end of the line
String regex = ".*(\"message\":\\s?\"started\".*|] started\n$)";
setWaitStrategy(new LogMessageWaitStrategy().withRegEx(regex));
if (isAtLeastMajorVersion8) {
withPassword(ELASTICSEARCH_DEFAULT_PASSWORD);
}
}
@Override
protected void containerIsStarted(InspectContainerResponse containerInfo) {
if (isAtLeastMajorVersion8) {
byte[] bytes = copyFileFromContainer("/usr/share/elasticsearch/config/certs/http_ca.crt", IOUtils::toByteArray);
if (bytes.length > 0) {
this.caCertAsBytes = Optional.of(bytes);
}
}
}
/**
* If this is running above Elasticsearch 8, the probably self signed CA cert will be extracted
*
* @return byte array optional containing the CA cert extracted from the docker container
*/
public Optional<byte[]> caCertAsBytes() {
return caCertAsBytes;
}
/**
* A SSL context based on the self signed CA, so that using this SSL Context allows to connect to the Elasticsearch service
* @return a customized SSL Context
*/
public SSLContext createSslContextFromCa() {
try {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
Certificate trustedCa = factory.generateCertificate(new ByteArrayInputStream(caCertAsBytes.get()));
KeyStore trustStore = KeyStore.getInstance("pkcs12");
trustStore.load(null, null);
trustStore.setCertificateEntry("ca", trustedCa);
final SSLContext sslContext = SSLContext.getInstance("TLSv1.3");
TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init(trustStore);
sslContext.init(null, tmfactory.getTrustManagers(), null);
return sslContext;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Define the Elasticsearch password to set. It enables security behind the scene for major version below 8.0.0.
* It's not possible to use security with the oss image.
* @param password Password to set
* @return this
*/
public ElasticsearchContainer withPassword(String password) {
if (isOss) {
throw new IllegalArgumentException("You can not activate security on Elastic OSS Image. " +
"Please switch to the default distribution");
}
withEnv("ELASTIC_PASSWORD", password);
if (!isAtLeastMajorVersion8) {
// major version 8 is secure by default and does not need this to enable authentication
withEnv("xpack.security.enabled", "true");
}
return this;
}
public String getHttpHostAddress() {
return getHost() + ":" + getMappedPort(ELASTICSEARCH_DEFAULT_PORT);
}
@Deprecated // The TransportClient will be removed in Elasticsearch 8. No need to expose this port anymore in the future.
public InetSocketAddress getTcpHost() {
return new InetSocketAddress(getHost(), getMappedPort(ELASTICSEARCH_DEFAULT_TCP_PORT));
}
}