-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocker_cli_network_unix_test.go
1843 lines (1513 loc) · 72.5 KB
/
docker_cli_network_unix_test.go
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
// +build !windows
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/versions/v1p20"
"github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/cli"
"github.com/docker/docker/integration-cli/daemon"
"github.com/docker/docker/pkg/stringid"
icmd "github.com/docker/docker/pkg/testutil/cmd"
"github.com/docker/docker/runconfig"
"github.com/docker/libnetwork/driverapi"
remoteapi "github.com/docker/libnetwork/drivers/remote/api"
"github.com/docker/libnetwork/ipamapi"
remoteipam "github.com/docker/libnetwork/ipams/remote/api"
"github.com/docker/libnetwork/netlabel"
"github.com/go-check/check"
"github.com/vishvananda/netlink"
)
const dummyNetworkDriver = "dummy-network-driver"
const dummyIPAMDriver = "dummy-ipam-driver"
var remoteDriverNetworkRequest remoteapi.CreateNetworkRequest
func init() {
check.Suite(&DockerNetworkSuite{
ds: &DockerSuite{},
})
}
type DockerNetworkSuite struct {
server *httptest.Server
ds *DockerSuite
d *daemon.Daemon
}
func (s *DockerNetworkSuite) SetUpTest(c *check.C) {
s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
Experimental: testEnv.ExperimentalDaemon(),
})
}
func (s *DockerNetworkSuite) TearDownTest(c *check.C) {
if s.d != nil {
s.d.Stop(c)
s.ds.TearDownTest(c)
}
}
func (s *DockerNetworkSuite) SetUpSuite(c *check.C) {
mux := http.NewServeMux()
s.server = httptest.NewServer(mux)
c.Assert(s.server, check.NotNil, check.Commentf("Failed to start an HTTP Server"))
setupRemoteNetworkDrivers(c, mux, s.server.URL, dummyNetworkDriver, dummyIPAMDriver)
}
func setupRemoteNetworkDrivers(c *check.C, mux *http.ServeMux, url, netDrv, ipamDrv string) {
mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType)
})
// Network driver implementation
mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, `{"Scope":"local"}`)
})
mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
if err != nil {
http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, "null")
})
mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, "null")
})
mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, `{"Interface":{"MacAddress":"a0:b1:c2:d3:e4:f5"}}`)
})
mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
veth := &netlink.Veth{
LinkAttrs: netlink.LinkAttrs{Name: "randomIfName", TxQLen: 0}, PeerName: "cnt0"}
if err := netlink.LinkAdd(veth); err != nil {
fmt.Fprintf(w, `{"Error":"failed to add veth pair: `+err.Error()+`"}`)
} else {
fmt.Fprintf(w, `{"InterfaceName":{ "SrcName":"cnt0", "DstPrefix":"veth"}}`)
}
})
mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, "null")
})
mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
if link, err := netlink.LinkByName("cnt0"); err == nil {
netlink.LinkDel(link)
}
fmt.Fprintf(w, "null")
})
// IPAM Driver implementation
var (
poolRequest remoteipam.RequestPoolRequest
poolReleaseReq remoteipam.ReleasePoolRequest
addressRequest remoteipam.RequestAddressRequest
addressReleaseReq remoteipam.ReleaseAddressRequest
lAS = "localAS"
gAS = "globalAS"
pool = "172.28.0.0/16"
poolID = lAS + "/" + pool
gw = "172.28.255.254/16"
)
mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`)
})
mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&poolRequest)
if err != nil {
http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS {
fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`)
} else if poolRequest.Pool != "" && poolRequest.Pool != pool {
fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`)
} else {
fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`)
}
})
mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&addressRequest)
if err != nil {
http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
// make sure libnetwork is now querying on the expected pool id
if addressRequest.PoolID != poolID {
fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
} else if addressRequest.Address != "" {
fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`)
} else {
fmt.Fprintf(w, `{"Address":"`+gw+`"}`)
}
})
mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&addressReleaseReq)
if err != nil {
http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
// make sure libnetwork is now asking to release the expected address from the expected poolid
if addressRequest.PoolID != poolID {
fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
} else if addressReleaseReq.Address != gw {
fmt.Fprintf(w, `{"Error":"unknown address"}`)
} else {
fmt.Fprintf(w, "null")
}
})
mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&poolReleaseReq)
if err != nil {
http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
// make sure libnetwork is now asking to release the expected poolid
if addressRequest.PoolID != poolID {
fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
} else {
fmt.Fprintf(w, "null")
}
})
err := os.MkdirAll("/etc/docker/plugins", 0755)
c.Assert(err, checker.IsNil)
fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", netDrv)
err = ioutil.WriteFile(fileName, []byte(url), 0644)
c.Assert(err, checker.IsNil)
ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", ipamDrv)
err = ioutil.WriteFile(ipamFileName, []byte(url), 0644)
c.Assert(err, checker.IsNil)
}
func (s *DockerNetworkSuite) TearDownSuite(c *check.C) {
if s.server == nil {
return
}
s.server.Close()
err := os.RemoveAll("/etc/docker/plugins")
c.Assert(err, checker.IsNil)
}
func assertNwIsAvailable(c *check.C, name string) {
if !isNwPresent(c, name) {
c.Fatalf("Network %s not found in network ls o/p", name)
}
}
func assertNwNotAvailable(c *check.C, name string) {
if isNwPresent(c, name) {
c.Fatalf("Found network %s in network ls o/p", name)
}
}
func isNwPresent(c *check.C, name string) bool {
out, _ := dockerCmd(c, "network", "ls")
lines := strings.Split(out, "\n")
for i := 1; i < len(lines)-1; i++ {
netFields := strings.Fields(lines[i])
if netFields[1] == name {
return true
}
}
return false
}
// assertNwList checks network list retrieved with ls command
// equals to expected network list
// note: out should be `network ls [option]` result
func assertNwList(c *check.C, out string, expectNws []string) {
lines := strings.Split(out, "\n")
var nwList []string
for _, line := range lines[1 : len(lines)-1] {
netFields := strings.Fields(line)
// wrap all network name in nwList
nwList = append(nwList, netFields[1])
}
// network ls should contains all expected networks
c.Assert(nwList, checker.DeepEquals, expectNws)
}
func getNwResource(c *check.C, name string) *types.NetworkResource {
out, _ := dockerCmd(c, "network", "inspect", name)
nr := []types.NetworkResource{}
err := json.Unmarshal([]byte(out), &nr)
c.Assert(err, check.IsNil)
return &nr[0]
}
func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) {
defaults := []string{"bridge", "host", "none"}
for _, nn := range defaults {
assertNwIsAvailable(c, nn)
}
}
func (s *DockerSuite) TestNetworkLsFormat(c *check.C) {
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "network", "ls", "--format", "{{.Name}}")
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
expected := []string{"bridge", "host", "none"}
var names []string
names = append(names, lines...)
c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names))
}
func (s *DockerSuite) TestNetworkLsFormatDefaultFormat(c *check.C) {
testRequires(c, DaemonIsLinux)
config := `{
"networksFormat": "{{ .Name }} default"
}`
d, err := ioutil.TempDir("", "integration-cli-")
c.Assert(err, checker.IsNil)
defer os.RemoveAll(d)
err = ioutil.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0644)
c.Assert(err, checker.IsNil)
out, _ := dockerCmd(c, "--config", d, "network", "ls")
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
expected := []string{"bridge default", "host default", "none default"}
var names []string
names = append(names, lines...)
c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names))
}
func (s *DockerNetworkSuite) TestDockerNetworkCreatePredefined(c *check.C) {
predefined := []string{"bridge", "host", "none", "default"}
for _, net := range predefined {
// predefined networks can't be created again
out, _, err := dockerCmdWithError("network", "create", net)
c.Assert(err, checker.NotNil, check.Commentf("%v", out))
}
}
func (s *DockerNetworkSuite) TestDockerNetworkCreateHostBind(c *check.C) {
dockerCmd(c, "network", "create", "--subnet=192.168.10.0/24", "--gateway=192.168.10.1", "-o", "com.docker.network.bridge.host_binding_ipv4=192.168.10.1", "testbind")
assertNwIsAvailable(c, "testbind")
out := runSleepingContainer(c, "--net=testbind", "-p", "5000:5000")
id := strings.TrimSpace(out)
c.Assert(waitRun(id), checker.IsNil)
out, _ = dockerCmd(c, "ps")
c.Assert(out, checker.Contains, "192.168.10.1:5000->5000/tcp")
}
func (s *DockerNetworkSuite) TestDockerNetworkRmPredefined(c *check.C) {
predefined := []string{"bridge", "host", "none", "default"}
for _, net := range predefined {
// predefined networks can't be removed
out, _, err := dockerCmdWithError("network", "rm", net)
c.Assert(err, checker.NotNil, check.Commentf("%v", out))
}
}
func (s *DockerNetworkSuite) TestDockerNetworkLsFilter(c *check.C) {
testNet := "testnet1"
testLabel := "foo"
testValue := "bar"
out, _ := dockerCmd(c, "network", "create", "dev")
defer func() {
dockerCmd(c, "network", "rm", "dev")
dockerCmd(c, "network", "rm", testNet)
}()
networkID := strings.TrimSpace(out)
// filter with partial ID
// only show 'dev' network
out, _ = dockerCmd(c, "network", "ls", "-f", "id="+networkID[0:5])
assertNwList(c, out, []string{"dev"})
out, _ = dockerCmd(c, "network", "ls", "-f", "name=dge")
assertNwList(c, out, []string{"bridge"})
// only show built-in network (bridge, none, host)
out, _ = dockerCmd(c, "network", "ls", "-f", "type=builtin")
assertNwList(c, out, []string{"bridge", "host", "none"})
// only show custom networks (dev)
out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom")
assertNwList(c, out, []string{"dev"})
// show all networks with filter
// it should be equivalent of ls without option
out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom", "-f", "type=builtin")
assertNwList(c, out, []string{"bridge", "dev", "host", "none"})
out, _ = dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet)
assertNwIsAvailable(c, testNet)
out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel)
assertNwList(c, out, []string{testNet})
out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel+"="+testValue)
assertNwList(c, out, []string{testNet})
out, _ = dockerCmd(c, "network", "ls", "-f", "label=nonexistent")
outArr := strings.Split(strings.TrimSpace(out), "\n")
c.Assert(len(outArr), check.Equals, 1, check.Commentf("%s\n", out))
out, _ = dockerCmd(c, "network", "ls", "-f", "driver=null")
assertNwList(c, out, []string{"none"})
out, _ = dockerCmd(c, "network", "ls", "-f", "driver=host")
assertNwList(c, out, []string{"host"})
out, _ = dockerCmd(c, "network", "ls", "-f", "driver=bridge")
assertNwList(c, out, []string{"bridge", "dev", testNet})
}
func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *check.C) {
dockerCmd(c, "network", "create", "test")
assertNwIsAvailable(c, "test")
dockerCmd(c, "network", "rm", "test")
assertNwNotAvailable(c, "test")
}
func (s *DockerNetworkSuite) TestDockerNetworkCreateLabel(c *check.C) {
testNet := "testnetcreatelabel"
testLabel := "foo"
testValue := "bar"
dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet)
assertNwIsAvailable(c, testNet)
out, _, err := dockerCmdWithError("network", "inspect", "--format={{ .Labels."+testLabel+" }}", testNet)
c.Assert(err, check.IsNil)
c.Assert(strings.TrimSpace(out), check.Equals, testValue)
dockerCmd(c, "network", "rm", testNet)
assertNwNotAvailable(c, testNet)
}
func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *check.C) {
out, _, err := dockerCmdWithError("network", "rm", "test")
c.Assert(err, checker.NotNil, check.Commentf("%v", out))
}
func (s *DockerSuite) TestDockerNetworkDeleteMultiple(c *check.C) {
dockerCmd(c, "network", "create", "testDelMulti0")
assertNwIsAvailable(c, "testDelMulti0")
dockerCmd(c, "network", "create", "testDelMulti1")
assertNwIsAvailable(c, "testDelMulti1")
dockerCmd(c, "network", "create", "testDelMulti2")
assertNwIsAvailable(c, "testDelMulti2")
out, _ := dockerCmd(c, "run", "-d", "--net", "testDelMulti2", "busybox", "top")
containerID := strings.TrimSpace(out)
waitRun(containerID)
// delete three networks at the same time, since testDelMulti2
// contains active container, its deletion should fail.
out, _, err := dockerCmdWithError("network", "rm", "testDelMulti0", "testDelMulti1", "testDelMulti2")
// err should not be nil due to deleting testDelMulti2 failed.
c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
// testDelMulti2 should fail due to network has active endpoints
c.Assert(out, checker.Contains, "has active endpoints")
assertNwNotAvailable(c, "testDelMulti0")
assertNwNotAvailable(c, "testDelMulti1")
// testDelMulti2 can't be deleted, so it should exist
assertNwIsAvailable(c, "testDelMulti2")
}
func (s *DockerSuite) TestDockerNetworkInspect(c *check.C) {
out, _ := dockerCmd(c, "network", "inspect", "host")
networkResources := []types.NetworkResource{}
err := json.Unmarshal([]byte(out), &networkResources)
c.Assert(err, check.IsNil)
c.Assert(networkResources, checker.HasLen, 1)
out, _ = dockerCmd(c, "network", "inspect", "--format={{ .Name }}", "host")
c.Assert(strings.TrimSpace(out), check.Equals, "host")
}
func (s *DockerSuite) TestDockerNetworkInspectWithID(c *check.C) {
out, _ := dockerCmd(c, "network", "create", "test2")
networkID := strings.TrimSpace(out)
assertNwIsAvailable(c, "test2")
out, _ = dockerCmd(c, "network", "inspect", "--format={{ .Id }}", "test2")
c.Assert(strings.TrimSpace(out), check.Equals, networkID)
out, _ = dockerCmd(c, "network", "inspect", "--format={{ .ID }}", "test2")
c.Assert(strings.TrimSpace(out), check.Equals, networkID)
}
func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) {
result := dockerCmdWithResult("network", "inspect", "host", "none")
c.Assert(result, icmd.Matches, icmd.Success)
networkResources := []types.NetworkResource{}
err := json.Unmarshal([]byte(result.Stdout()), &networkResources)
c.Assert(err, check.IsNil)
c.Assert(networkResources, checker.HasLen, 2)
}
func (s *DockerSuite) TestDockerInspectMultipleNetworksIncludingNonexistent(c *check.C) {
// non-existent network was not at the beginning of the inspect list
// This should print an error, return an exitCode 1 and print the host network
result := dockerCmdWithResult("network", "inspect", "host", "nonexistent")
c.Assert(result, icmd.Matches, icmd.Expected{
ExitCode: 1,
Err: "Error: No such network: nonexistent",
Out: "host",
})
networkResources := []types.NetworkResource{}
err := json.Unmarshal([]byte(result.Stdout()), &networkResources)
c.Assert(err, check.IsNil)
c.Assert(networkResources, checker.HasLen, 1)
// Only one non-existent network to inspect
// Should print an error and return an exitCode, nothing else
result = dockerCmdWithResult("network", "inspect", "nonexistent")
c.Assert(result, icmd.Matches, icmd.Expected{
ExitCode: 1,
Err: "Error: No such network: nonexistent",
Out: "[]",
})
// non-existent network was at the beginning of the inspect list
// Should not fail fast, and still print host network but print an error
result = dockerCmdWithResult("network", "inspect", "nonexistent", "host")
c.Assert(result, icmd.Matches, icmd.Expected{
ExitCode: 1,
Err: "Error: No such network: nonexistent",
Out: "host",
})
networkResources = []types.NetworkResource{}
err = json.Unmarshal([]byte(result.Stdout()), &networkResources)
c.Assert(err, check.IsNil)
c.Assert(networkResources, checker.HasLen, 1)
}
func (s *DockerSuite) TestDockerInspectNetworkWithContainerName(c *check.C) {
dockerCmd(c, "network", "create", "brNetForInspect")
assertNwIsAvailable(c, "brNetForInspect")
defer func() {
dockerCmd(c, "network", "rm", "brNetForInspect")
assertNwNotAvailable(c, "brNetForInspect")
}()
out, _ := dockerCmd(c, "run", "-d", "--name", "testNetInspect1", "--net", "brNetForInspect", "busybox", "top")
c.Assert(waitRun("testNetInspect1"), check.IsNil)
containerID := strings.TrimSpace(out)
defer func() {
// we don't stop container by name, because we'll rename it later
dockerCmd(c, "stop", containerID)
}()
out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
networkResources := []types.NetworkResource{}
err := json.Unmarshal([]byte(out), &networkResources)
c.Assert(err, check.IsNil)
c.Assert(networkResources, checker.HasLen, 1)
container, ok := networkResources[0].Containers[containerID]
c.Assert(ok, checker.True)
c.Assert(container.Name, checker.Equals, "testNetInspect1")
// rename container and check docker inspect output update
newName := "HappyNewName"
dockerCmd(c, "rename", "testNetInspect1", newName)
// check whether network inspect works properly
out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
newNetRes := []types.NetworkResource{}
err = json.Unmarshal([]byte(out), &newNetRes)
c.Assert(err, check.IsNil)
c.Assert(newNetRes, checker.HasLen, 1)
container1, ok := newNetRes[0].Containers[containerID]
c.Assert(ok, checker.True)
c.Assert(container1.Name, checker.Equals, newName)
}
func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) {
dockerCmd(c, "network", "create", "test")
assertNwIsAvailable(c, "test")
nr := getNwResource(c, "test")
c.Assert(nr.Name, checker.Equals, "test")
c.Assert(len(nr.Containers), checker.Equals, 0)
// run a container
out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
c.Assert(waitRun("test"), check.IsNil)
containerID := strings.TrimSpace(out)
// connect the container to the test network
dockerCmd(c, "network", "connect", "test", containerID)
// inspect the network to make sure container is connected
nr = getNetworkResource(c, nr.ID)
c.Assert(len(nr.Containers), checker.Equals, 1)
c.Assert(nr.Containers[containerID], check.NotNil)
// check if container IP matches network inspect
ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address)
c.Assert(err, check.IsNil)
containerIP := findContainerIP(c, "test", "test")
c.Assert(ip.String(), checker.Equals, containerIP)
// disconnect container from the network
dockerCmd(c, "network", "disconnect", "test", containerID)
nr = getNwResource(c, "test")
c.Assert(nr.Name, checker.Equals, "test")
c.Assert(len(nr.Containers), checker.Equals, 0)
// run another container
out, _ = dockerCmd(c, "run", "-d", "--net", "test", "--name", "test2", "busybox", "top")
c.Assert(waitRun("test2"), check.IsNil)
containerID = strings.TrimSpace(out)
nr = getNwResource(c, "test")
c.Assert(nr.Name, checker.Equals, "test")
c.Assert(len(nr.Containers), checker.Equals, 1)
// force disconnect the container to the test network
dockerCmd(c, "network", "disconnect", "-f", "test", containerID)
nr = getNwResource(c, "test")
c.Assert(nr.Name, checker.Equals, "test")
c.Assert(len(nr.Containers), checker.Equals, 0)
dockerCmd(c, "network", "rm", "test")
assertNwNotAvailable(c, "test")
}
func (s *DockerNetworkSuite) TestDockerNetworkIPAMMultipleNetworks(c *check.C) {
// test0 bridge network
dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
assertNwIsAvailable(c, "test1")
// test2 bridge network does not overlap
dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
assertNwIsAvailable(c, "test2")
// for networks w/o ipam specified, docker will choose proper non-overlapping subnets
dockerCmd(c, "network", "create", "test3")
assertNwIsAvailable(c, "test3")
dockerCmd(c, "network", "create", "test4")
assertNwIsAvailable(c, "test4")
dockerCmd(c, "network", "create", "test5")
assertNwIsAvailable(c, "test5")
// test network with multiple subnets
// bridge network doesn't support multiple subnets. hence, use a dummy driver that supports
dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6")
assertNwIsAvailable(c, "test6")
// test network with multiple subnets with valid ipam combinations
// also check same subnet across networks when the driver supports it.
dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
"--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16",
"--gateway=192.168.0.100", "--gateway=192.170.0.100",
"--ip-range=192.168.1.0/24",
"--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6",
"--aux-address", "c=192.170.1.5", "--aux-address", "d=192.170.1.6",
"test7")
assertNwIsAvailable(c, "test7")
// cleanup
for i := 1; i < 8; i++ {
dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
}
}
func (s *DockerNetworkSuite) TestDockerNetworkCustomIPAM(c *check.C) {
// Create a bridge network using custom ipam driver
dockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "br0")
assertNwIsAvailable(c, "br0")
// Verify expected network ipam fields are there
nr := getNetworkResource(c, "br0")
c.Assert(nr.Driver, checker.Equals, "bridge")
c.Assert(nr.IPAM.Driver, checker.Equals, dummyIPAMDriver)
// remove network and exercise remote ipam driver
dockerCmd(c, "network", "rm", "br0")
assertNwNotAvailable(c, "br0")
}
func (s *DockerNetworkSuite) TestDockerNetworkIPAMOptions(c *check.C) {
// Create a bridge network using custom ipam driver and options
dockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "--ipam-opt", "opt1=drv1", "--ipam-opt", "opt2=drv2", "br0")
assertNwIsAvailable(c, "br0")
// Verify expected network ipam options
nr := getNetworkResource(c, "br0")
opts := nr.IPAM.Options
c.Assert(opts["opt1"], checker.Equals, "drv1")
c.Assert(opts["opt2"], checker.Equals, "drv2")
}
func (s *DockerNetworkSuite) TestDockerNetworkInspectDefault(c *check.C) {
nr := getNetworkResource(c, "none")
c.Assert(nr.Driver, checker.Equals, "null")
c.Assert(nr.Scope, checker.Equals, "local")
c.Assert(nr.Internal, checker.Equals, false)
c.Assert(nr.EnableIPv6, checker.Equals, false)
c.Assert(nr.IPAM.Driver, checker.Equals, "default")
c.Assert(len(nr.IPAM.Config), checker.Equals, 0)
nr = getNetworkResource(c, "host")
c.Assert(nr.Driver, checker.Equals, "host")
c.Assert(nr.Scope, checker.Equals, "local")
c.Assert(nr.Internal, checker.Equals, false)
c.Assert(nr.EnableIPv6, checker.Equals, false)
c.Assert(nr.IPAM.Driver, checker.Equals, "default")
c.Assert(len(nr.IPAM.Config), checker.Equals, 0)
nr = getNetworkResource(c, "bridge")
c.Assert(nr.Driver, checker.Equals, "bridge")
c.Assert(nr.Scope, checker.Equals, "local")
c.Assert(nr.Internal, checker.Equals, false)
c.Assert(nr.EnableIPv6, checker.Equals, false)
c.Assert(nr.IPAM.Driver, checker.Equals, "default")
c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
c.Assert(nr.IPAM.Config[0].Subnet, checker.NotNil)
c.Assert(nr.IPAM.Config[0].Gateway, checker.NotNil)
}
func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomUnspecified(c *check.C) {
// if unspecified, network subnet will be selected from inside preferred pool
dockerCmd(c, "network", "create", "test01")
assertNwIsAvailable(c, "test01")
nr := getNetworkResource(c, "test01")
c.Assert(nr.Driver, checker.Equals, "bridge")
c.Assert(nr.Scope, checker.Equals, "local")
c.Assert(nr.Internal, checker.Equals, false)
c.Assert(nr.EnableIPv6, checker.Equals, false)
c.Assert(nr.IPAM.Driver, checker.Equals, "default")
c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
c.Assert(nr.IPAM.Config[0].Subnet, checker.NotNil)
c.Assert(nr.IPAM.Config[0].Gateway, checker.NotNil)
dockerCmd(c, "network", "rm", "test01")
assertNwNotAvailable(c, "test01")
}
func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomSpecified(c *check.C) {
dockerCmd(c, "network", "create", "--driver=bridge", "--ipv6", "--subnet=fd80:24e2:f998:72d6::/64", "--subnet=172.28.0.0/16", "--ip-range=172.28.5.0/24", "--gateway=172.28.5.254", "br0")
assertNwIsAvailable(c, "br0")
nr := getNetworkResource(c, "br0")
c.Assert(nr.Driver, checker.Equals, "bridge")
c.Assert(nr.Scope, checker.Equals, "local")
c.Assert(nr.Internal, checker.Equals, false)
c.Assert(nr.EnableIPv6, checker.Equals, true)
c.Assert(nr.IPAM.Driver, checker.Equals, "default")
c.Assert(len(nr.IPAM.Config), checker.Equals, 2)
c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16")
c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24")
c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254")
c.Assert(nr.Internal, checker.False)
dockerCmd(c, "network", "rm", "br0")
assertNwNotAvailable(c, "test01")
}
func (s *DockerNetworkSuite) TestDockerNetworkIPAMInvalidCombinations(c *check.C) {
// network with ip-range out of subnet range
_, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
c.Assert(err, check.NotNil)
// network with multiple gateways for a single subnet
_, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
c.Assert(err, check.NotNil)
// Multiple overlapping subnets in the same network must fail
_, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
c.Assert(err, check.NotNil)
// overlapping subnets across networks must fail
// create a valid test0 network
dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
assertNwIsAvailable(c, "test0")
// create an overlapping test1 network
_, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
c.Assert(err, check.NotNil)
dockerCmd(c, "network", "rm", "test0")
assertNwNotAvailable(c, "test0")
}
func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) {
dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
assertNwIsAvailable(c, "testopt")
gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
c.Assert(gopts, checker.NotNil)
opts, ok := gopts.(map[string]interface{})
c.Assert(ok, checker.Equals, true)
c.Assert(opts["opt1"], checker.Equals, "drv1")
c.Assert(opts["opt2"], checker.Equals, "drv2")
dockerCmd(c, "network", "rm", "testopt")
assertNwNotAvailable(c, "testopt")
}
func (s *DockerNetworkSuite) TestDockerPluginV2NetworkDriver(c *check.C) {
testRequires(c, DaemonIsLinux, IsAmd64, Network)
var (
npName = "tiborvass/test-docker-netplugin"
npTag = "latest"
npNameWithTag = npName + ":" + npTag
)
_, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", npNameWithTag)
c.Assert(err, checker.IsNil)
out, _, err := dockerCmdWithError("plugin", "ls")
c.Assert(err, checker.IsNil)
c.Assert(out, checker.Contains, npName)
c.Assert(out, checker.Contains, npTag)
c.Assert(out, checker.Contains, "true")
dockerCmd(c, "network", "create", "-d", npNameWithTag, "v2net")
assertNwIsAvailable(c, "v2net")
dockerCmd(c, "network", "rm", "v2net")
assertNwNotAvailable(c, "v2net")
}
func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *check.C) {
testRequires(c, ExecSupport)
// On default bridge network built-in service discovery should not happen
hostsFile := "/etc/hosts"
bridgeName := "external-bridge"
bridgeIP := "192.169.255.254/24"
createInterface(c, "bridge", bridgeName, bridgeIP)
defer deleteInterface(c, bridgeName)
s.d.StartWithBusybox(c, "--bridge", bridgeName)
defer s.d.Restart(c)
// run two containers and store first container's etc/hosts content
out, err := s.d.Cmd("run", "-d", "busybox", "top")
c.Assert(err, check.IsNil)
cid1 := strings.TrimSpace(out)
defer s.d.Cmd("stop", cid1)
hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
c.Assert(err, checker.IsNil)
out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top")
c.Assert(err, check.IsNil)
cid2 := strings.TrimSpace(out)
// verify first container's etc/hosts file has not changed after spawning the second named container
hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
c.Assert(err, checker.IsNil)
c.Assert(string(hosts), checker.Equals, string(hostsPost),
check.Commentf("Unexpected %s change on second container creation", hostsFile))
// stop container 2 and verify first container's etc/hosts has not changed
_, err = s.d.Cmd("stop", cid2)
c.Assert(err, check.IsNil)
hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
c.Assert(err, checker.IsNil)
c.Assert(string(hosts), checker.Equals, string(hostsPost),
check.Commentf("Unexpected %s change on second container creation", hostsFile))
// but discovery is on when connecting to non default bridge network
network := "anotherbridge"
out, err = s.d.Cmd("network", "create", network)
c.Assert(err, check.IsNil, check.Commentf(out))
defer s.d.Cmd("network", "rm", network)
out, err = s.d.Cmd("network", "connect", network, cid1)
c.Assert(err, check.IsNil, check.Commentf(out))
hosts, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
c.Assert(err, checker.IsNil)
hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
c.Assert(err, checker.IsNil)
c.Assert(string(hosts), checker.Equals, string(hostsPost),
check.Commentf("Unexpected %s change on second network connection", hostsFile))
}
func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
testRequires(c, ExecSupport, NotArm)
hostsFile := "/etc/hosts"
cstmBridgeNw := "custom-bridge-nw"
cstmBridgeNw1 := "custom-bridge-nw1"
dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw)
assertNwIsAvailable(c, cstmBridgeNw)
// run two anonymous containers and store their etc/hosts content
out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
cid1 := strings.TrimSpace(out)
hosts1 := readContainerFileWithExec(c, cid1, hostsFile)
out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
cid2 := strings.TrimSpace(out)
hosts2 := readContainerFileWithExec(c, cid2, hostsFile)
// verify first container etc/hosts file has not changed
hosts1post := readContainerFileWithExec(c, cid1, hostsFile)
c.Assert(string(hosts1), checker.Equals, string(hosts1post),
check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
// Connect the 2nd container to a new network and verify the
// first container /etc/hosts file still hasn't changed.
dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1)
assertNwIsAvailable(c, cstmBridgeNw1)
dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2)
hosts2 = readContainerFileWithExec(c, cid2, hostsFile)
hosts1post = readContainerFileWithExec(c, cid1, hostsFile)
c.Assert(string(hosts1), checker.Equals, string(hosts1post),
check.Commentf("Unexpected %s change on container connect", hostsFile))
// start a named container
cName := "AnyName"
out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top")
cid3 := strings.TrimSpace(out)
// verify that container 1 and 2 can ping the named container
dockerCmd(c, "exec", cid1, "ping", "-c", "1", cName)
dockerCmd(c, "exec", cid2, "ping", "-c", "1", cName)
// Stop named container and verify first two containers' etc/hosts file hasn't changed
dockerCmd(c, "stop", cid3)
hosts1post = readContainerFileWithExec(c, cid1, hostsFile)
c.Assert(string(hosts1), checker.Equals, string(hosts1post),
check.Commentf("Unexpected %s change on name container creation", hostsFile))
hosts2post := readContainerFileWithExec(c, cid2, hostsFile)
c.Assert(string(hosts2), checker.Equals, string(hosts2post),
check.Commentf("Unexpected %s change on name container creation", hostsFile))
// verify that container 1 and 2 can't ping the named container now
_, _, err := dockerCmdWithError("exec", cid1, "ping", "-c", "1", cName)
c.Assert(err, check.NotNil)
_, _, err = dockerCmdWithError("exec", cid2, "ping", "-c", "1", cName)
c.Assert(err, check.NotNil)
}
func (s *DockerNetworkSuite) TestDockerNetworkLinkOnDefaultNetworkOnly(c *check.C) {
// Legacy Link feature must work only on default network, and not across networks
cnt1 := "container1"
cnt2 := "container2"
network := "anotherbridge"
// Run first container on default network
dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top")
// Create another network and run the second container on it
dockerCmd(c, "network", "create", network)
assertNwIsAvailable(c, network)
dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top")
// Try launching a container on default network, linking to the first container. Must succeed
dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top")
// Try launching a container on default network, linking to the second container. Must fail
_, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
c.Assert(err, checker.NotNil)
// Connect second container to default network. Now a container on default network can link to it
dockerCmd(c, "network", "connect", "bridge", cnt2)
dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
}
func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) {
// Verify exposed ports are present in ps output when running a container on
// a network managed by a driver which does not provide the default gateway
// for the container
nwn := "ov"
ctn := "bb"
port1 := 80
port2 := 443
expose1 := fmt.Sprintf("--expose=%d", port1)
expose2 := fmt.Sprintf("--expose=%d", port2)
dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
assertNwIsAvailable(c, nwn)
dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top")
// Check docker ps o/p for last created container reports the unpublished ports
unpPort1 := fmt.Sprintf("%d/tcp", port1)
unpPort2 := fmt.Sprintf("%d/tcp", port2)
out, _ := dockerCmd(c, "ps", "-n=1")
// Missing unpublished ports in docker ps output
c.Assert(out, checker.Contains, unpPort1)
// Missing unpublished ports in docker ps output
c.Assert(out, checker.Contains, unpPort2)
}
func (s *DockerNetworkSuite) TestDockerNetworkDriverUngracefulRestart(c *check.C) {
testRequires(c, DaemonIsLinux, NotUserNamespace)
dnd := "dnd"
did := "did"
mux := http.NewServeMux()
server := httptest.NewServer(mux)