-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
GenericContainer.java
1230 lines (1035 loc) · 40.6 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.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
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.Info;
import com.github.dockerjava.api.model.Link;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.api.model.Volume;
import com.github.dockerjava.api.model.VolumesFrom;
import com.google.common.base.Strings;
import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.Setter;
import lombok.SneakyThrows;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang.StringUtils;
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.rnorth.visibleassertions.VisibleAssertions;
import org.slf4j.Logger;
import org.slf4j.profiler.Profiler;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.output.FrameConsumerResultCallback;
import org.testcontainers.containers.output.OutputFrame;
import org.testcontainers.containers.output.Slf4jLogConsumer;
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.Wait;
import org.testcontainers.containers.wait.WaitStrategy;
import org.testcontainers.containers.wait.strategy.WaitStrategyTarget;
import org.testcontainers.images.RemoteDockerImage;
import org.testcontainers.images.builder.Transferable;
import org.testcontainers.lifecycle.Startable;
import org.testcontainers.lifecycle.TestDescription;
import org.testcontainers.lifecycle.TestLifecycleAware;
import org.testcontainers.utility.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
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 static com.google.common.collect.Lists.newArrayList;
import static org.testcontainers.containers.output.OutputFrame.OutputType.STDERR;
import static org.testcontainers.containers.output.OutputFrame.OutputType.STDOUT;
import static org.testcontainers.utility.CommandLine.runShellCommand;
/**
* Base class for that allows a container to be launched and controlled.
*/
@Data
@EqualsAndHashCode(callSuper = false)
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";
/*
* Default settings
*/
@NonNull
private List<Integer> exposedPorts = new ArrayList<>();
@NonNull
private List<String> portBindings = new ArrayList<>();
@NonNull
private List<String> extraHosts = new ArrayList<>();
@NonNull
private String networkMode;
@NonNull
private Network network;
@NonNull
private List<String> networkAliases = new ArrayList<>(Arrays.asList(
"tc-" + Base58.randomString(8)
));
@NonNull
private Future<String> 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;
private Map<MountableFile, String> copyToFileContainerPathMap = new HashMap<>();
/*
* Unique instance of DockerClient for use by this container object.
*/
@Setter(AccessLevel.NONE)
protected DockerClient dockerClient = DockerClientFactory.instance().client();
/*
* Info about the Docker server; lazily fetched.
*/
@Setter(AccessLevel.NONE)
protected Info dockerDaemonInfo = null;
/*
* Set during container startup
*/
@Setter(AccessLevel.NONE)
protected String containerId;
@Setter(AccessLevel.NONE)
protected String containerName;
@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();
public GenericContainer() {
this(TestcontainersConfiguration.getInstance().getTinyImage());
}
public GenericContainer(@NonNull final String dockerImageName) {
this.setDockerImageName(dockerImageName);
}
public GenericContainer(@NonNull final Future<String> image) {
this.image = image;
}
/**
* Starts the container using docker, pulling an image if necessary.
*/
@Override
public void start() {
if (containerId != null) {
return;
}
doStart();
}
protected void doStart() {
Profiler profiler = new Profiler("Container startup");
profiler.setLogger(logger());
try {
profiler.start("Prepare container configuration and host configuration");
configure();
logger().debug("Starting container: {}", getDockerImageName());
logger().debug("Trying to start container: {}", image.get());
AtomicInteger attempt = new AtomicInteger(0);
Unreliables.retryUntilSuccess(startupAttempts, () -> {
logger().debug("Trying to start container: {} (attempt {}/{})", image.get(), attempt.incrementAndGet(), startupAttempts);
tryStart(profiler.startNested("Container startup attempt"));
return true;
});
} catch (Exception e) {
throw new ContainerLaunchException("Container startup failed", e);
} finally {
profiler.stop().log();
}
}
private void tryStart(Profiler profiler) {
try {
String dockerImageName = image.get();
logger().debug("Starting container: {}", dockerImageName);
logger().info("Creating container for image: {}", dockerImageName);
profiler.start("Create container");
CreateContainerCmd createCommand = dockerClient.createContainerCmd(dockerImageName);
applyConfiguration(createCommand);
containerId = createCommand.exec().getId();
connectToPortForwardingNetwork(createCommand.getNetworkMode());
copyToFileContainerPathMap.forEach(this::copyFileToContainer);
containerIsCreated(containerId);
logger().info("Starting container with ID: {}", containerId);
profiler.start("Start container");
dockerClient.startContainerCmd(containerId).exec();
// For all registered output consumers, start following as close to container startup as possible
this.logConsumers.forEach(this::followOutput);
logger().info("Container {} is starting: {}", dockerImageName, containerId);
// Tell subclasses that we're starting
profiler.start("Inspecting container");
containerInfo = dockerClient.inspectContainerCmd(containerId).exec();
containerName = containerInfo.getName();
profiler.start("Call containerIsStarting on subclasses");
containerIsStarting(containerInfo);
// Wait until the container is running (may not be fully started)
profiler.start("Wait until container has started properly, or there's evidence it failed to start.");
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.");
}
profiler.start("Wait until container started properly");
waitUntilContainerStarted();
logger().info("Container {} started", dockerImageName);
containerIsStarted(containerInfo);
} catch (Exception e) {
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)
logger().error("Container log output (if any) will follow:");
FrameConsumerResultCallback resultCallback = new FrameConsumerResultCallback();
resultCallback.addConsumer(STDOUT, new Slf4jLogConsumer(logger()));
resultCallback.addConsumer(STDERR, new Slf4jLogConsumer(logger()));
dockerClient.logContainerCmd(containerId).withStdOut(true).withStdErr(true).exec(resultCallback);
// Try to ensure that container log output is shown before proceeding
try {
resultCallback.getCompletionLatch().await(1, TimeUnit.MINUTES);
} catch (InterruptedException ignored) {
// Cannot do anything at this point
}
}
throw new ContainerLaunchException("Could not create/start container", e);
} finally {
profiler.stop();
}
}
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 = image.get();
} catch (Exception e) {
imageName = "<unknown>";
}
ResourceReaper.instance().stopAndRemoveContainer(containerId, imageName);
} 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
*/
protected Path createVolumeDirectory(boolean temporary) {
Path directory = new File(".tmp-volume-" + System.currentTimeMillis()).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"})
protected void containerIsStarted(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
if (exposedPorts.size() > 0) {
return getMappedPort(exposedPorts.get(0));
} 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) {
// Set up exposed ports (where there are no host port bindings defined)
ExposedPort[] portArray = exposedPorts.stream()
.map(ExposedPort::new)
.toArray(ExposedPort[]::new);
createCommand.withExposedPorts(portArray);
// Set up exposed ports that need host port bindings
PortBinding[] portBindingArray = portBindings.stream()
.map(PortBinding::parse)
.toArray(PortBinding[]::new);
createCommand.withPortBindings(portBindingArray);
if (commandParts != null) {
createCommand.withCmd(commandParts);
}
String[] envArray = env.entrySet().stream()
.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()) {
VisibleAssertions.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 (Map.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());
}
createCommand.withPublishAllPorts(true);
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());
}
combinedLabels.putAll(DockerClientFactory.DEFAULT_LABELS);
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) {
final MountableFile mountableFile = MountableFile.forHostPath(hostPath);
binds.add(new Bind(mountableFile.getResolvedPath(), new Volume(containerPath), mode.accessMode, selinuxContext.selContext));
}
/**
* {@inheritDoc}
*/
@Override
public SELF withFileSystemBind(String hostPath, String containerPath, BindMode mode) {
addFileSystemBind(hostPath, containerPath, mode);
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withVolumesFrom(Container container, BindMode mode) {
addVolumesFrom(container, mode);
return self();
}
private void addVolumesFrom(Container container, BindMode mode) {
volumesFroms.add(new VolumesFrom(container.getContainerName(), mode.accessMode));
}
/**
* @deprecated Links are deprecated (see <a href="https://github.com/testcontainers/testcontainers-java/issues/465">#465</a>). Please use {@link Network} features instead.
*/
@Deprecated
@Override
public void addLink(LinkableContainer otherContainer, String alias) {
this.linkedContainers.put(alias, otherContainer);
}
@Override
public void addExposedPort(Integer port) {
exposedPorts.add(port);
}
@Override
public void addExposedPorts(int... ports) {
for (int port : ports) {
exposedPorts.add(port);
}
}
private TestDescription toDescription(Description description) {
return new TestDescription() {
@Override
public String getTestId() {
return description.getDisplayName();
}
@Override
public String getFilesystemFriendlyName() {
return description.getClassName() + "-" + description.getMethodName();
}
};
}
@Override
@Deprecated
public Statement apply(Statement base, Description description) {
return super.apply(base, description);
}
@Override
@Deprecated
protected void starting(Description description) {
if (this instanceof TestLifecycleAware) {
((TestLifecycleAware) this).beforeTest(toDescription(description));
}
this.start();
}
@Override
@Deprecated
protected void succeeded(Description description) {
if (this instanceof TestLifecycleAware) {
((TestLifecycleAware) this).afterTest(toDescription(description), Optional.empty());
}
}
@Override
@Deprecated
protected void failed(Throwable e, Description description) {
if (this instanceof TestLifecycleAware) {
((TestLifecycleAware) this).afterTest(toDescription(description), Optional.of(e));
}
}
@Override
@Deprecated
protected void finished(Description description) {
this.stop();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withExposedPorts(Integer... ports) {
this.setExposedPorts(newArrayList(ports));
return self();
}
/**
* Add a TCP container port that should be bound to a fixed port on the docker host.
* <p>
* Note that this method is protected scope to discourage use, as clashes or instability are more likely when
* using fixed port mappings. If you need to use this method from a test, please use {@link FixedHostPortGenericContainer}
* instead of GenericContainer.
*
* @param hostPort
* @param containerPort
*/
protected void addFixedExposedPort(int hostPort, int containerPort) {
addFixedExposedPort(hostPort, containerPort, InternetProtocol.TCP);
}
/**
* Add a container port that should be bound to a fixed port on the docker host.
* <p>
* Note that this method is protected scope to discourage use, as clashes or instability are more likely when
* using fixed port mappings. If you need to use this method from a test, please use {@link FixedHostPortGenericContainer}
* instead of GenericContainer.
*
* @param hostPort
* @param containerPort
* @param protocol
*/
protected void addFixedExposedPort(int hostPort, int containerPort, InternetProtocol protocol) {
portBindings.add(String.format("%d:%d/%s", hostPort, containerPort, protocol.toDockerNotation()));
}
/**
* {@inheritDoc}
*/
@Override
public SELF withEnv(String key, String value) {
this.addEnv(key, value);
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withEnv(Map<String, String> env) {
env.forEach(this::addEnv);
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withLabel(String key, String value) {
if (key.startsWith("org.testcontainers")) {
throw new IllegalArgumentException("The org.testcontainers namespace is reserved for interal use");
}
labels.put(key, value);
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withLabels(Map<String, String> labels) {
labels.forEach(this::withLabel);
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withCommand(String cmd) {
this.setCommand(cmd);
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withCommand(String... commandParts) {
this.setCommand(commandParts);
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withExtraHost(String hostname, String ipAddress) {
this.extraHosts.add(String.format("%s:%s", hostname, ipAddress));
return self();
}
@Override
public SELF withNetworkMode(String networkMode) {
this.networkMode = networkMode;
return self();
}
@Override
public SELF withNetwork(Network network) {
this.network = network;
return self();
}
@Override
public SELF withNetworkAliases(String... aliases) {
Collections.addAll(this.networkAliases, aliases);
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withClasspathResourceMapping(final String resourcePath, final String containerPath, final BindMode mode) {
return withClasspathResourceMapping(resourcePath, containerPath, mode, SelinuxContext.NONE);
}
/**
* {@inheritDoc}
*/
@Override
public SELF withClasspathResourceMapping(final String resourcePath, final String containerPath, final BindMode mode, final SelinuxContext selinuxContext) {
final MountableFile mountableFile = MountableFile.forClasspathResource(resourcePath);
this.addFileSystemBind(mountableFile.getResolvedPath(), containerPath, mode, selinuxContext);
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withStartupTimeout(Duration startupTimeout) {
getWaitStrategy().withStartupTimeout(startupTimeout);
return self();
}
@Override
public SELF withPrivilegedMode(boolean mode) {
this.privilegedMode = mode;
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withMinimumRunningDuration(Duration minimumRunningDuration) {
this.startupCheckStrategy = new MinimumDurationRunningStartupCheckStrategy(minimumRunningDuration);
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withStartupCheckStrategy(StartupCheckStrategy strategy) {
this.startupCheckStrategy = strategy;
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withWorkingDirectory(String workDir) {
this.setWorkingDirectory(workDir);
return self();
}
/**
* {@inheritDoc}
*/
@Override
public SELF withCopyFileToContainer(MountableFile mountableFile, String containerPath) {
copyToFileContainerPathMap.put(mountableFile, containerPath);
return self();
}
/**
* Get the IP address that this container may be reached on (may not be the local machine).
*
* @return an IP address
* @deprecated please use getContainerIpAddress() instead
*/
@Deprecated
public String getIpAddress() {
return getContainerIpAddress();
}
/**
* {@inheritDoc}
*/
@Override
public void setDockerImageName(@NonNull String dockerImageName) {
this.image = new RemoteDockerImage(dockerImageName);
// Mimic old behavior where we resolve image once it's set
getDockerImageName();
}
/**
* {@inheritDoc}
*/
@Override
@NonNull
public String getDockerImageName() {
try {
return image.get();
} catch (Exception e) {
throw new ContainerFetchException("Can't get Docker image: " + image, e);
}
}
/**
* {@inheritDoc}
*/
@Override
public String getTestHostIpAddress() {
if (DockerMachineClient.instance().isInstalled()) {
try {
Optional<String> defaultMachine = DockerMachineClient.instance().getDefaultMachine();
if (!defaultMachine.isPresent()) {