forked from spotify/docker-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DefaultDockerClientUnitTest.java
1381 lines (1103 loc) · 48 KB
/
DefaultDockerClientUnitTest.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
* --
* 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.spotify.docker.FixtureUtil.fixture;
import static com.spotify.hamcrest.jackson.JsonMatchers.jsonArray;
import static com.spotify.hamcrest.jackson.JsonMatchers.jsonObject;
import static com.spotify.hamcrest.jackson.JsonMatchers.jsonText;
import static com.spotify.hamcrest.pojo.IsPojo.pojo;
import static java.util.Collections.singletonList;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.BaseEncoding;
import com.google.common.io.Resources;
import com.spotify.docker.client.DockerClient.Signal;
import com.spotify.docker.client.auth.RegistryAuthSupplier;
import com.spotify.docker.client.exceptions.ConflictException;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.exceptions.NodeNotFoundException;
import com.spotify.docker.client.exceptions.NonSwarmNodeException;
import com.spotify.docker.client.exceptions.NotFoundException;
import com.spotify.docker.client.messages.ContainerConfig;
import com.spotify.docker.client.messages.Distribution;
import com.spotify.docker.client.messages.HostConfig;
import com.spotify.docker.client.messages.HostConfig.Bind;
import com.spotify.docker.client.messages.RegistryAuth;
import com.spotify.docker.client.messages.RegistryConfigs;
import com.spotify.docker.client.messages.ServiceCreateResponse;
import com.spotify.docker.client.messages.Volume;
import com.spotify.docker.client.messages.swarm.Config;
import com.spotify.docker.client.messages.swarm.ConfigBind;
import com.spotify.docker.client.messages.swarm.ConfigCreateResponse;
import com.spotify.docker.client.messages.swarm.ConfigFile;
import com.spotify.docker.client.messages.swarm.ConfigSpec;
import com.spotify.docker.client.messages.swarm.ContainerSpec;
import com.spotify.docker.client.messages.swarm.EngineConfig;
import com.spotify.docker.client.messages.swarm.Node;
import com.spotify.docker.client.messages.swarm.NodeDescription;
import com.spotify.docker.client.messages.swarm.NodeInfo;
import com.spotify.docker.client.messages.swarm.NodeSpec;
import com.spotify.docker.client.messages.swarm.Placement;
import com.spotify.docker.client.messages.swarm.Preference;
import com.spotify.docker.client.messages.swarm.ResourceRequirements;
import com.spotify.docker.client.messages.swarm.Service;
import com.spotify.docker.client.messages.swarm.ServiceSpec;
import com.spotify.docker.client.messages.swarm.Spread;
import com.spotify.docker.client.messages.swarm.SwarmJoin;
import com.spotify.docker.client.messages.swarm.Task;
import com.spotify.docker.client.messages.swarm.TaskSpec;
import com.spotify.docker.client.messages.swarm.Version;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Date;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.HttpUrl;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import okio.Buffer;
import org.glassfish.jersey.client.RequestEntityProcessing;
import org.glassfish.jersey.internal.util.Base64;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Tests DefaultDockerClient against a {@link okhttp3.mockwebserver.MockWebServer} instance, so
* we can assert what the HTTP requests look like that DefaultDockerClient sends and test how
* DefaltDockerClient behaves given certain responses from the Docker Remote API.
* <p>
* This test may not be a true "unit test", but using a MockWebServer where we can control the HTTP
* responses sent by the server and capture the HTTP requests sent by the class-under-test is far
* simpler that attempting to mock the {@link javax.ws.rs.client.Client} instance used by
* DefaultDockerClient, since the Client has such a rich/fluent interface and many methods/classes
* that would need to be mocked. Ultimately for testing DefaultDockerClient all we care about is
* the HTTP requests it sends, rather than what HTTP client library it uses.</p>
* <p>
* When adding new functionality to DefaultDockerClient, please consider and prioritize adding unit
* tests to cover the new functionality in this file rather than integration tests that require a
* real docker daemon in {@link DefaultDockerClientTest}. While integration tests are valuable,
* they are more brittle and harder to run than a simple unit test that captures/asserts HTTP
* requests and responses.</p>
*
* @see <a href="https://github.com/square/okhttp/tree/master/mockwebserver">
* https://github.com/square/okhttp/tree/master/mockwebserver</a>
*/
public class DefaultDockerClientUnitTest {
private final MockWebServer server = new MockWebServer();
private DefaultDockerClient.Builder builder;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setup() throws Exception {
server.start();
builder = DefaultDockerClient.builder();
builder.uri(server.url("/").uri());
}
@After
public void tearDown() throws Exception {
server.shutdown();
}
@Test
public void testHostForUnixSocket() {
final DefaultDockerClient client = DefaultDockerClient.builder()
.uri("unix:///var/run/docker.sock").build();
assertThat(client.getHost(), equalTo("localhost"));
}
@Test
public void testHostForLocalHttps() {
final DefaultDockerClient client = DefaultDockerClient.builder()
.uri("https://localhost:2375").build();
assertThat(client.getHost(), equalTo("localhost"));
}
@Test
public void testHostForFqdnHttps() {
final DefaultDockerClient client = DefaultDockerClient.builder()
.uri("https://perdu.com:2375").build();
assertThat(client.getHost(), equalTo("perdu.com"));
}
@Test
public void testHostForIpHttps() {
final DefaultDockerClient client = DefaultDockerClient.builder()
.uri("https://192.168.53.103:2375").build();
assertThat(client.getHost(), equalTo("192.168.53.103"));
}
@Test
public void testHostWithProxy() {
try {
System.setProperty("http.proxyHost", "gmodules.com");
System.setProperty("http.proxyPort", "80");
final DefaultDockerClient client = DefaultDockerClient.builder()
.uri("https://192.168.53.103:2375").build();
assertThat(client.getClient().getConfiguration()
.getProperty("jersey.config.client.proxy.uri"),
equalTo("http://gmodules.com:80"));
} finally {
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
}
}
@Test
public void testHostWithNonProxyHost() {
try {
System.setProperty("http.proxyHost", "gmodules.com");
System.setProperty("http.proxyPort", "80");
final String nonProxyHostsPropertyValue = "127.0.0.1|localhost|192.168.*";
final List<String> nonProxyHostsPropertyValues = Arrays.asList(
nonProxyHostsPropertyValue, "\"" + nonProxyHostsPropertyValue + "\"");
for (String value : nonProxyHostsPropertyValues) {
System.setProperty("http.nonProxyHosts", value);
final DefaultDockerClient client = DefaultDockerClient.builder()
.uri("https://192.168.53.103:2375").build();
assertThat((String) client.getClient().getConfiguration()
.getProperty("jersey.config.client.proxy.uri"),
isEmptyOrNullString());
final DefaultDockerClient client1 = DefaultDockerClient.builder()
.uri("https://127.0.0.1:2375").build();
assertThat((String) client1.getClient().getConfiguration()
.getProperty("jersey.config.client.proxy.uri"),
isEmptyOrNullString());
final DefaultDockerClient client2 = DefaultDockerClient.builder()
.uri("https://localhost:2375").build();
assertThat((String) client2.getClient().getConfiguration()
.getProperty("jersey.config.client.proxy.uri"),
isEmptyOrNullString());
}
} finally {
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
System.clearProperty("http.nonProxyHosts");
}
}
private RecordedRequest takeRequestImmediately() throws InterruptedException {
return server.takeRequest(1, TimeUnit.MILLISECONDS);
}
@Test
public void testCustomHeaders() throws Exception {
builder.header("int", 1);
builder.header("string", "2");
builder.header("list", Lists.newArrayList("a", "b", "c"));
server.enqueue(new MockResponse());
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
dockerClient.info();
final RecordedRequest recordedRequest = takeRequestImmediately();
assertThat(recordedRequest.getMethod(), is("GET"));
assertThat(recordedRequest.getPath(), is("/info"));
assertThat(recordedRequest.getHeader("int"), is("1"));
assertThat(recordedRequest.getHeader("string"), is("2"));
// TODO (mbrown): this seems like incorrect behavior - the client should send 3 headers with
// name "list", not one header with a value of "[a, b, c]"
assertThat(recordedRequest.getHeaders().values("list"), contains("[a, b, c]"));
}
private static JsonNode toJson(Buffer buffer) throws IOException {
return ObjectMapperProvider.objectMapper().readTree(buffer.inputStream());
}
private static JsonNode toJson(final String string) throws IOException {
return ObjectMapperProvider.objectMapper().readTree(string);
}
private static JsonNode toJson(byte[] bytes) throws IOException {
return ObjectMapperProvider.objectMapper().readTree(bytes);
}
private static JsonNode toJson(Object object) {
return ObjectMapperProvider.objectMapper().valueToTree(object);
}
private static ObjectNode createObjectNode() {
return ObjectMapperProvider.objectMapper().createObjectNode();
}
@Test
@SuppressWarnings("unchecked")
public void testGroupAdd() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
final HostConfig hostConfig = HostConfig.builder()
.groupAdd("63", "65")
.build();
final ContainerConfig containerConfig = ContainerConfig.builder()
.hostConfig(hostConfig)
.build();
server.enqueue(new MockResponse());
dockerClient.createContainer(containerConfig);
final RecordedRequest recordedRequest = takeRequestImmediately();
final JsonNode groupAdd = toJson(recordedRequest.getBody()).get("HostConfig").get("GroupAdd");
assertThat(groupAdd.isArray(), is(true));
assertThat(childrenTextNodes((ArrayNode) groupAdd), containsInAnyOrder("63", "65"));
}
@Test
@SuppressWarnings("unchecked")
public void testCapAddAndDrop() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
final HostConfig hostConfig = HostConfig.builder()
.capAdd(ImmutableList.of("foo", "bar"))
.capAdd(ImmutableList.of("baz", "qux"))
.build();
final ContainerConfig containerConfig = ContainerConfig.builder()
.hostConfig(hostConfig)
.build();
server.enqueue(new MockResponse());
dockerClient.createContainer(containerConfig);
final RecordedRequest recordedRequest = takeRequestImmediately();
assertThat(recordedRequest.getMethod(), is("POST"));
assertThat(recordedRequest.getPath(), is("/containers/create"));
assertThat(recordedRequest.getHeader("Content-Type"), is("application/json"));
final JsonNode requestJson = toJson(recordedRequest.getBody());
assertThat(requestJson, is(jsonObject()
.where("HostConfig", is(jsonObject()
.where("CapAdd", is(jsonArray(
containsInAnyOrder(jsonText("baz"), jsonText("qux")))))))));
}
private static Set<String> childrenTextNodes(ArrayNode arrayNode) {
final Set<String> texts = new HashSet<>();
for (JsonNode child : arrayNode) {
Preconditions.checkState(child.isTextual(),
"ArrayNode must only contain text nodes, but found %s in %s",
child.getNodeType(),
arrayNode);
texts.add(child.textValue());
}
return texts;
}
@Test
@SuppressWarnings("deprecated")
public void buildThrowsIfRegistryAuthandRegistryAuthSupplierAreBothSpecified() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("LOGIC ERROR");
final RegistryAuthSupplier authSupplier = mock(RegistryAuthSupplier.class);
//noinspection deprecation
DefaultDockerClient.builder()
.registryAuth(RegistryAuth.builder().identityToken("hello").build())
.registryAuthSupplier(authSupplier)
.build();
}
@Test
public void testBuildPassesMultipleRegistryConfigs() throws Exception {
final RegistryConfigs registryConfigs = RegistryConfigs.create(ImmutableMap.of(
"server1", RegistryAuth.builder()
.serverAddress("server1")
.username("u1")
.password("p1")
.email("e1")
.build(),
"server2", RegistryAuth.builder()
.serverAddress("server2")
.username("u2")
.password("p2")
.email("e2")
.build()
));
final RegistryAuthSupplier authSupplier = mock(RegistryAuthSupplier.class);
when(authSupplier.authForBuild()).thenReturn(registryConfigs);
final DefaultDockerClient client = builder.registryAuthSupplier(authSupplier)
.build();
// build() calls /version to check what format of header to send
enqueueServerApiVersion("1.20");
server.enqueue(new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json")
.setBody(
fixture("fixtures/1.22/build.json")
)
);
final Path path = Paths.get(Resources.getResource("dockerDirectory").toURI());
client.build(path);
final RecordedRequest versionRequest = takeRequestImmediately();
assertThat(versionRequest.getMethod(), is("GET"));
assertThat(versionRequest.getPath(), is("/version"));
final RecordedRequest buildRequest = takeRequestImmediately();
assertThat(buildRequest.getMethod(), is("POST"));
assertThat(buildRequest.getPath(), is("/build"));
final String registryConfigHeader = buildRequest.getHeader("X-Registry-Config");
assertThat(registryConfigHeader, is(not(nullValue())));
// check that the JSON in the header is equivalent to what we mocked out above from
// the registryAuthSupplier
final JsonNode headerJsonNode = toJson(BaseEncoding.base64().decode(registryConfigHeader));
assertThat(headerJsonNode, is(toJson(registryConfigs.configs())));
}
@Test
public void testNanoCpus() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
final HostConfig hostConfig = HostConfig.builder()
.nanoCpus(2_000_000_000L)
.build();
final ContainerConfig containerConfig = ContainerConfig.builder()
.hostConfig(hostConfig)
.build();
server.enqueue(new MockResponse());
dockerClient.createContainer(containerConfig);
final RecordedRequest recordedRequest = takeRequestImmediately();
final JsonNode requestJson = toJson(recordedRequest.getBody());
final JsonNode nanoCpus = requestJson.get("HostConfig").get("NanoCpus");
assertThat(hostConfig.nanoCpus(), is(nanoCpus.longValue()));
}
@Test
public void testInspectNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
// build() calls /version to check what format of header to send
enqueueServerApiVersion("1.28");
enqueueServerApiResponse(200, "fixtures/1.28/nodeInfo.json");
final NodeInfo nodeInfo = dockerClient.inspectNode("24ifsmvkjbyhk");
assertThat(nodeInfo, notNullValue());
assertThat(nodeInfo.id(), is("24ifsmvkjbyhk"));
assertThat(nodeInfo.status(), notNullValue());
assertThat(nodeInfo.status().addr(), is("172.17.0.2"));
assertThat(nodeInfo.managerStatus(), notNullValue());
assertThat(nodeInfo.managerStatus().addr(), is("172.17.0.2:2377"));
assertThat(nodeInfo.managerStatus().leader(), is(true));
assertThat(nodeInfo.managerStatus().reachability(), is("reachable"));
}
@Test
public void testInspectNonLeaderNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.27");
server.enqueue(new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json")
.setBody(
fixture("fixtures/1.27/nodeInfoNonLeader.json")
)
);
NodeInfo nodeInfo = dockerClient.inspectNode("24ifsmvkjbyhk");
assertThat(nodeInfo, notNullValue());
assertThat(nodeInfo.id(), is("24ifsmvkjbyhk"));
assertThat(nodeInfo.status(), notNullValue());
assertThat(nodeInfo.status().addr(), is("172.17.0.2"));
assertThat(nodeInfo.managerStatus(), notNullValue());
assertThat(nodeInfo.managerStatus().addr(), is("172.17.0.2:2377"));
assertThat(nodeInfo.managerStatus().leader(), nullValue());
assertThat(nodeInfo.managerStatus().reachability(), is("reachable"));
}
@Test
public void testInspectNodeNonManager() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.27");
server.enqueue(new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json")
.setBody(
fixture("fixtures/1.27/nodeInfoNonManager.json")
)
);
NodeInfo nodeInfo = dockerClient.inspectNode("24ifsmvkjbyhk");
assertThat(nodeInfo, notNullValue());
assertThat(nodeInfo.id(), is("24ifsmvkjbyhk"));
assertThat(nodeInfo.status(), notNullValue());
assertThat(nodeInfo.status().addr(), is("172.17.0.2"));
assertThat(nodeInfo.managerStatus(), nullValue());
}
@Test(expected = NodeNotFoundException.class)
public void testInspectMissingNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
// build() calls /version to check what format of header to send
enqueueServerApiVersion("1.28");
enqueueServerApiEmptyResponse(404);
dockerClient.inspectNode("24ifsmvkjbyhk");
}
@Test(expected = NonSwarmNodeException.class)
public void testInspectNonSwarmNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
// build() calls /version to check what format of header to send
enqueueServerApiVersion("1.28");
enqueueServerApiEmptyResponse(503);
dockerClient.inspectNode("24ifsmvkjbyhk");
}
@Test
public void testUpdateNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.28");
enqueueServerApiResponse(200, "fixtures/1.28/listNodes.json");
final List<Node> nodes = dockerClient.listNodes();
assertThat(nodes.size(), is(1));
final Node node = nodes.get(0);
assertThat(node.id(), equalTo("24ifsmvkjbyhk"));
assertThat(node.version().index(), equalTo(8L));
assertThat(node.spec().name(), equalTo("my-node"));
assertThat(node.spec().role(), equalTo("manager"));
assertThat(node.spec().availability(), equalTo("active"));
assertThat(node.spec().labels(), hasKey(equalTo("foo")));
final NodeSpec updatedNodeSpec = NodeSpec.builder(node.spec())
.addLabel("foobar", "foobar")
.build();
enqueueServerApiVersion("1.28");
enqueueServerApiEmptyResponse(200);
dockerClient.updateNode(node.id(), node.version().index(), updatedNodeSpec);
}
@Test(expected = DockerException.class)
public void testUpdateNodeWithInvalidVersion() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.28");
final ObjectNode errorMessage = createObjectNode()
.put("message", "invalid node version: '7'");
enqueueServerApiResponse(500, errorMessage);
final NodeSpec nodeSpec = NodeSpec.builder()
.addLabel("foo", "baz")
.name("foobar")
.availability("active")
.role("manager")
.build();
dockerClient.updateNode("24ifsmvkjbyhk", 7L, nodeSpec);
}
@Test(expected = NodeNotFoundException.class)
public void testUpdateMissingNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.28");
enqueueServerApiError(404, "Error updating node: '24ifsmvkjbyhk'");
final NodeSpec nodeSpec = NodeSpec.builder()
.addLabel("foo", "baz")
.name("foobar")
.availability("active")
.role("manager")
.build();
dockerClient.updateNode("24ifsmvkjbyhk", 8L, nodeSpec);
}
@Test(expected = NonSwarmNodeException.class)
public void testUpdateNonSwarmNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.28");
enqueueServerApiError(503, "Error updating node: '24ifsmvkjbyhk'");
final NodeSpec nodeSpec = NodeSpec.builder()
.name("foobar")
.addLabel("foo", "baz")
.availability("active")
.role("manager")
.build();
dockerClient.updateNode("24ifsmvkjbyhk", 8L, nodeSpec);
}
@Test
public void testJoinSwarm() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.24");
enqueueServerApiEmptyResponse(200);
SwarmJoin swarmJoin = SwarmJoin.builder()
.joinToken("token_foo")
.listenAddr("0.0.0.0:2377")
.remoteAddrs(singletonList("10.0.0.10:2377"))
.build();
dockerClient.joinSwarm(swarmJoin);
}
private void enqueueServerApiError(final int statusCode, final String message) {
final ObjectNode errorMessage = createObjectNode()
.put("message", message);
enqueueServerApiResponse(statusCode, errorMessage);
}
@Test
public void testDeleteNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.24");
enqueueServerApiEmptyResponse(200);
dockerClient.deleteNode("node-1234");
}
@Test(expected = NodeNotFoundException.class)
public void testDeleteNode_NodeNotFound() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.24");
enqueueServerApiEmptyResponse(404);
dockerClient.deleteNode("node-1234");
}
@Test(expected = NonSwarmNodeException.class)
public void testDeleteNode_NodeNotPartOfSwarm() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.24");
enqueueServerApiEmptyResponse(503);
dockerClient.deleteNode("node-1234");
}
@Test
public void testCreateServiceWithWarnings() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
// build() calls /version to check what format of header to send
enqueueServerApiVersion("1.25");
enqueueServerApiResponse(201, "fixtures/1.25/createServiceResponse.json");
final TaskSpec taskSpec = TaskSpec.builder()
.containerSpec(ContainerSpec.builder()
.image("this_image_is_not_found_in_the_registry")
.build())
.build();
final ServiceSpec spec = ServiceSpec.builder()
.name("test")
.taskTemplate(taskSpec)
.build();
final ServiceCreateResponse response = dockerClient.createService(spec);
assertThat(response.id(), is(notNullValue()));
assertThat(response.warnings(), is(hasSize(1)));
assertThat(response.warnings(),
contains("unable to pin image this_image_is_not_found_in_the_registry to digest"));
}
@Test
public void testServiceLogs() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.25");
server.enqueue(new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "text/plain; charset=utf-8")
.setBody(
fixture("fixtures/1.25/serviceLogs.txt")
)
);
final LogStream stream = dockerClient.serviceLogs("serviceId", DockerClient.LogsParam.stderr());
assertThat(stream.readFully(), is("Log Statement"));
}
private void enqueueServerApiEmptyResponse(final int statusCode) {
server.enqueue(new MockResponse()
.setResponseCode(statusCode)
.addHeader("Content-Type", "application/json")
);
}
@Test
public void testCreateServiceWithPlacementPreference()
throws IOException, DockerException, InterruptedException {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
final ImmutableList<Preference> prefs = ImmutableList.of(
Preference.create(
Spread.create(
"test"
)
)
);
final TaskSpec taskSpec = TaskSpec.builder()
.placement(Placement.create(null, prefs))
.containerSpec(ContainerSpec.builder()
.image("this_image_is_found_in_the_registry")
.build())
.build();
final ServiceSpec spec = ServiceSpec.builder()
.name("test")
.taskTemplate(taskSpec)
.build();
enqueueServerApiVersion("1.30");
enqueueServerApiResponse(201, "fixtures/1.30/createServiceResponse.json");
final ServiceCreateResponse response = dockerClient.createService(spec);
assertThat(response.id(), equalTo("ak7w3gjqoa3kuz8xcpnyy0pvl"));
enqueueServerApiVersion("1.30");
enqueueServerApiResponse(200, "fixtures/1.30/inspectCreateResponseWithPlacementPrefs.json");
final Service service = dockerClient.inspectService("ak7w3gjqoa3kuz8xcpnyy0pvl");
assertThat(service.spec().taskTemplate().placement(), equalTo(taskSpec.placement()));
}
@Test
public void testCreateServiceWithConfig() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
// build() calls /version to check what format of header to send
enqueueServerApiVersion("1.30");
enqueueServerApiResponse(201, "fixtures/1.30/configCreateResponse.json");
final ConfigSpec configSpec = ConfigSpec
.builder()
.data(Base64.encodeAsString("foobar"))
.name("foo.yaml")
.build();
final ConfigCreateResponse configCreateResponse = dockerClient.createConfig(configSpec);
assertThat(configCreateResponse.id(), equalTo("ktnbjxoalbkvbvedmg1urrz8h"));
final ConfigBind configBind = ConfigBind.builder()
.configName(configSpec.name())
.configId(configCreateResponse.id())
.file(ConfigFile.builder()
.gid("1000")
.uid("1000")
.mode(600L)
.name(configSpec.name())
.build()
).build();
final TaskSpec taskSpec = TaskSpec.builder()
.containerSpec(ContainerSpec.builder()
.image("this_image_is_found_in_the_registry")
.configs(ImmutableList.of(configBind))
.build())
.build();
final ServiceSpec spec = ServiceSpec.builder()
.name("test")
.taskTemplate(taskSpec)
.build();
enqueueServerApiVersion("1.30");
enqueueServerApiResponse(201, "fixtures/1.30/createServiceResponse.json");
final ServiceCreateResponse response = dockerClient.createService(spec);
assertThat(response.id(), equalTo("ak7w3gjqoa3kuz8xcpnyy0pvl"));
}
@Test
public void testListConfigs() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.30");
server.enqueue(new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json")
.setBody(
fixture("fixtures/1.30/listConfigs.json")
)
);
final List<Config> configs = dockerClient.listConfigs();
assertThat(configs.size(), equalTo(1));
final Config config = configs.get(0);
assertThat(config, notNullValue());
assertThat(config.id(), equalTo("ktnbjxoalbkvbvedmg1urrz8h"));
assertThat(config.version().index(), equalTo(11L));
final ConfigSpec configSpec = config.configSpec();
assertThat(configSpec.name(), equalTo("server.conf"));
}
@Test
public void testCreateConfig() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.30");
server.enqueue(new MockResponse()
.setResponseCode(201)
.addHeader("Content-Type", "application/json")
.setBody(
fixture("fixtures/1.30/inspectConfig.json")
)
);
final ConfigSpec configSpec = ConfigSpec
.builder()
.data(Base64.encodeAsString("foobar"))
.name("foo.yaml")
.build();
final ConfigCreateResponse configCreateResponse = dockerClient.createConfig(configSpec);
assertThat(configCreateResponse.id(), equalTo("ktnbjxoalbkvbvedmg1urrz8h"));
}
@Test(expected = ConflictException.class)
public void testCreateConfig_ConflictingName() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.30");
server.enqueue(new MockResponse()
.setResponseCode(409)
.addHeader("Content-Type", "application/json")
);
final ConfigSpec configSpec = ConfigSpec
.builder()
.data(Base64.encodeAsString("foobar"))
.name("foo.yaml")
.build();
dockerClient.createConfig(configSpec);
}
@Test(expected = NonSwarmNodeException.class)
public void testCreateConfig_NonSwarmNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.30");
server.enqueue(new MockResponse()
.setResponseCode(503)
.addHeader("Content-Type", "application/json")
);
final ConfigSpec configSpec = ConfigSpec
.builder()
.data(Base64.encodeAsString("foobar"))
.name("foo.yaml")
.build();
dockerClient.createConfig(configSpec);
}
@Test
public void testInspectConfig() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.30");
server.enqueue(new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json")
.setBody(
fixture("fixtures/1.30/inspectConfig.json")
)
);
final Config config = dockerClient.inspectConfig("ktnbjxoalbkvbvedmg1urrz8h");
assertThat(config, notNullValue());
assertThat(config.id(), equalTo("ktnbjxoalbkvbvedmg1urrz8h"));
assertThat(config.version().index(), equalTo(11L));
final ConfigSpec configSpec = config.configSpec();
assertThat(configSpec.name(), equalTo("app-dev.crt"));
}
@Test(expected = NotFoundException.class)
public void testInspectConfig_NotFound() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.30");
server.enqueue(new MockResponse()
.setResponseCode(404)
.addHeader("Content-Type", "application/json")
);
dockerClient.inspectConfig("ktnbjxoalbkvbvedmg1urrz8h");
}
@Test(expected = NonSwarmNodeException.class)
public void testInspectConfig_NonSwarmNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.30");
server.enqueue(new MockResponse()
.setResponseCode(503)
.addHeader("Content-Type", "application/json")
);
dockerClient.inspectConfig("ktnbjxoalbkvbvedmg1urrz8h");
}
@Test
public void testDeleteConfig() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.30");
server.enqueue(new MockResponse()
.setResponseCode(204)
.addHeader("Content-Type", "application/json")
);
dockerClient.deleteConfig("ktnbjxoalbkvbvedmg1urrz8h");
}
@Test(expected = NotFoundException.class)
public void testDeleteConfig_NotFound() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.30");
server.enqueue(new MockResponse()
.setResponseCode(404)
.addHeader("Content-Type", "application/json")
);
dockerClient.deleteConfig("ktnbjxoalbkvbvedmg1urrz8h");
}
@Test(expected = NonSwarmNodeException.class)
public void testDeleteConfig_NonSwarmNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.30");
server.enqueue(new MockResponse()
.setResponseCode(503)
.addHeader("Content-Type", "application/json")
);
dockerClient.deleteConfig("ktnbjxoalbkvbvedmg1urrz8h");
}
@Test(expected = NotFoundException.class)
public void testUpdateConfig_NotFound() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
enqueueServerApiVersion("1.30");