-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
TestcontainersConfiguration.java
404 lines (342 loc) · 15.5 KB
/
TestcontainersConfiguration.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
package org.testcontainers.utility;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import lombok.Data;
import lombok.Getter;
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.testcontainers.UnstableAPI;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
/**
* Provides a mechanism for fetching configuration/default settings.
* <p>
* Configuration may be provided in:
* <ul>
* <li>A file in the user's home directory named <code>.testcontainers.properties</code></li>
* <li>A file in the classpath named <code>testcontainers.properties</code></li>
* <li>Environment variables</li>
* </ul>
* <p>
* Note that, if using environment variables, property names are in upper case separated by underscores, preceded by
* <code>TESTCONTAINERS_</code>.
*/
@Data
@Slf4j
public class TestcontainersConfiguration {
private static String PROPERTIES_FILE_NAME = "testcontainers.properties";
private static File USER_CONFIG_FILE = new File(System.getProperty("user.home"), "." + PROPERTIES_FILE_NAME);
private static final String AMBASSADOR_IMAGE = "richnorth/ambassador";
private static final String SOCAT_IMAGE = "alpine/socat";
private static final String VNC_RECORDER_IMAGE = "testcontainers/vnc-recorder";
private static final String COMPOSE_IMAGE = "docker/compose";
private static final String ALPINE_IMAGE = "alpine";
private static final String RYUK_IMAGE = "testcontainers/ryuk";
private static final String KAFKA_IMAGE = "confluentinc/cp-kafka";
private static final String PULSAR_IMAGE = "apachepulsar/pulsar";
private static final String LOCALSTACK_IMAGE = "localstack/localstack";
private static final String SSHD_IMAGE = "testcontainers/sshd";
private static final String ORACLE_IMAGE = "gvenzl/oracle-xe";
private static final ImmutableMap<DockerImageName, String> CONTAINER_MAPPING = ImmutableMap
.<DockerImageName, String>builder()
.put(DockerImageName.parse(AMBASSADOR_IMAGE), "ambassador.container.image")
.put(DockerImageName.parse(SOCAT_IMAGE), "socat.container.image")
.put(DockerImageName.parse(VNC_RECORDER_IMAGE), "vncrecorder.container.image")
.put(DockerImageName.parse(COMPOSE_IMAGE), "compose.container.image")
.put(DockerImageName.parse(ALPINE_IMAGE), "tinyimage.container.image")
.put(DockerImageName.parse(RYUK_IMAGE), "ryuk.container.image")
.put(DockerImageName.parse(KAFKA_IMAGE), "kafka.container.image")
.put(DockerImageName.parse(PULSAR_IMAGE), "pulsar.container.image")
.put(DockerImageName.parse(LOCALSTACK_IMAGE), "localstack.container.image")
.put(DockerImageName.parse(SSHD_IMAGE), "sshd.container.image")
.put(DockerImageName.parse(ORACLE_IMAGE), "oracle.container.image")
.build();
@Getter(lazy = true)
private static final TestcontainersConfiguration instance = loadConfiguration();
@SuppressWarnings({ "ConstantConditions", "unchecked", "rawtypes" })
@VisibleForTesting
static AtomicReference<TestcontainersConfiguration> getInstanceField() {
// Lazy Getter from Lombok changes the field's type to AtomicReference
return (AtomicReference) (Object) instance;
}
private final Properties userProperties;
private final Properties classpathProperties;
private final Map<String, String> environment;
TestcontainersConfiguration(
Properties userProperties,
Properties classpathProperties,
final Map<String, String> environment
) {
this.userProperties = userProperties;
this.classpathProperties = classpathProperties;
this.environment = environment;
}
@Deprecated
public String getAmbassadorContainerImage() {
return getImage(AMBASSADOR_IMAGE).asCanonicalNameString();
}
@Deprecated
public String getSocatContainerImage() {
return getImage(SOCAT_IMAGE).asCanonicalNameString();
}
@Deprecated
public String getVncRecordedContainerImage() {
return getImage(VNC_RECORDER_IMAGE).asCanonicalNameString();
}
@Deprecated
public String getDockerComposeContainerImage() {
return getImage(COMPOSE_IMAGE).asCanonicalNameString();
}
@Deprecated
public String getTinyImage() {
return getImage(ALPINE_IMAGE).asCanonicalNameString();
}
public boolean isRyukPrivileged() {
return Boolean.parseBoolean(getEnvVarOrProperty("ryuk.container.privileged", "false"));
}
@Deprecated
public String getRyukImage() {
return getImage(RYUK_IMAGE).asCanonicalNameString();
}
@Deprecated
public String getSSHdImage() {
return getImage(SSHD_IMAGE).asCanonicalNameString();
}
public Integer getRyukTimeout() {
return Integer.parseInt(getEnvVarOrProperty("ryuk.container.timeout", "30"));
}
@Deprecated
public String getKafkaImage() {
return getImage(KAFKA_IMAGE).asCanonicalNameString();
}
@Deprecated
public String getOracleImage() {
return getImage(ORACLE_IMAGE).asCanonicalNameString();
}
@Deprecated
public String getPulsarImage() {
return getImage(PULSAR_IMAGE).asCanonicalNameString();
}
@Deprecated
public String getLocalStackImage() {
return getImage(LOCALSTACK_IMAGE).asCanonicalNameString();
}
public boolean isDisableChecks() {
return Boolean.parseBoolean(getEnvVarOrUserProperty("checks.disable", "false"));
}
@UnstableAPI
public boolean environmentSupportsReuse() {
// specifically not supported as an environment variable or classpath property
return Boolean.parseBoolean(getEnvVarOrUserProperty("testcontainers.reuse.enable", "false"));
}
public String getDockerClientStrategyClassName() {
// getConfigurable won't apply the TESTCONTAINERS_ prefix when looking for env vars if DOCKER_ appears at the beginning.
// Because of this overlap, and the desire to not change this specific TESTCONTAINERS_DOCKER_CLIENT_STRATEGY setting,
// we special-case the logic here so that docker.client.strategy is used when reading properties files and
// TESTCONTAINERS_DOCKER_CLIENT_STRATEGY is used when searching environment variables.
// looks for TESTCONTAINERS_ prefixed env var only
String prefixedEnvVarStrategy = environment.get("TESTCONTAINERS_DOCKER_CLIENT_STRATEGY");
if (prefixedEnvVarStrategy != null) {
return prefixedEnvVarStrategy;
}
// looks for unprefixed env var or unprefixed property, or null if the strategy is not set at all
return getEnvVarOrUserProperty("docker.client.strategy", null);
}
public String getTransportType() {
return getEnvVarOrProperty("transport.type", "httpclient5");
}
public Integer getImagePullPauseTimeout() {
return Integer.parseInt(getEnvVarOrProperty("pull.pause.timeout", "30"));
}
public String getImageSubstitutorClassName() {
return getEnvVarOrProperty("image.substitutor", null);
}
public Integer getClientPingTimeout() {
return Integer.parseInt(getEnvVarOrProperty("client.ping.timeout", "10"));
}
@Nullable
@Contract("_, !null, _ -> !null")
private String getConfigurable(
@NotNull final String propertyName,
@Nullable final String defaultValue,
Properties... propertiesSources
) {
String envVarName = propertyName.replaceAll("\\.", "_").toUpperCase();
if (!envVarName.startsWith("TESTCONTAINERS_") && !envVarName.startsWith("DOCKER_")) {
envVarName = "TESTCONTAINERS_" + envVarName;
}
if (environment.containsKey(envVarName)) {
String value = environment.get(envVarName);
if (!value.isEmpty()) {
return value;
}
}
for (final Properties properties : propertiesSources) {
if (properties.get(propertyName) != null) {
return (String) properties.get(propertyName);
}
}
return defaultValue;
}
/**
* Gets a configured setting from an environment variable (if present) or a configuration file property otherwise.
* The configuration file will be the <code>.testcontainers.properties</code> file in the user's home directory or
* a <code>testcontainers.properties</code> found on the classpath.
* <p>
* Note that when searching environment variables, the prefix `TESTCONTAINERS_` will usually be applied to the
* property name, which will be converted to upper-case with underscore separators. This prefix will not be added
* if the property name begins `docker.`.
*
* @param propertyName name of configuration file property (dot-separated lower case)
* @return the found value, or null if not set
*/
@Contract("_, !null -> !null")
public String getEnvVarOrProperty(@NotNull final String propertyName, @Nullable final String defaultValue) {
return getConfigurable(propertyName, defaultValue, userProperties, classpathProperties);
}
/**
* Gets a configured setting from an environment variable (if present) or a configuration file property otherwise.
* The configuration file will be the <code>.testcontainers.properties</code> file in the user's home directory.
* <p>
* Note that when searching environment variables, the prefix `TESTCONTAINERS_` will usually be applied to the
* property name, which will be converted to upper-case with underscore separators. This prefix will not be added
* if the property name begins `docker.`.
*
* @param propertyName name of configuration file property (dot-separated lower case)
* @return the found value, or null if not set
*/
@Contract("_, !null -> !null")
public String getEnvVarOrUserProperty(@NotNull final String propertyName, @Nullable final String defaultValue) {
return getConfigurable(propertyName, defaultValue, userProperties);
}
/**
* Gets a configured setting from an environment variable.
* <p>
* Note that when searching environment variables, the prefix `TESTCONTAINERS_` will usually be applied to the
* property name, which will be converted to upper-case with underscore separators. This prefix will not be added
* if the property name begins `docker.`.
*
* @param propertyName name of configuration file property (dot-separated lower case)
* @return the found value, or null if not set
*/
@Contract("_, !null -> !null")
public String getUserProperty(@NotNull final String propertyName, @Nullable final String defaultValue) {
return getConfigurable(propertyName, defaultValue);
}
/**
* @return properties values available from user properties and classpath properties. Values set by environment
* variable are NOT included.
* @deprecated usages should be removed ASAP. See {@link TestcontainersConfiguration#getEnvVarOrProperty(String, String)},
* {@link TestcontainersConfiguration#getEnvVarOrUserProperty(String, String)} or {@link TestcontainersConfiguration#getUserProperty(String, String)}
* for suitable replacements.
*/
@Deprecated
public Properties getProperties() {
return Stream
.of(userProperties, classpathProperties)
.reduce(
new Properties(),
(a, b) -> {
a.putAll(b);
return a;
}
);
}
@Deprecated
public boolean updateGlobalConfig(@NonNull String prop, @NonNull String value) {
return updateUserConfig(prop, value);
}
@Synchronized
public boolean updateUserConfig(@NonNull String prop, @NonNull String value) {
try {
if (value.equals(userProperties.get(prop))) {
return false;
}
userProperties.setProperty(prop, value);
USER_CONFIG_FILE.createNewFile();
try (OutputStream outputStream = new FileOutputStream(USER_CONFIG_FILE)) {
userProperties.store(outputStream, "Modified by Testcontainers");
}
// Update internal state only if environment config was successfully updated
userProperties.setProperty(prop, value);
return true;
} catch (Exception e) {
log.debug("Can't store environment property {} in {}", prop, USER_CONFIG_FILE);
return false;
}
}
@SneakyThrows(MalformedURLException.class)
private static TestcontainersConfiguration loadConfiguration() {
return new TestcontainersConfiguration(
readProperties(USER_CONFIG_FILE.toURI().toURL()),
ClasspathScanner
.scanFor(PROPERTIES_FILE_NAME)
.map(TestcontainersConfiguration::readProperties)
.reduce(
new Properties(),
(a, b) -> {
// first-write-wins merging - URLs appearing first on the classpath alphabetically will take priority.
// Note that this means that file: URLs will always take priority over jar: URLs.
b.putAll(a);
return b;
}
),
System.getenv()
);
}
private static Properties readProperties(URL url) {
log.debug("Testcontainers configuration overrides will be loaded from {}", url);
Properties properties = new Properties();
try (InputStream inputStream = url.openStream()) {
properties.load(inputStream);
} catch (FileNotFoundException e) {
log.warn(
"Attempted to read Testcontainers configuration file at {} but the file was not found. Exception message: {}",
url,
ExceptionUtils.getRootCauseMessage(e)
);
} catch (IOException e) {
log.warn(
"Attempted to read Testcontainers configuration file at {} but could it not be loaded. Exception message: {}",
url,
ExceptionUtils.getRootCauseMessage(e)
);
}
return properties;
}
private DockerImageName getImage(final String defaultValue) {
return getConfiguredSubstituteImage(DockerImageName.parse(defaultValue));
}
DockerImageName getConfiguredSubstituteImage(DockerImageName original) {
for (final Map.Entry<DockerImageName, String> entry : CONTAINER_MAPPING.entrySet()) {
if (original.isCompatibleWith(entry.getKey())) {
return Optional
.ofNullable(entry.getValue())
.map(propertyName -> getEnvVarOrProperty(propertyName, null))
.map(String::valueOf)
.map(String::trim)
.map(DockerImageName::parse)
.orElse(original)
.asCompatibleSubstituteFor(original);
}
}
return original;
}
}