forked from spotify/docker-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDefaultDockerClientTest.java
5687 lines (4781 loc) · 214 KB
/
DefaultDockerClientTest.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
/*-
* -\-\-
* docker-client
* --
* Copyright (C) 2016 Spotify AB
* Copyright (C) 2016 Thoughtworks, Inc
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/
package com.spotify.docker.client;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.Lists.newArrayList;
import static com.spotify.docker.client.DefaultDockerClient.NO_TIMEOUT;
import static com.spotify.docker.client.DockerClient.EventsParam.since;
import static com.spotify.docker.client.DockerClient.EventsParam.type;
import static com.spotify.docker.client.DockerClient.EventsParam.until;
import static com.spotify.docker.client.DockerClient.ListContainersParam.allContainers;
import static com.spotify.docker.client.DockerClient.ListContainersParam.withLabel;
import static com.spotify.docker.client.DockerClient.ListContainersParam.withStatusCreated;
import static com.spotify.docker.client.DockerClient.ListContainersParam.withStatusExited;
import static com.spotify.docker.client.DockerClient.ListContainersParam.withStatusPaused;
import static com.spotify.docker.client.DockerClient.ListContainersParam.withStatusRunning;
import static com.spotify.docker.client.DockerClient.ListImagesParam.allImages;
import static com.spotify.docker.client.DockerClient.ListImagesParam.byName;
import static com.spotify.docker.client.DockerClient.ListImagesParam.danglingImages;
import static com.spotify.docker.client.DockerClient.ListImagesParam.digests;
import static com.spotify.docker.client.DockerClient.ListVolumesParam.dangling;
import static com.spotify.docker.client.DockerClient.ListVolumesParam.driver;
import static com.spotify.docker.client.DockerClient.ListVolumesParam.name;
import static com.spotify.docker.client.DockerClient.LogsParam.follow;
import static com.spotify.docker.client.DockerClient.LogsParam.since;
import static com.spotify.docker.client.DockerClient.LogsParam.stderr;
import static com.spotify.docker.client.DockerClient.LogsParam.stdout;
import static com.spotify.docker.client.DockerClient.LogsParam.tail;
import static com.spotify.docker.client.DockerClient.LogsParam.timestamps;
import static com.spotify.docker.client.DockerClient.RemoveContainerParam.forceKill;
import static com.spotify.docker.client.VersionCompare.compareVersion;
import static com.spotify.docker.client.messages.Event.Type.CONTAINER;
import static com.spotify.docker.client.messages.Event.Type.IMAGE;
import static com.spotify.docker.client.messages.Event.Type.NETWORK;
import static com.spotify.docker.client.messages.Event.Type.VOLUME;
import static com.spotify.docker.client.messages.Network.Type.BUILTIN;
import static com.spotify.docker.client.messages.RemovedImage.Type.UNTAGGED;
import static com.spotify.docker.client.messages.swarm.PortConfig.PROTOCOL_TCP;
import static com.spotify.docker.client.messages.swarm.RestartPolicy.RESTART_POLICY_ANY;
import static java.lang.Long.toHexString;
import static java.lang.String.format;
import static java.lang.System.getenv;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.apache.commons.lang.StringUtils.containsIgnoreCase;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.any;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.anything;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.either;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import com.google.common.base.Throwables;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.Resources;
import com.google.common.util.concurrent.SettableFuture;
import com.spotify.docker.client.DockerClient.AttachParameter;
import com.spotify.docker.client.DockerClient.BuildParam;
import com.spotify.docker.client.DockerClient.EventsParam;
import com.spotify.docker.client.DockerClient.ExecCreateParam;
import com.spotify.docker.client.DockerClient.ListImagesParam;
import com.spotify.docker.client.DockerClient.ListNetworksParam;
import com.spotify.docker.client.auth.FixedRegistryAuthSupplier;
import com.spotify.docker.client.exceptions.BadParamException;
import com.spotify.docker.client.exceptions.ConflictException;
import com.spotify.docker.client.exceptions.ContainerNotFoundException;
import com.spotify.docker.client.exceptions.ContainerRenameConflictException;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.exceptions.DockerRequestException;
import com.spotify.docker.client.exceptions.DockerTimeoutException;
import com.spotify.docker.client.exceptions.ImageNotFoundException;
import com.spotify.docker.client.exceptions.ImagePushFailedException;
import com.spotify.docker.client.exceptions.NetworkNotFoundException;
import com.spotify.docker.client.exceptions.NotFoundException;
import com.spotify.docker.client.exceptions.TaskNotFoundException;
import com.spotify.docker.client.exceptions.UnsupportedApiVersionException;
import com.spotify.docker.client.exceptions.VolumeNotFoundException;
import com.spotify.docker.client.messages.AttachedNetwork;
import com.spotify.docker.client.messages.Container;
import com.spotify.docker.client.messages.ContainerChange;
import com.spotify.docker.client.messages.ContainerConfig;
import com.spotify.docker.client.messages.ContainerConfig.Healthcheck;
import com.spotify.docker.client.messages.ContainerCreation;
import com.spotify.docker.client.messages.ContainerExit;
import com.spotify.docker.client.messages.ContainerInfo;
import com.spotify.docker.client.messages.ContainerMount;
import com.spotify.docker.client.messages.ContainerStats;
import com.spotify.docker.client.messages.ContainerUpdate;
import com.spotify.docker.client.messages.Device;
import com.spotify.docker.client.messages.EndpointConfig;
import com.spotify.docker.client.messages.EndpointConfig.EndpointIpamConfig;
import com.spotify.docker.client.messages.Event;
import com.spotify.docker.client.messages.ExecCreation;
import com.spotify.docker.client.messages.ExecState;
import com.spotify.docker.client.messages.HostConfig;
import com.spotify.docker.client.messages.HostConfig.Bind;
import com.spotify.docker.client.messages.HostConfig.Ulimit;
import com.spotify.docker.client.messages.Image;
import com.spotify.docker.client.messages.ImageHistory;
import com.spotify.docker.client.messages.ImageInfo;
import com.spotify.docker.client.messages.ImageSearchResult;
import com.spotify.docker.client.messages.Info;
import com.spotify.docker.client.messages.Ipam;
import com.spotify.docker.client.messages.IpamConfig;
import com.spotify.docker.client.messages.LogConfig;
import com.spotify.docker.client.messages.Network;
import com.spotify.docker.client.messages.NetworkConfig;
import com.spotify.docker.client.messages.NetworkConnection;
import com.spotify.docker.client.messages.NetworkCreation;
import com.spotify.docker.client.messages.PortBinding;
import com.spotify.docker.client.messages.ProcessConfig;
import com.spotify.docker.client.messages.ProgressMessage;
import com.spotify.docker.client.messages.RegistryAuth;
import com.spotify.docker.client.messages.RegistryConfigs;
import com.spotify.docker.client.messages.RemovedImage;
import com.spotify.docker.client.messages.ServiceCreateResponse;
import com.spotify.docker.client.messages.TopResults;
import com.spotify.docker.client.messages.Version;
import com.spotify.docker.client.messages.Volume;
import com.spotify.docker.client.messages.VolumeList;
import com.spotify.docker.client.messages.mount.BindOptions;
import com.spotify.docker.client.messages.mount.Mount;
import com.spotify.docker.client.messages.mount.TmpfsOptions;
import com.spotify.docker.client.messages.mount.VolumeOptions;
import com.spotify.docker.client.messages.swarm.CaConfig;
import com.spotify.docker.client.messages.swarm.ContainerSpec;
import com.spotify.docker.client.messages.swarm.DispatcherConfig;
import com.spotify.docker.client.messages.swarm.Driver;
import com.spotify.docker.client.messages.swarm.EncryptionConfig;
import com.spotify.docker.client.messages.swarm.Endpoint;
import com.spotify.docker.client.messages.swarm.EndpointSpec;
import com.spotify.docker.client.messages.swarm.EngineConfig;
import com.spotify.docker.client.messages.swarm.EnginePlugin;
import com.spotify.docker.client.messages.swarm.NetworkAttachmentConfig;
import com.spotify.docker.client.messages.swarm.Node;
import com.spotify.docker.client.messages.swarm.NodeDescription;
import com.spotify.docker.client.messages.swarm.NodeSpec;
import com.spotify.docker.client.messages.swarm.OrchestrationConfig;
import com.spotify.docker.client.messages.swarm.Placement;
import com.spotify.docker.client.messages.swarm.PortConfig;
import com.spotify.docker.client.messages.swarm.PortConfig.PortConfigPublishMode;
import com.spotify.docker.client.messages.swarm.RaftConfig;
import com.spotify.docker.client.messages.swarm.ReplicatedService;
import com.spotify.docker.client.messages.swarm.ResourceRequirements;
import com.spotify.docker.client.messages.swarm.RestartPolicy;
import com.spotify.docker.client.messages.swarm.Secret;
import com.spotify.docker.client.messages.swarm.SecretBind;
import com.spotify.docker.client.messages.swarm.SecretCreateResponse;
import com.spotify.docker.client.messages.swarm.SecretFile;
import com.spotify.docker.client.messages.swarm.SecretSpec;
import com.spotify.docker.client.messages.swarm.Service;
import com.spotify.docker.client.messages.swarm.ServiceMode;
import com.spotify.docker.client.messages.swarm.ServiceSpec;
import com.spotify.docker.client.messages.swarm.Swarm;
import com.spotify.docker.client.messages.swarm.SwarmInit;
import com.spotify.docker.client.messages.swarm.SwarmSpec;
import com.spotify.docker.client.messages.swarm.Task;
import com.spotify.docker.client.messages.swarm.TaskDefaults;
import com.spotify.docker.client.messages.swarm.TaskSpec;
import com.spotify.docker.client.messages.swarm.UnlockKey;
import com.spotify.docker.client.messages.swarm.UpdateConfig;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.pool.PoolStats;
import org.glassfish.jersey.apache.connector.ApacheClientProperties;
import org.glassfish.jersey.internal.util.Base64;
import org.hamcrest.CustomTypeSafeMatcher;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Integration tests for DefaultDockerClient that assume a docker daemon is available to connect to
* at the DOCKER_HOST environment variable.
* <p>
* When adding new functionality to DefaultDockerClient, <b>please consider adding new unit tests
* to {@link DefaultDockerClientUnitTest} rather than integration tests to this file</b>, for all of
* the reasons outlined in that class.
* </p>
*/
public class DefaultDockerClientTest {
private static final String BUSYBOX = "busybox";
private static final String BUSYBOX_LATEST = BUSYBOX + ":latest";
private static final String BUSYBOX_BUILDROOT_2013_08_1 = BUSYBOX + ":buildroot-2013.08.1";
private static final String MEMCACHED = "rohan/memcached-mini";
private static final String MEMCACHED_LATEST = MEMCACHED + ":latest";
private static final String CIRROS_PRIVATE = "dxia/cirros-private";
private static final String CIRROS_PRIVATE_LATEST = CIRROS_PRIVATE + ":latest";
private static final boolean CIRCLECI = !isNullOrEmpty(getenv("CIRCLECI"));
private static final boolean TRAVIS = "true".equals(getenv("TRAVIS"));
private static final String AUTH_USERNAME = "dxia2";
private static final String AUTH_PASSWORD = System.getenv("HUB_DXIA2_PASSWORD");
private static final Logger log = LoggerFactory.getLogger(DefaultDockerClientTest.class);
@Rule
public final ExpectedException exception = ExpectedException.none();
@Rule
public final TestName testName = new TestName();
private final RegistryAuth registryAuth = RegistryAuth.builder()
.username(AUTH_USERNAME)
.password(AUTH_PASSWORD)
.email("1234@example.com")
.build();
private final String nameTag = toHexString(ThreadLocalRandom.current().nextLong());
private URI dockerEndpoint;
private DefaultDockerClient sut;
private String dockerApiVersion;
@Before
public void setup() throws Exception {
final DefaultDockerClient.Builder builder = DefaultDockerClient.fromEnv();
// Make it easier to test no read timeout occurs by using a smaller value
// Such test methods should end in 'NoTimeout'
if (testName.getMethodName().endsWith("NoTimeout")) {
builder.readTimeoutMillis(5000);
} else {
builder.readTimeoutMillis(120000);
}
dockerEndpoint = builder.uri();
sut = builder.build();
dockerApiVersion = sut.version().apiVersion();
System.out.printf("- %s\n", testName.getMethodName());
}
@After
public void tearDown() throws Exception {
if (dockerApiVersionAtLeast("1.24")) {
try {
final List<Service> services = sut.listServices();
for (final Service service : services) {
if (service.spec().name().startsWith(nameTag)) {
sut.removeService(service.id());
}
}
} catch (DockerException e) {
log.warn("Ignoring DockerException in teardown", e);
}
}
// Remove containers
final List<Container> containers = sut.listContainers();
for (final Container container : containers) {
final ContainerInfo info = sut.inspectContainer(container.id());
if (info != null && info.name().startsWith(nameTag)) {
try {
sut.killContainer(info.id());
} catch (DockerRequestException e) {
// Docker 1.6 sometimes fails to kill a container because it disappears.
// https://github.com/docker/docker/issues/12738
log.warn("Failed to kill container {}", info.id(), e);
}
}
}
// Close the client
sut.close();
}
private void requireDockerApiVersionAtLeast(final String required, final String functionality)
throws Exception {
final String msg = String.format(
"Docker API should be at least v%s to support %s but runtime version is %s",
required, functionality, dockerApiVersion);
assumeTrue(msg, dockerApiVersionAtLeast(required));
}
private void requireStorageDriverNotAufs() throws Exception {
Info info = sut.info();
assumeFalse(info.storageDriver().equals("aufs"));
}
private boolean dockerApiVersionAtLeast(final String expected) throws Exception {
return compareVersion(dockerApiVersion, expected) >= 0;
}
private boolean dockerApiVersionLessThan(final String expected) throws Exception {
return compareVersion(dockerApiVersion, expected) < 0;
}
private void requireDockerApiVersionLessThan(final String required, final String functionality)
throws Exception {
final String actualVersion = sut.version().apiVersion();
final String msg = String.format(
"Docker API should be less than v%s to support %s but runtime version is %s",
required, functionality, actualVersion);
assumeTrue(msg, dockerApiVersionLessThan(required));
}
private boolean dockerApiVersionNot(final String expected) {
return compareVersion(dockerApiVersion, expected) != 0;
}
private boolean dockerApiVersionEquals(final String expected) {
return compareVersion(dockerApiVersion, expected) == 0;
}
private void requireDockerApiVersionNot(final String version, final String msg) {
assumeTrue(msg, dockerApiVersionNot(version));
}
@Test
public void testSearchImage() throws Exception {
requireDockerApiVersionNot("1.19", "Docker 1.7.x sends the wrong Content-Type header for "
+ "/images/search. So we skip this test.");
// when
final List<ImageSearchResult> searchResult = sut.searchImages(BUSYBOX);
// then
assertThat(searchResult.size(), greaterThan(0));
}
@Test
public void testPullWithTag() throws Exception {
sut.pull(BUSYBOX_BUILDROOT_2013_08_1);
}
@SuppressWarnings("emptyCatchBlock")
@Test
public void testPullInterruption() throws Exception {
// Wait for container on a thread
final ExecutorService executorService = Executors.newSingleThreadExecutor();
final SettableFuture<Boolean> started = SettableFuture.create();
final SettableFuture<Boolean> interrupted = SettableFuture.create();
final Future<?> exitFuture = executorService.submit(new Callable<ContainerExit>() {
@Override
public ContainerExit call() throws Exception {
try {
try {
sut.removeImage(BUSYBOX_BUILDROOT_2013_08_1);
} catch (DockerException ignored) {
}
sut.pull(BUSYBOX_BUILDROOT_2013_08_1, message -> {
if (!started.isDone()) {
started.set(true);
}
});
return null;
} catch (InterruptedException e) {
interrupted.set(true);
throw e;
}
}
});
// Interrupt waiting thread
started.get();
executorService.shutdownNow();
try {
exitFuture.get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause(), instanceOf(InterruptedException.class));
}
// Verify that the thread was interrupted
assertThat(interrupted.get(), is(true));
}
@Test(expected = ImageNotFoundException.class)
public void testPullBadImage() throws Exception {
// The Docker daemon on CircleCI won't throw ImageNotFoundException for some reason...
assumeFalse(CIRCLECI);
sut.pull(randomName());
}
@Test(expected = ImageNotFoundException.class)
public void testPullPrivateRepoWithoutAuth() throws Exception {
sut.pull(CIRROS_PRIVATE_LATEST);
}
private static Path getResource(String name) throws URISyntaxException {
// Resources.getResources(...).getPath() does not work correctly on windows,
// hence this workaround. See: https://github.com/spotify/docker-client/pull/780
// for details
return Paths.get(Resources.getResource(name).toURI());
}
@Test
public void testBuildImageIdWithBuildargs() throws Exception {
requireDockerApiVersionAtLeast("1.21", "build args");
final Path dockerDirectory = getResource("dockerDirectoryWithBuildargs");
final String buildargs = "{\"testargument\":\"22-12-2015\"}";
final BuildParam buildParam =
BuildParam.create("buildargs", URLEncoder.encode(buildargs, "UTF-8"));
sut.build(dockerDirectory, "test-buildargs", buildParam);
}
@Test
public void testHealthCheck() throws Exception {
requireDockerApiVersionAtLeast("1.24", "health check");
// Create image
final Path dockerDirectory = getResource("dockerDirectoryWithHealthCheck");
final String imageId = sut.build(dockerDirectory, "test-healthcheck");
// Inpect image to check healthcheck configuration
final ImageInfo imageInfo = sut.inspectImage(imageId);
assertNotNull(imageInfo.config().healthcheck());
assertEquals(Arrays.asList("CMD-SHELL", "exit 1"),
imageInfo.config().healthcheck().test());
// Create container based on this image to check initial container health state
final ContainerConfig config = ContainerConfig.builder()
.image("test-healthcheck")
.build();
final String name = randomName();
final ContainerCreation creation = sut.createContainer(config, name);
sut.startContainer(creation.id());
final ContainerInfo containerInfo = sut.inspectContainer(creation.id());
assertNotNull(containerInfo.state().health());
assertEquals("starting", containerInfo.state().health().status());
}
@SuppressWarnings("emptyCatchBlock")
@Test
public void testFailedPullDoesNotLeakConn() throws Exception {
log.info("Connection pool stats: " + getClientConnectionPoolStats(sut).toString());
// Pull a non-existent image 10 times and check that the number of leased connections is still 0
// I.e. check that we are not leaking connections.
for (int i = 0; i < 10; i++) {
try {
sut.pull(BUSYBOX + ":" + randomName());
} catch (ImageNotFoundException ignored) {
}
log.info("Connection pool stats: " + getClientConnectionPoolStats(sut).toString());
}
assertThat(getClientConnectionPoolStats(sut).getLeased(), equalTo(0));
}
@Test
public void testPullByDigest() throws Exception {
// The current Docker client on CircleCI does allow you to pull images by digest.
assumeFalse(CIRCLECI);
// note: this digest may change over time, the value here may disappear from hub.docker.com
sut.pull(BUSYBOX + "@sha256:4a887a2326ec9e0fa90cce7b4764b0e627b5d6afcb81a3f73c85dc29cea00048");
}
@Test
public void testSave() throws Exception {
// Ensure the local Docker instance has the busybox image so that save() will work
sut.pull(BUSYBOX_LATEST);
final File imageFile = save(BUSYBOX);
assertTrue(imageFile.length() > 0);
}
@Test
public void testLoad() throws Exception {
// Ensure the local Docker instance has the busybox image so that save() will work
sut.pull(BUSYBOX_LATEST);
// duplicate busybox with another name
final String image1 = BUSYBOX + "test1" + System.nanoTime() + ":latest";
final String image2 = BUSYBOX + "test2" + System.nanoTime() + ":latest";
try (InputStream imagePayload =
new BufferedInputStream(new FileInputStream(save(BUSYBOX_LATEST)))) {
sut.create(image1, imagePayload);
}
try (InputStream imagePayload =
new BufferedInputStream(new FileInputStream(save(BUSYBOX_LATEST)))) {
sut.create(image2, imagePayload);
}
final File imagesFile = save(image1, image2);
// Remove image from the local Docker instance to test the load
sut.removeImage(image1);
sut.removeImage(image2);
// Try to inspect deleted images and make sure ImageNotFoundException is thrown
try {
sut.inspectImage(image1);
fail("inspectImage should have thrown ImageNotFoundException");
} catch (ImageNotFoundException e) {
// we should get exception because we deleted image
}
try {
sut.inspectImage(image2);
fail("inspectImage should have thrown ImageNotFoundException");
} catch (ImageNotFoundException e) {
// we should get exception because we deleted image
}
final List<ProgressMessage> messages = new ArrayList<>();
final Set<String> loadedImages;
try (InputStream imageFileInputStream = new FileInputStream(imagesFile)) {
loadedImages = sut.load(imageFileInputStream, messages::add);
}
if (dockerApiVersionAtLeast("1.24")) {
// Verify that both images are loaded
assertEquals(loadedImages.size(), 2);
assertTrue(loadedImages.contains(image1));
assertTrue(loadedImages.contains(image2));
}
if (dockerApiVersionAtLeast("1.23")) {
// Verify that we have multiple messages, and each one has a non-null field
assertThat(messages, not(empty()));
for (final ProgressMessage message : messages) {
assertTrue(message.error() != null
|| message.id() != null
|| message.progress() != null
|| message.progressDetail() != null
|| message.status() != null
|| message.stream() != null);
}
}
// Try to inspect created images and make sure ImageNotFoundException is not thrown
try {
sut.inspectImage(image1);
sut.inspectImage(image2);
} catch (ImageNotFoundException e) {
fail("image not properly loaded in the local Docker instance");
}
// Clean created image
sut.removeImage(image1);
sut.removeImage(image2);
}
private File save(final String ... images) throws Exception {
final File tmpDir = new File(System.getProperty("java.io.tmpdir"));
assertTrue("Temp directory " + tmpDir.getAbsolutePath() + " does not exist", tmpDir.exists());
final File imageFile = new File(tmpDir, "busybox-" + System.nanoTime() + ".tar");
//noinspection ResultOfMethodCallIgnored
imageFile.createNewFile();
imageFile.deleteOnExit();
final byte[] buffer = new byte[2048];
int read;
try (OutputStream imageOutput = new BufferedOutputStream(new FileOutputStream(imageFile))) {
try (InputStream imageInput = sut.save(images)) {
while ((read = imageInput.read(buffer)) > -1) {
imageOutput.write(buffer, 0, read);
}
}
}
return imageFile;
}
@Test
public void testCreate() throws Exception {
// Ensure the local Docker instance has the busybox image so that save() will work
sut.pull(BUSYBOX_LATEST);
final File imageFile = save(BUSYBOX);
final String image = BUSYBOX + "test" + System.nanoTime();
try (InputStream imagePayload = new BufferedInputStream(new FileInputStream(imageFile))) {
sut.create(image, imagePayload);
}
final Collection<Image> images = Collections2.filter(sut.listImages(),
img -> img.repoTags() != null && img.repoTags().contains(image + ":latest"));
assertThat(images.size(), greaterThan(0));
for (final Image img : images) {
sut.removeImage(img.id());
}
}
@Test
public void testPingReturnsOk() throws Exception {
final String pingResponse = sut.ping();
assertThat(pingResponse, equalTo("OK"));
}
@Test
public void testVersion() throws Exception {
final Version version = sut.version();
assertThat(version.apiVersion(), not(isEmptyOrNullString()));
assertThat(version.arch(), not(isEmptyOrNullString()));
assertThat(version.gitCommit(), not(isEmptyOrNullString()));
assertThat(version.goVersion(), not(isEmptyOrNullString()));
assertThat(version.kernelVersion(), not(isEmptyOrNullString()));
assertThat(version.os(), not(isEmptyOrNullString()));
assertThat(version.version(), not(isEmptyOrNullString()));
if (dockerApiVersionAtLeast("1.22")) {
assertThat(version.buildTime(), not(isEmptyOrNullString()));
}
}
@Test
public void testAuth() throws Exception {
// The Docker Hub password is stored encrypted in Travis. So only run on Travis.
assumeTrue(TRAVIS);
final int statusCode = sut.auth(registryAuth);
assertThat(statusCode, equalTo(200));
}
@Test
public void testBadAuth() throws Exception {
final RegistryAuth badRegistryAuth = RegistryAuth.builder()
.username(AUTH_USERNAME)
.email("user@example.com") // docker < 1.11 requires email to be set in RegistryAuth
.password("foobar")
.build();
final int statusCode = sut.auth(badRegistryAuth);
assertThat(statusCode, equalTo(401));
}
@Test
public void testMissingAuthParam() throws Exception {
requireDockerApiVersionLessThan("1.23", "https://github.com/docker/docker/issues/24093");
final RegistryAuth badRegistryAuth = RegistryAuth.builder()
.username(AUTH_USERNAME)
.build();
final int statusCode = sut.auth(badRegistryAuth);
assertThat(statusCode, equalTo(500));
}
@Test
@SuppressWarnings("deprecation")
public void testInfo() throws Exception {
final Info info = sut.info();
assertThat(info.containers(), is(anything()));
assertThat(info.debug(), is(anything()));
assertThat(info.dockerRootDir(), not(isEmptyOrNullString()));
assertThat(info.storageDriver(), not(isEmptyOrNullString()));
assertThat(info.driverStatus(), is(anything()));
if (dockerApiVersionLessThan("1.23")) {
// Execution driver was removed in 1.24 https://github.com/docker/docker/pull/24501
// But it also shows up as "" in 1.23, and I don't know why - JF
assertThat(info.executionDriver(), not(isEmptyOrNullString()));
}
assertThat(info.id(), not(isEmptyOrNullString()));
assertThat(info.ipv4Forwarding(), is(anything()));
assertThat(info.images(), greaterThan(-1));
assertThat(info.indexServerAddress(), not(isEmptyOrNullString()));
if (dockerApiVersionLessThan("1.23")) {
// Init path seems to have been removed in API 1.23.
// Still documented as of 2016-09-26, but InitPath field is not in /info - JF
assertThat(info.initPath(), not(isEmptyOrNullString()));
}
assertThat(info.initSha1(), is(anything()));
assertThat(info.kernelVersion(), not(isEmptyOrNullString()));
assertThat(info.labels(), is(anything()));
assertThat(info.memTotal(), greaterThan(0L));
assertThat(info.memoryLimit(), not(nullValue()));
assertThat(info.cpus(), greaterThan(0));
assertThat(info.eventsListener(), is(anything()));
assertThat(info.fileDescriptors(), is(anything()));
assertThat(info.goroutines(), is(anything()));
assertThat(info.name(), not(isEmptyOrNullString()));
assertThat(info.operatingSystem(), not(isEmptyOrNullString()));
assertThat(info.registryConfig(), notNullValue());
assertThat(info.registryConfig().indexConfigs(), hasKey("docker.io"));
assertThat(info.swapLimit(), not(nullValue()));
assertThat(info.swarm(), is(anything()));
if (dockerApiVersionAtLeast("1.18")) {
assertThat(info.httpProxy(), is(anything()));
assertThat(info.httpsProxy(), is(anything()));
assertThat(info.noProxy(), is(anything()));
assertThat(info.systemTime(), not(nullValue()));
}
if (dockerApiVersionAtLeast("1.19")) {
assertThat(info.cpuCfsPeriod(), is(anything()));
assertThat(info.cpuCfsQuota(), is(anything()));
assertThat(info.experimentalBuild(), is(anything()));
assertThat(info.oomKillDisable(), is(anything()));
}
if (dockerApiVersionAtLeast("1.21")) {
assertThat(info.clusterStore(), is(anything()));
assertEquals(info.serverVersion(), sut.version().version());
}
if (dockerApiVersionAtLeast("1.22")) {
assertThat(info.architecture(), not(isEmptyOrNullString()));
assertThat(info.containersRunning(), is(anything()));
assertThat(info.containersStopped(), is(anything()));
assertThat(info.containersPaused(), is(anything()));
assertThat(info.osType(), not(isEmptyOrNullString()));
assertThat(info.systemStatus(), is(anything()));
}
if (dockerApiVersionAtLeast("1.23")) {
assertThat(info.cgroupDriver(), not(isEmptyOrNullString()));
assertThat(info.kernelMemory(), is(anything()));
}
}
@Test
public void testRemoveImage() throws Exception {
// Don't remove images on CircleCI. Their version of Docker causes failures when pulling an
// image that shares layers with an image that has been removed. This causes tests after this
// one to fail.
assumeFalse(CIRCLECI);
sut.pull("dxia/cirros:latest");
sut.pull("dxia/cirros:0.3.0");
final String imageLatest = "dxia/cirros:latest";
final String imageVersion = "dxia/cirros:0.3.0";
final Set<RemovedImage> removedImages = Sets.newHashSet();
removedImages.addAll(sut.removeImage(imageLatest));
removedImages.addAll(sut.removeImage(imageVersion));
assertThat(removedImages, hasItems(
RemovedImage.create(UNTAGGED, imageLatest),
RemovedImage.create(UNTAGGED, imageVersion)
));
// Try to inspect deleted image and make sure ImageNotFoundException is thrown
try {
sut.inspectImage(imageLatest);
fail("inspectImage should have thrown ImageNotFoundException");
} catch (ImageNotFoundException e) {
// we should get exception because we deleted image
}
}
@Test
public void testTag() throws Exception {
sut.pull(BUSYBOX_LATEST);
// Tag image
final String newImageName = "test-repo:testTag";
sut.tag(BUSYBOX, newImageName);
// Verify tag was successful by trying to remove it.
final RemovedImage removedImage = getOnlyElement(sut.removeImage(newImageName));
assertThat(removedImage, equalTo(RemovedImage.create(UNTAGGED, newImageName)));
}
@Test
public void testTagForce() throws Exception {
sut.pull(BUSYBOX_LATEST);
sut.pull(BUSYBOX_BUILDROOT_2013_08_1);
final String name = "test-repo/tag-force:sometag";
// Assign name to first image
sut.tag(BUSYBOX_LATEST, name);
// Force-re-assign tag to another image
sut.tag(BUSYBOX_BUILDROOT_2013_08_1, name, true);
// Verify that re-tagging was successful
final RemovedImage removedImage = getOnlyElement(sut.removeImage(name));
assertThat(removedImage, is(RemovedImage.create(UNTAGGED, name)));
}
@Test
public void testInspectImage() throws Exception {
sut.pull(BUSYBOX_BUILDROOT_2013_08_1);
final ImageInfo info = sut.inspectImage(BUSYBOX_BUILDROOT_2013_08_1);
assertThat(info, notNullValue());
assertThat(info.architecture(), not(isEmptyOrNullString()));
assertThat(info.author(), not(isEmptyOrNullString()));
assertThat(info.config(), notNullValue());
assertThat(info.container(), not(isEmptyOrNullString()));
assertThat(info.containerConfig(), notNullValue());
assertThat(info.comment(), notNullValue());
assertThat(info.created(), notNullValue());
assertThat(info.dockerVersion(), not(isEmptyOrNullString()));
assertThat(info.id(), not(isEmptyOrNullString()));
assertThat(info.os(), equalTo("linux"));
//noinspection StatementWithEmptyBody
if (dockerApiVersionLessThan("1.22")) {
assertThat(info.parent(), not(isEmptyOrNullString()));
} else {
// The "parent" field can be empty because of changes in
// image storage in 1.10. See https://github.com/docker/docker/issues/19650.
}
assertThat(info.size(), notNullValue());
assertThat(info.virtualSize(), notNullValue());
assertThat(info.rootFs(), notNullValue());
}
@Test
public void testCustomProgressMessageHandler() throws Exception {
final List<ProgressMessage> messages = new ArrayList<>();
sut.pull(BUSYBOX_LATEST, new ProgressHandler() {
@Override
public void progress(ProgressMessage message) throws DockerException {
messages.add(message);
}
});
// Verify that we have multiple messages, and each one has a non-null field
assertThat(messages, not(empty()));
for (final ProgressMessage message : messages) {
assertTrue(message.error() != null
|| message.id() != null
|| message.progress() != null
|| message.progressDetail() != null
|| message.status() != null
|| message.stream() != null);
}
}
@Test
public void testBuildImageId() throws Exception {
final Path dockerDirectory = getResource("dockerDirectory");
final AtomicReference<String> imageIdFromMessage = new AtomicReference<>();
final String returnedImageId = sut.build(dockerDirectory, "test", message -> {
final String imageId = message.buildImageId();
if (imageId != null) {
imageIdFromMessage.set(imageId);
}
});
assertThat(returnedImageId, is(imageIdFromMessage.get()));
}
@Test
public void testBuildImageIdPathToDockerFile() throws Exception {
final Path dockerDirectory = getResource("dockerDirectory");
final AtomicReference<String> imageIdFromMessage = new AtomicReference<>();
final String returnedImageId = sut.build(dockerDirectory, "test", "innerDir/innerDockerfile",
message -> {
final String imageId = message.buildImageId();
if (imageId != null) {
imageIdFromMessage.set(imageId);
}
});
assertThat(returnedImageId, is(imageIdFromMessage.get()));
}
@Test
public void testBuildImageIdWithAuth() throws Exception {
// The Docker Hub password is stored encrypted in Travis. So only run on Travis.
assumeTrue(TRAVIS);
final Path dockerDirectory = getResource("dockerDirectory");
final AtomicReference<String> imageIdFromMessage = new AtomicReference<>();
final RegistryAuth registryAuth = RegistryAuth.builder()
.username(AUTH_USERNAME)
.password(AUTH_PASSWORD)
.build();
final DockerClient sut2 = DefaultDockerClient.fromEnv()
.registryAuthSupplier(new FixedRegistryAuthSupplier(
registryAuth, RegistryConfigs.create(singletonMap("", registryAuth))))
.build();
final String returnedImageId = sut2.build(dockerDirectory, "test", message -> {
final String imageId = message.buildImageId();
if (imageId != null) {
imageIdFromMessage.set(imageId);
}
});
assertThat(returnedImageId, is(imageIdFromMessage.get()));
}
@SuppressWarnings("EmptyCatchBlock")
@Test
public void testFailedBuildDoesNotLeakConn() throws Exception {
final Path dockerDirectory = getResource("dockerDirectoryNonExistentImage");
log.info("Connection pool stats: " + getClientConnectionPoolStats(sut).toString());