/
GenericContainer.java
1459 lines (1241 loc) · 49.5 KB
/
GenericContainer.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.testcontainers.containers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Link;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.api.model.Ports;
import com.github.dockerjava.api.model.Volume;
import com.github.dockerjava.api.model.VolumesFrom;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.Hashing;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NonNull;
import lombok.Setter;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.rnorth.ducttape.ratelimits.RateLimiter;
import org.rnorth.ducttape.ratelimits.RateLimiterBuilder;
import org.rnorth.ducttape.unreliables.Unreliables;
import org.slf4j.Logger;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.UnstableAPI;
import org.testcontainers.containers.output.OutputFrame;
import org.testcontainers.containers.startupcheck.IsRunningStartupCheckStrategy;
import org.testcontainers.containers.startupcheck.MinimumDurationRunningStartupCheckStrategy;
import org.testcontainers.containers.startupcheck.StartupCheckStrategy;
import org.testcontainers.containers.traits.LinkableContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.containers.wait.strategy.WaitStrategy;
import org.testcontainers.containers.wait.strategy.WaitStrategyTarget;
import org.testcontainers.images.ImagePullPolicy;
import org.testcontainers.images.RemoteDockerImage;
import org.testcontainers.lifecycle.Startable;
import org.testcontainers.lifecycle.Startables;
import org.testcontainers.lifecycle.TestDescription;
import org.testcontainers.lifecycle.TestLifecycleAware;
import org.testcontainers.utility.Base58;
import org.testcontainers.utility.DockerImageName;
import org.testcontainers.utility.DockerLoggerFactory;
import org.testcontainers.utility.DockerMachineClient;
import org.testcontainers.utility.DynamicPollInterval;
import org.testcontainers.utility.MountableFile;
import org.testcontainers.utility.PathUtils;
import org.testcontainers.utility.ResourceReaper;
import org.testcontainers.utility.TestcontainersConfiguration;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
import static com.google.common.collect.Lists.newArrayList;
import static org.awaitility.Awaitility.await;
import static org.testcontainers.utility.CommandLine.runShellCommand;
/**
* Base class for that allows a container to be launched and controlled.
*/
@Data
public class GenericContainer<SELF extends GenericContainer<SELF>>
extends FailureDetectingExternalResource
implements Container<SELF>, AutoCloseable, WaitStrategyTarget, Startable {
private static final Charset UTF8 = Charset.forName("UTF-8");
public static final int CONTAINER_RUNNING_TIMEOUT_SEC = 30;
public static final String INTERNAL_HOST_HOSTNAME = "host.testcontainers.internal";
static final String HASH_LABEL = "org.testcontainers.hash";
static final String COPIED_FILES_HASH_LABEL = "org.testcontainers.copied_files.hash";
/*
* Default settings
*/
@NonNull
private LinkedHashSet<Integer> exposedPorts = new LinkedHashSet<>();
@NonNull
private List<String> portBindings = new ArrayList<>();
@NonNull
private List<String> extraHosts = new ArrayList<>();
@NonNull
private String networkMode;
@Nullable
private Network network;
@NonNull
private List<String> networkAliases = new ArrayList<>(Arrays.asList(
"tc-" + Base58.randomString(8)
));
@NonNull
private RemoteDockerImage image;
@NonNull
private Map<String, String> env = new HashMap<>();
@NonNull
private Map<String, String> labels = new HashMap<>();
@NonNull
private String[] commandParts = new String[0];
@NonNull
private List<Bind> binds = new ArrayList<>();
private boolean privilegedMode;
@NonNull
private List<VolumesFrom> volumesFroms = new ArrayList<>();
/**
* @deprecated Links are deprecated (see <a href="https://github.com/testcontainers/testcontainers-java/issues/465">#465</a>). Please use {@link Network} features instead.
*/
@NonNull
@Deprecated
private Map<String, LinkableContainer> linkedContainers = new HashMap<>();
private StartupCheckStrategy startupCheckStrategy = new IsRunningStartupCheckStrategy();
private int startupAttempts = 1;
@Nullable
private String workingDirectory = null;
/**
* The shared memory size to use when starting the container.
* This value is in bytes.
*/
@Nullable
private Long shmSize;
// Maintain order in which entries are added, as earlier target location may be a prefix of a later location.
private Map<MountableFile, String> copyToFileContainerPathMap = new LinkedHashMap<>();
protected final Set<Startable> dependencies = new HashSet<>();
/**
* Unique instance of DockerClient for use by this container object.
* We use {@link DockerClientFactory#lazyClient()} here to avoid eager client creation
*/
@Setter(AccessLevel.NONE)
protected DockerClient dockerClient = DockerClientFactory.lazyClient();
/**
* Set during container startup
*
*/
@Setter(AccessLevel.NONE)
@VisibleForTesting
String containerId;
@Setter(AccessLevel.NONE)
private InspectContainerResponse containerInfo;
/**
* The approach to determine if the container is ready.
*/
@NonNull
protected org.testcontainers.containers.wait.strategy.WaitStrategy waitStrategy = Wait.defaultWaitStrategy();
private List<Consumer<OutputFrame>> logConsumers = new ArrayList<>();
private final Set<Consumer<CreateContainerCmd>> createContainerCmdModifiers = new LinkedHashSet<>();
private static final Set<String> AVAILABLE_IMAGE_NAME_CACHE = new HashSet<>();
private static final RateLimiter DOCKER_CLIENT_RATE_LIMITER = RateLimiterBuilder
.newBuilder()
.withRate(1, TimeUnit.SECONDS)
.withConstantThroughput()
.build();
@Nullable
private Map<String, String> tmpFsMapping;
@Setter(AccessLevel.NONE)
private boolean shouldBeReused = false;
private boolean hostAccessible = false;
public GenericContainer(@NonNull final DockerImageName dockerImageName) {
this.image = new RemoteDockerImage(dockerImageName);
}
public GenericContainer(@NonNull final RemoteDockerImage image) {
this.image = image;
}
/**
* @deprecated use {@link GenericContainer(DockerImageName)} instead
*/
@Deprecated
public GenericContainer() {
this(TestcontainersConfiguration.getInstance().getTinyImage());
}
public GenericContainer(@NonNull final String dockerImageName) {
this.setDockerImageName(dockerImageName);
}
public GenericContainer(@NonNull final Future<String> image) {
setImage(image);
}
public void setImage(Future<String> image) {
this.image = new RemoteDockerImage(image);
}
@Override
public List<Integer> getExposedPorts() {
return new ArrayList<>(exposedPorts);
}
@Override
public void setExposedPorts(List<Integer> exposedPorts) {
this.exposedPorts = new LinkedHashSet<>(exposedPorts);
}
/**
* @see #dependsOn(Iterable)
*/
public SELF dependsOn(Startable... startables) {
Collections.addAll(dependencies, startables);
return self();
}
/**
* @see #dependsOn(Iterable)
*/
public SELF dependsOn(List<? extends Startable> startables) {
return this.dependsOn((Iterable<? extends Startable>) startables);
}
/**
* Delays this container's creation and start until provided {@link Startable}s start first.
* Note that the circular dependencies are not supported.
*
* @param startables a list of {@link Startable} to depend on
* @see Startables#deepStart(Iterable)
*/
public SELF dependsOn(Iterable<? extends Startable> startables) {
startables.forEach(dependencies::add);
return self();
}
public String getContainerId() {
return containerId;
}
/**
* Starts the container using docker, pulling an image if necessary.
*/
@Override
@SneakyThrows({InterruptedException.class, ExecutionException.class})
public void start() {
if (containerId != null) {
return;
}
Startables.deepStart(dependencies).get();
// trigger LazyDockerClient's resolve so that we fail fast here and not in getDockerImageName()
dockerClient.authConfig();
doStart();
}
protected void doStart() {
try {
configure();
Instant startedAt = Instant.now();
logger().debug("Starting container: {}", getDockerImageName());
AtomicInteger attempt = new AtomicInteger(0);
Unreliables.retryUntilSuccess(startupAttempts, () -> {
logger().debug("Trying to start container: {} (attempt {}/{})", getDockerImageName(), attempt.incrementAndGet(), startupAttempts);
tryStart(startedAt);
return true;
});
} catch (Exception e) {
throw new ContainerLaunchException("Container startup failed", e);
}
}
@UnstableAPI
@SneakyThrows
protected boolean canBeReused() {
for (Class<?> type = getClass(); type != GenericContainer.class; type = type.getSuperclass()) {
try {
Method method = type.getDeclaredMethod("containerIsCreated", String.class);
if (method.getDeclaringClass() != GenericContainer.class) {
logger().warn("{} can't be reused because it overrides {}", getClass(), method.getName());
return false;
}
} catch (NoSuchMethodException e) {
// ignore
}
}
return true;
}
private void tryStart(Instant startedAt) {
try {
String dockerImageName = getDockerImageName();
logger().debug("Starting container: {}", dockerImageName);
logger().info("Creating container for image: {}", dockerImageName);
CreateContainerCmd createCommand = dockerClient.createContainerCmd(dockerImageName);
applyConfiguration(createCommand);
createCommand.getLabels().putAll(DockerClientFactory.DEFAULT_LABELS);
boolean reused = false;
final boolean reusable;
if (shouldBeReused) {
if (!canBeReused()) {
throw new IllegalStateException("This container does not support reuse");
}
if (TestcontainersConfiguration.getInstance().environmentSupportsReuse()) {
createCommand.getLabels().put(
COPIED_FILES_HASH_LABEL,
Long.toHexString(hashCopiedFiles().getValue())
);
String hash = hash(createCommand);
containerId = findContainerForReuse(hash).orElse(null);
if (containerId != null) {
logger().info("Reusing container with ID: {} and hash: {}", containerId, hash);
reused = true;
} else {
logger().debug("Can't find a reusable running container with hash: {}", hash);
createCommand.getLabels().put(HASH_LABEL, hash);
}
reusable = true;
} else {
logger().warn(
"" +
"Reuse was requested but the environment does not support the reuse of containers\n" +
"To enable reuse of containers, you must set 'testcontainers.reuse.enable=true' in a file located at {}",
Paths.get(System.getProperty("user.home"), ".testcontainers.properties")
);
reusable = false;
}
} else {
reusable = false;
}
if (!reusable) {
//noinspection deprecation
createCommand.getLabels().putAll(ResourceReaper.instance().getLabels());
}
if (!reused) {
containerId = createCommand.exec().getId();
// TODO use single "copy" invocation (and calculate an hash of the resulting tar archive)
copyToFileContainerPathMap.forEach(this::copyFileToContainer);
}
connectToPortForwardingNetwork(createCommand.getNetworkMode());
if (!reused) {
containerIsCreated(containerId);
logger().info("Container {} is starting: {}", dockerImageName, containerId);
dockerClient.startContainerCmd(containerId).exec();
} else {
logger().info("Reusing existing container ({}) and not creating a new one", containerId);
}
// For all registered output consumers, start following as close to container startup as possible
this.logConsumers.forEach(this::followOutput);
// Wait until inspect container returns the mapped ports
containerInfo = await()
.atMost(5, TimeUnit.SECONDS)
.pollInterval(DynamicPollInterval.ofMillis(50))
.pollInSameThread()
.until(
() -> dockerClient.inspectContainerCmd(containerId).exec(),
inspectContainerResponse -> {
Set<Integer> exposedAndMappedPorts = inspectContainerResponse
.getNetworkSettings()
.getPorts()
.getBindings()
.entrySet()
.stream()
.filter(it -> Objects.nonNull(it.getValue())) // filter out exposed but not yet mapped
.map(Entry::getKey)
.map(ExposedPort::getPort)
.collect(Collectors.toSet());
return exposedAndMappedPorts.containsAll(exposedPorts);
}
);
// Tell subclasses that we're starting
containerIsStarting(containerInfo, reused);
// Wait until the container has reached the desired running state
if (!this.startupCheckStrategy.waitUntilStartupSuccessful(dockerClient, containerId)) {
// Bail out, don't wait for the port to start listening.
// (Exception thrown here will be caught below and wrapped)
throw new IllegalStateException("Container did not start correctly.");
}
// Wait until the process within the container has become ready for use (e.g. listening on network, log message emitted, etc).
try {
waitUntilContainerStarted();
} catch (Exception e) {
logger().debug("Wait strategy threw an exception", e);
InspectContainerResponse inspectContainerResponse = null;
try {
inspectContainerResponse = dockerClient.inspectContainerCmd(containerId).exec();
} catch (NotFoundException notFoundException) {
logger().debug("Container {} not found", containerId, notFoundException);
}
if (inspectContainerResponse == null) {
throw new IllegalStateException("Container is removed");
}
InspectContainerResponse.ContainerState state = inspectContainerResponse.getState();
if (Boolean.TRUE.equals(state.getDead())) {
throw new IllegalStateException("Container is dead");
}
if (Boolean.TRUE.equals(state.getOOMKilled())) {
throw new IllegalStateException("Container crashed with out-of-memory (OOMKilled)");
}
String error = state.getError();
if (!StringUtils.isBlank(error)) {
throw new IllegalStateException("Container crashed: " + error);
}
if (!Boolean.TRUE.equals(state.getRunning())) {
throw new IllegalStateException("Container exited with code " + state.getExitCode());
}
throw e;
}
logger().info("Container {} started in {}", dockerImageName, Duration.between(startedAt, Instant.now()));
containerIsStarted(containerInfo, reused);
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException && e.getCause() instanceof Exception) {
e = (Exception) e.getCause();
}
if (e instanceof InvocationTargetException && e.getCause() instanceof Exception) {
e = (Exception) e.getCause();
}
logger().error("Could not start container", e);
if (containerId != null) {
// Log output if startup failed, either due to a container failure or exception (including timeout)
final String containerLogs = getLogs();
if (containerLogs.length() > 0) {
logger().error("Log output from the failed container:\n{}", getLogs());
} else {
logger().error("There are no stdout/stderr logs available for the failed container");
}
}
throw new ContainerLaunchException("Could not create/start container", e);
}
}
@VisibleForTesting
Checksum hashCopiedFiles() {
Checksum checksum = new Adler32();
copyToFileContainerPathMap.entrySet().stream().sorted(Entry.comparingByValue()).forEach(entry -> {
byte[] pathBytes = entry.getValue().getBytes();
// Add path to the hash
checksum.update(pathBytes, 0, pathBytes.length);
File file = new File(entry.getKey().getResolvedPath());
checksumFile(file, checksum);
});
return checksum;
}
@VisibleForTesting
@SneakyThrows(IOException.class)
void checksumFile(File file, Checksum checksum) {
Path path = file.toPath();
checksum.update(MountableFile.getUnixFileMode(path));
if (file.isDirectory()) {
try (Stream<Path> stream = Files.walk(path)) {
stream.filter(it -> it != path).forEach(it -> {
checksumFile(it.toFile(), checksum);
});
}
} else {
FileUtils.checksum(file, checksum);
}
}
@UnstableAPI
@SneakyThrows(JsonProcessingException.class)
final String hash(CreateContainerCmd createCommand) {
DefaultDockerClientConfig dockerClientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder().build();
byte[] commandJson = dockerClientConfig.getObjectMapper()
.copy()
.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)
.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)
.writeValueAsBytes(createCommand);
// TODO add Testcontainers' version to the hash
return Hashing.sha1().hashBytes(commandJson).toString();
}
@VisibleForTesting
Optional<String> findContainerForReuse(String hash) {
// TODO locking
return dockerClient.listContainersCmd()
.withLabelFilter(ImmutableMap.of(HASH_LABEL, hash))
.withLimit(1)
.withStatusFilter(Arrays.asList("running"))
.exec()
.stream()
.findAny()
.map(it -> it.getId());
}
/**
* Set any custom settings for the create command such as shared memory size.
*/
private HostConfig buildHostConfig() {
HostConfig config = new HostConfig();
if (shmSize != null) {
config.withShmSize(shmSize);
}
if (tmpFsMapping != null) {
config.withTmpFs(tmpFsMapping);
}
return config;
}
private void connectToPortForwardingNetwork(String networkMode) {
PortForwardingContainer.INSTANCE.getNetwork().map(ContainerNetwork::getNetworkID).ifPresent(networkId -> {
if (!Arrays.asList(networkId, "none", "host").contains(networkMode)) {
dockerClient.connectToNetworkCmd().withContainerId(containerId).withNetworkId(networkId).exec();
}
});
}
/**
* Stops the container.
*/
@Override
public void stop() {
if (containerId == null) {
return;
}
try {
String imageName;
try {
imageName = getDockerImageName();
} catch (Exception e) {
imageName = "<unknown>";
}
containerIsStopping(containerInfo);
ResourceReaper.instance().stopAndRemoveContainer(containerId, imageName);
containerIsStopped(containerInfo);
} finally {
containerId = null;
containerInfo = null;
}
}
/**
* Provide a logger that references the docker image name.
*
* @return a logger that references the docker image name
*/
protected Logger logger() {
return DockerLoggerFactory.getLogger(this.getDockerImageName());
}
/**
* Creates a directory on the local filesystem which will be mounted as a volume for the container.
*
* @param temporary is the volume directory temporary? If true, the directory will be deleted on JVM shutdown.
* @return path to the volume directory
*/
@Deprecated
protected Path createVolumeDirectory(boolean temporary) {
Path directory = new File(".tmp-volume-" + UUID.randomUUID()).toPath();
PathUtils.mkdirp(directory);
if (temporary) Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> {
PathUtils.recursiveDeleteDir(directory);
}));
return directory;
}
protected void configure() {
}
@SuppressWarnings({"EmptyMethod", "UnusedParameters"})
protected void containerIsCreated(String containerId) {
}
@SuppressWarnings({"EmptyMethod", "UnusedParameters"})
protected void containerIsStarting(InspectContainerResponse containerInfo) {
}
@SuppressWarnings({"EmptyMethod", "UnusedParameters"})
@UnstableAPI
protected void containerIsStarting(InspectContainerResponse containerInfo, boolean reused) {
containerIsStarting(containerInfo);
}
@SuppressWarnings({"EmptyMethod", "UnusedParameters"})
protected void containerIsStarted(InspectContainerResponse containerInfo) {
}
@SuppressWarnings({"EmptyMethod", "UnusedParameters"})
@UnstableAPI
protected void containerIsStarted(InspectContainerResponse containerInfo, boolean reused) {
containerIsStarted(containerInfo);
}
/**
* A hook that is executed before the container is stopped with {@link #stop()}.
* Warning! This hook won't be executed if the container is terminated during
* the JVM's shutdown hook or by Ryuk.
*/
@SuppressWarnings({"EmptyMethod", "UnusedParameters"})
protected void containerIsStopping(InspectContainerResponse containerInfo) {
}
/**
* A hook that is executed after the container is stopped with {@link #stop()}.
* Warning! This hook won't be executed if the container is terminated during
* the JVM's shutdown hook or by Ryuk.
*/
@SuppressWarnings({"EmptyMethod", "UnusedParameters"})
protected void containerIsStopped(InspectContainerResponse containerInfo) {
}
/**
* @return the port on which to check if the container is ready
* @deprecated see {@link GenericContainer#getLivenessCheckPorts()} for replacement
*/
@Deprecated
protected Integer getLivenessCheckPort() {
// legacy implementation for backwards compatibility
Iterator<Integer> exposedPortsIterator = exposedPorts.iterator();
if (exposedPortsIterator.hasNext()) {
return getMappedPort(exposedPortsIterator.next());
} else if (portBindings.size() > 0) {
return Integer.valueOf(PortBinding.parse(portBindings.get(0)).getBinding().getHostPortSpec());
} else {
return null;
}
}
/**
* @return the ports on which to check if the container is ready
* @deprecated use {@link #getLivenessCheckPortNumbers()} instead
*/
@NotNull
@NonNull
@Deprecated
protected Set<Integer> getLivenessCheckPorts() {
final Set<Integer> result = WaitStrategyTarget.super.getLivenessCheckPortNumbers();
// for backwards compatibility
if (this.getLivenessCheckPort() != null) {
result.add(this.getLivenessCheckPort());
}
return result;
}
@Override
public Set<Integer> getLivenessCheckPortNumbers() {
return this.getLivenessCheckPorts();
}
private void applyConfiguration(CreateContainerCmd createCommand) {
HostConfig hostConfig = buildHostConfig();
// PortBindings must contain:
// * all exposed ports with a randomized host port (equivalent to -p CONTAINER_PORT)
// * all exposed ports with a fixed host port (equivalent to -p HOST_PORT:CONTAINER_PORT)
Map<ExposedPort, PortBinding> allPortBindings = new HashMap<>();
// First collect all the randomized host ports from our 'exposedPorts' field
for (final Integer tcpPort : exposedPorts) {
ExposedPort exposedPort = ExposedPort.tcp(tcpPort);
allPortBindings.put(exposedPort, new PortBinding(Ports.Binding.empty(), exposedPort));
}
// Next collect all the fixed host ports from our 'portBindings' field, overwriting any randomized ports so that
// we don't create two bindings for the same container port.
for (final String portBinding : portBindings) {
PortBinding parsedBinding = PortBinding.parse(portBinding);
allPortBindings.put(parsedBinding.getExposedPort(), parsedBinding);
}
hostConfig.withPortBindings(new ArrayList<>(allPortBindings.values()));
// Next, ExposedPorts must be set up to publish all of the above ports, both randomized and fixed.
createCommand.withExposedPorts(new ArrayList<>(allPortBindings.keySet()));
createCommand.withHostConfig(hostConfig);
if (commandParts != null) {
createCommand.withCmd(commandParts);
}
String[] envArray = env.entrySet().stream()
.filter(it -> it.getValue() != null)
.map(it -> it.getKey() + "=" + it.getValue())
.toArray(String[]::new);
createCommand.withEnv(envArray);
boolean shouldCheckFileMountingSupport = binds.size() > 0 && !TestcontainersConfiguration.getInstance().isDisableChecks();
if (shouldCheckFileMountingSupport) {
if (!DockerClientFactory.instance().isFileMountingSupported()) {
logger().warn(
"Unable to mount a file from test host into a running container. " +
"This may be a misconfiguration or limitation of your Docker environment. " +
"Some features might not work."
);
}
}
Bind[] bindsArray = binds.stream()
.toArray(Bind[]::new);
createCommand.withBinds(bindsArray);
VolumesFrom[] volumesFromsArray = volumesFroms.stream()
.toArray(VolumesFrom[]::new);
createCommand.withVolumesFrom(volumesFromsArray);
Set<Link> allLinks = new HashSet<>();
Set<String> allLinkedContainerNetworks = new HashSet<>();
for (Entry<String, LinkableContainer> linkEntries : linkedContainers.entrySet()) {
String alias = linkEntries.getKey();
LinkableContainer linkableContainer = linkEntries.getValue();
Set<Link> links = findLinksFromThisContainer(alias, linkableContainer);
allLinks.addAll(links);
if (allLinks.size() == 0) {
throw new ContainerLaunchException("Aborting attempt to link to container " +
linkableContainer.getContainerName() +
" as it is not running");
}
Set<String> linkedContainerNetworks = findAllNetworksForLinkedContainers(linkableContainer);
allLinkedContainerNetworks.addAll(linkedContainerNetworks);
}
createCommand.withLinks(allLinks.toArray(new Link[allLinks.size()]));
allLinkedContainerNetworks.remove("bridge");
if (allLinkedContainerNetworks.size() > 1) {
logger().warn("Container needs to be on more than one custom network to link to other " +
"containers - this is not currently supported. Required networks are: {}",
allLinkedContainerNetworks);
}
Optional<String> networkForLinks = allLinkedContainerNetworks.stream().findFirst();
if (networkForLinks.isPresent()) {
logger().debug("Associating container with network: {}", networkForLinks.get());
createCommand.withNetworkMode(networkForLinks.get());
}
if (hostAccessible) {
PortForwardingContainer.INSTANCE.start();
}
PortForwardingContainer.INSTANCE.getNetwork().ifPresent(it -> {
withExtraHost(INTERNAL_HOST_HOSTNAME, it.getIpAddress());
});
String[] extraHostsArray = extraHosts.stream()
.toArray(String[]::new);
createCommand.withExtraHosts(extraHostsArray);
if (network != null) {
createCommand.withNetworkMode(network.getId());
createCommand.withAliases(this.networkAliases);
} else if (networkMode != null) {
createCommand.withNetworkMode(networkMode);
}
if (workingDirectory != null) {
createCommand.withWorkingDir(workingDirectory);
}
if (privilegedMode) {
createCommand.withPrivileged(privilegedMode);
}
createContainerCmdModifiers.forEach(hook -> hook.accept(createCommand));
Map<String, String> combinedLabels = new HashMap<>();
combinedLabels.putAll(labels);
if (createCommand.getLabels() != null) {
combinedLabels.putAll(createCommand.getLabels());
}
createCommand.withLabels(combinedLabels);
}
private Set<Link> findLinksFromThisContainer(String alias, LinkableContainer linkableContainer) {
return dockerClient.listContainersCmd()
.withStatusFilter(Arrays.asList("running"))
.exec().stream()
.flatMap(container -> Stream.of(container.getNames()))
.filter(name -> name.endsWith(linkableContainer.getContainerName()))
.map(name -> new Link(name, alias))
.collect(Collectors.toSet());
}
private Set<String> findAllNetworksForLinkedContainers(LinkableContainer linkableContainer) {
return dockerClient.listContainersCmd().exec().stream()
.filter(container -> container.getNames()[0].endsWith(linkableContainer.getContainerName()))
.filter(container -> container.getNetworkSettings() != null &&
container.getNetworkSettings().getNetworks() != null)
.flatMap(container -> container.getNetworkSettings().getNetworks().keySet().stream())
.distinct()
.collect(Collectors.toSet());
}
/**
* {@inheritDoc}
*/
@Override
public SELF waitingFor(@NonNull org.testcontainers.containers.wait.strategy.WaitStrategy waitStrategy) {
this.waitStrategy = waitStrategy;
return self();
}
/**
* The {@link WaitStrategy} to use to determine if the container is ready.
* Defaults to {@link Wait#defaultWaitStrategy()}.
*
* @return the {@link WaitStrategy} to use
*/
protected org.testcontainers.containers.wait.strategy.WaitStrategy getWaitStrategy() {
return waitStrategy;
}
@Override
public void setWaitStrategy(org.testcontainers.containers.wait.strategy.WaitStrategy waitStrategy) {
this.waitStrategy = waitStrategy;
}
/**
* Wait until the container has started. The default implementation simply
* waits for a port to start listening; other implementations are available
* as implementations of {@link org.testcontainers.containers.wait.strategy.WaitStrategy}
*
* @see #waitingFor(org.testcontainers.containers.wait.strategy.WaitStrategy)
*/
protected void waitUntilContainerStarted() {
org.testcontainers.containers.wait.strategy.WaitStrategy waitStrategy = getWaitStrategy();
if (waitStrategy != null) {
waitStrategy.waitUntilReady(this);
}
}
/**
* {@inheritDoc}
*/
@Override
public void setCommand(@NonNull String command) {
this.commandParts = command.split(" ");
}
/**
* {@inheritDoc}
*/
@Override
public void setCommand(@NonNull String... commandParts) {
this.commandParts = commandParts;
}
@Override
public Map<String, String> getEnvMap() {
return env;
}
/**
* {@inheritDoc}
*/
@Override
public List<String> getEnv() {
return env.entrySet().stream()
.map(it -> it.getKey() + "=" + it.getValue())
.collect(Collectors.toList());
}
@Override
public void setEnv(List<String> env) {
this.env = env.stream()
.map(it -> it.split("="))
.collect(Collectors.toMap(
it -> it[0],
it -> it[1]
));
}
/**
* {@inheritDoc}
*/
@Override
public void addEnv(String key, String value) {
env.put(key, value);
}
/**
* {@inheritDoc}
*/
@Override
public void addFileSystemBind(final String hostPath, final String containerPath, final BindMode mode, final SelinuxContext selinuxContext) {
if (SystemUtils.IS_OS_WINDOWS && hostPath.startsWith("/")) {
// e.g. Docker socket mount
binds.add(new Bind(hostPath, new Volume(containerPath), mode.accessMode, selinuxContext.selContext));
} else {
final MountableFile mountableFile = MountableFile.forHostPath(hostPath);
binds.add(new Bind(mountableFile.getResolvedPath(), new Volume(containerPath), mode.accessMode, selinuxContext.selContext));
}
}
/**
* {@inheritDoc}
*/