docker_cli_network_unix_test.go 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843
  1. // +build !windows
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "net/http/httptest"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. "syscall"
  14. "time"
  15. "github.com/docker/docker/api/types"
  16. "github.com/docker/docker/api/types/versions/v1p20"
  17. "github.com/docker/docker/integration-cli/checker"
  18. "github.com/docker/docker/integration-cli/cli"
  19. "github.com/docker/docker/integration-cli/daemon"
  20. "github.com/docker/docker/pkg/stringid"
  21. icmd "github.com/docker/docker/pkg/testutil/cmd"
  22. "github.com/docker/docker/runconfig"
  23. "github.com/docker/libnetwork/driverapi"
  24. remoteapi "github.com/docker/libnetwork/drivers/remote/api"
  25. "github.com/docker/libnetwork/ipamapi"
  26. remoteipam "github.com/docker/libnetwork/ipams/remote/api"
  27. "github.com/docker/libnetwork/netlabel"
  28. "github.com/go-check/check"
  29. "github.com/vishvananda/netlink"
  30. )
  31. const dummyNetworkDriver = "dummy-network-driver"
  32. const dummyIPAMDriver = "dummy-ipam-driver"
  33. var remoteDriverNetworkRequest remoteapi.CreateNetworkRequest
  34. func init() {
  35. check.Suite(&DockerNetworkSuite{
  36. ds: &DockerSuite{},
  37. })
  38. }
  39. type DockerNetworkSuite struct {
  40. server *httptest.Server
  41. ds *DockerSuite
  42. d *daemon.Daemon
  43. }
  44. func (s *DockerNetworkSuite) SetUpTest(c *check.C) {
  45. s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
  46. Experimental: testEnv.ExperimentalDaemon(),
  47. })
  48. }
  49. func (s *DockerNetworkSuite) TearDownTest(c *check.C) {
  50. if s.d != nil {
  51. s.d.Stop(c)
  52. s.ds.TearDownTest(c)
  53. }
  54. }
  55. func (s *DockerNetworkSuite) SetUpSuite(c *check.C) {
  56. mux := http.NewServeMux()
  57. s.server = httptest.NewServer(mux)
  58. c.Assert(s.server, check.NotNil, check.Commentf("Failed to start an HTTP Server"))
  59. setupRemoteNetworkDrivers(c, mux, s.server.URL, dummyNetworkDriver, dummyIPAMDriver)
  60. }
  61. func setupRemoteNetworkDrivers(c *check.C, mux *http.ServeMux, url, netDrv, ipamDrv string) {
  62. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  63. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  64. fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType)
  65. })
  66. // Network driver implementation
  67. mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  68. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  69. fmt.Fprintf(w, `{"Scope":"local"}`)
  70. })
  71. mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  72. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  73. if err != nil {
  74. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  75. return
  76. }
  77. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  78. fmt.Fprintf(w, "null")
  79. })
  80. mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  81. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  82. fmt.Fprintf(w, "null")
  83. })
  84. mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  85. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  86. fmt.Fprintf(w, `{"Interface":{"MacAddress":"a0:b1:c2:d3:e4:f5"}}`)
  87. })
  88. mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  89. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  90. veth := &netlink.Veth{
  91. LinkAttrs: netlink.LinkAttrs{Name: "randomIfName", TxQLen: 0}, PeerName: "cnt0"}
  92. if err := netlink.LinkAdd(veth); err != nil {
  93. fmt.Fprintf(w, `{"Error":"failed to add veth pair: `+err.Error()+`"}`)
  94. } else {
  95. fmt.Fprintf(w, `{"InterfaceName":{ "SrcName":"cnt0", "DstPrefix":"veth"}}`)
  96. }
  97. })
  98. mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  99. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  100. fmt.Fprintf(w, "null")
  101. })
  102. mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  103. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  104. if link, err := netlink.LinkByName("cnt0"); err == nil {
  105. netlink.LinkDel(link)
  106. }
  107. fmt.Fprintf(w, "null")
  108. })
  109. // IPAM Driver implementation
  110. var (
  111. poolRequest remoteipam.RequestPoolRequest
  112. poolReleaseReq remoteipam.ReleasePoolRequest
  113. addressRequest remoteipam.RequestAddressRequest
  114. addressReleaseReq remoteipam.ReleaseAddressRequest
  115. lAS = "localAS"
  116. gAS = "globalAS"
  117. pool = "172.28.0.0/16"
  118. poolID = lAS + "/" + pool
  119. gw = "172.28.255.254/16"
  120. )
  121. mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  122. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  123. fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`)
  124. })
  125. mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  126. err := json.NewDecoder(r.Body).Decode(&poolRequest)
  127. if err != nil {
  128. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  129. return
  130. }
  131. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  132. if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS {
  133. fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`)
  134. } else if poolRequest.Pool != "" && poolRequest.Pool != pool {
  135. fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`)
  136. } else {
  137. fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`)
  138. }
  139. })
  140. mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  141. err := json.NewDecoder(r.Body).Decode(&addressRequest)
  142. if err != nil {
  143. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  144. return
  145. }
  146. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  147. // make sure libnetwork is now querying on the expected pool id
  148. if addressRequest.PoolID != poolID {
  149. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  150. } else if addressRequest.Address != "" {
  151. fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`)
  152. } else {
  153. fmt.Fprintf(w, `{"Address":"`+gw+`"}`)
  154. }
  155. })
  156. mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  157. err := json.NewDecoder(r.Body).Decode(&addressReleaseReq)
  158. if err != nil {
  159. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  160. return
  161. }
  162. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  163. // make sure libnetwork is now asking to release the expected address from the expected poolid
  164. if addressRequest.PoolID != poolID {
  165. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  166. } else if addressReleaseReq.Address != gw {
  167. fmt.Fprintf(w, `{"Error":"unknown address"}`)
  168. } else {
  169. fmt.Fprintf(w, "null")
  170. }
  171. })
  172. mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  173. err := json.NewDecoder(r.Body).Decode(&poolReleaseReq)
  174. if err != nil {
  175. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  176. return
  177. }
  178. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  179. // make sure libnetwork is now asking to release the expected poolid
  180. if addressRequest.PoolID != poolID {
  181. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  182. } else {
  183. fmt.Fprintf(w, "null")
  184. }
  185. })
  186. err := os.MkdirAll("/etc/docker/plugins", 0755)
  187. c.Assert(err, checker.IsNil)
  188. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", netDrv)
  189. err = ioutil.WriteFile(fileName, []byte(url), 0644)
  190. c.Assert(err, checker.IsNil)
  191. ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", ipamDrv)
  192. err = ioutil.WriteFile(ipamFileName, []byte(url), 0644)
  193. c.Assert(err, checker.IsNil)
  194. }
  195. func (s *DockerNetworkSuite) TearDownSuite(c *check.C) {
  196. if s.server == nil {
  197. return
  198. }
  199. s.server.Close()
  200. err := os.RemoveAll("/etc/docker/plugins")
  201. c.Assert(err, checker.IsNil)
  202. }
  203. func assertNwIsAvailable(c *check.C, name string) {
  204. if !isNwPresent(c, name) {
  205. c.Fatalf("Network %s not found in network ls o/p", name)
  206. }
  207. }
  208. func assertNwNotAvailable(c *check.C, name string) {
  209. if isNwPresent(c, name) {
  210. c.Fatalf("Found network %s in network ls o/p", name)
  211. }
  212. }
  213. func isNwPresent(c *check.C, name string) bool {
  214. out, _ := dockerCmd(c, "network", "ls")
  215. lines := strings.Split(out, "\n")
  216. for i := 1; i < len(lines)-1; i++ {
  217. netFields := strings.Fields(lines[i])
  218. if netFields[1] == name {
  219. return true
  220. }
  221. }
  222. return false
  223. }
  224. // assertNwList checks network list retrieved with ls command
  225. // equals to expected network list
  226. // note: out should be `network ls [option]` result
  227. func assertNwList(c *check.C, out string, expectNws []string) {
  228. lines := strings.Split(out, "\n")
  229. var nwList []string
  230. for _, line := range lines[1 : len(lines)-1] {
  231. netFields := strings.Fields(line)
  232. // wrap all network name in nwList
  233. nwList = append(nwList, netFields[1])
  234. }
  235. // network ls should contains all expected networks
  236. c.Assert(nwList, checker.DeepEquals, expectNws)
  237. }
  238. func getNwResource(c *check.C, name string) *types.NetworkResource {
  239. out, _ := dockerCmd(c, "network", "inspect", name)
  240. nr := []types.NetworkResource{}
  241. err := json.Unmarshal([]byte(out), &nr)
  242. c.Assert(err, check.IsNil)
  243. return &nr[0]
  244. }
  245. func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) {
  246. defaults := []string{"bridge", "host", "none"}
  247. for _, nn := range defaults {
  248. assertNwIsAvailable(c, nn)
  249. }
  250. }
  251. func (s *DockerSuite) TestNetworkLsFormat(c *check.C) {
  252. testRequires(c, DaemonIsLinux)
  253. out, _ := dockerCmd(c, "network", "ls", "--format", "{{.Name}}")
  254. lines := strings.Split(strings.TrimSpace(string(out)), "\n")
  255. expected := []string{"bridge", "host", "none"}
  256. var names []string
  257. names = append(names, lines...)
  258. c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names))
  259. }
  260. func (s *DockerSuite) TestNetworkLsFormatDefaultFormat(c *check.C) {
  261. testRequires(c, DaemonIsLinux)
  262. config := `{
  263. "networksFormat": "{{ .Name }} default"
  264. }`
  265. d, err := ioutil.TempDir("", "integration-cli-")
  266. c.Assert(err, checker.IsNil)
  267. defer os.RemoveAll(d)
  268. err = ioutil.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0644)
  269. c.Assert(err, checker.IsNil)
  270. out, _ := dockerCmd(c, "--config", d, "network", "ls")
  271. lines := strings.Split(strings.TrimSpace(string(out)), "\n")
  272. expected := []string{"bridge default", "host default", "none default"}
  273. var names []string
  274. names = append(names, lines...)
  275. c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names))
  276. }
  277. func (s *DockerNetworkSuite) TestDockerNetworkCreatePredefined(c *check.C) {
  278. predefined := []string{"bridge", "host", "none", "default"}
  279. for _, net := range predefined {
  280. // predefined networks can't be created again
  281. out, _, err := dockerCmdWithError("network", "create", net)
  282. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  283. }
  284. }
  285. func (s *DockerNetworkSuite) TestDockerNetworkCreateHostBind(c *check.C) {
  286. 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")
  287. assertNwIsAvailable(c, "testbind")
  288. out := runSleepingContainer(c, "--net=testbind", "-p", "5000:5000")
  289. id := strings.TrimSpace(out)
  290. c.Assert(waitRun(id), checker.IsNil)
  291. out, _ = dockerCmd(c, "ps")
  292. c.Assert(out, checker.Contains, "192.168.10.1:5000->5000/tcp")
  293. }
  294. func (s *DockerNetworkSuite) TestDockerNetworkRmPredefined(c *check.C) {
  295. predefined := []string{"bridge", "host", "none", "default"}
  296. for _, net := range predefined {
  297. // predefined networks can't be removed
  298. out, _, err := dockerCmdWithError("network", "rm", net)
  299. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  300. }
  301. }
  302. func (s *DockerNetworkSuite) TestDockerNetworkLsFilter(c *check.C) {
  303. testNet := "testnet1"
  304. testLabel := "foo"
  305. testValue := "bar"
  306. out, _ := dockerCmd(c, "network", "create", "dev")
  307. defer func() {
  308. dockerCmd(c, "network", "rm", "dev")
  309. dockerCmd(c, "network", "rm", testNet)
  310. }()
  311. networkID := strings.TrimSpace(out)
  312. // filter with partial ID
  313. // only show 'dev' network
  314. out, _ = dockerCmd(c, "network", "ls", "-f", "id="+networkID[0:5])
  315. assertNwList(c, out, []string{"dev"})
  316. out, _ = dockerCmd(c, "network", "ls", "-f", "name=dge")
  317. assertNwList(c, out, []string{"bridge"})
  318. // only show built-in network (bridge, none, host)
  319. out, _ = dockerCmd(c, "network", "ls", "-f", "type=builtin")
  320. assertNwList(c, out, []string{"bridge", "host", "none"})
  321. // only show custom networks (dev)
  322. out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom")
  323. assertNwList(c, out, []string{"dev"})
  324. // show all networks with filter
  325. // it should be equivalent of ls without option
  326. out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom", "-f", "type=builtin")
  327. assertNwList(c, out, []string{"bridge", "dev", "host", "none"})
  328. out, _ = dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet)
  329. assertNwIsAvailable(c, testNet)
  330. out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel)
  331. assertNwList(c, out, []string{testNet})
  332. out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel+"="+testValue)
  333. assertNwList(c, out, []string{testNet})
  334. out, _ = dockerCmd(c, "network", "ls", "-f", "label=nonexistent")
  335. outArr := strings.Split(strings.TrimSpace(out), "\n")
  336. c.Assert(len(outArr), check.Equals, 1, check.Commentf("%s\n", out))
  337. out, _ = dockerCmd(c, "network", "ls", "-f", "driver=null")
  338. assertNwList(c, out, []string{"none"})
  339. out, _ = dockerCmd(c, "network", "ls", "-f", "driver=host")
  340. assertNwList(c, out, []string{"host"})
  341. out, _ = dockerCmd(c, "network", "ls", "-f", "driver=bridge")
  342. assertNwList(c, out, []string{"bridge", "dev", testNet})
  343. }
  344. func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *check.C) {
  345. dockerCmd(c, "network", "create", "test")
  346. assertNwIsAvailable(c, "test")
  347. dockerCmd(c, "network", "rm", "test")
  348. assertNwNotAvailable(c, "test")
  349. }
  350. func (s *DockerNetworkSuite) TestDockerNetworkCreateLabel(c *check.C) {
  351. testNet := "testnetcreatelabel"
  352. testLabel := "foo"
  353. testValue := "bar"
  354. dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet)
  355. assertNwIsAvailable(c, testNet)
  356. out, _, err := dockerCmdWithError("network", "inspect", "--format={{ .Labels."+testLabel+" }}", testNet)
  357. c.Assert(err, check.IsNil)
  358. c.Assert(strings.TrimSpace(out), check.Equals, testValue)
  359. dockerCmd(c, "network", "rm", testNet)
  360. assertNwNotAvailable(c, testNet)
  361. }
  362. func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *check.C) {
  363. out, _, err := dockerCmdWithError("network", "rm", "test")
  364. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  365. }
  366. func (s *DockerSuite) TestDockerNetworkDeleteMultiple(c *check.C) {
  367. dockerCmd(c, "network", "create", "testDelMulti0")
  368. assertNwIsAvailable(c, "testDelMulti0")
  369. dockerCmd(c, "network", "create", "testDelMulti1")
  370. assertNwIsAvailable(c, "testDelMulti1")
  371. dockerCmd(c, "network", "create", "testDelMulti2")
  372. assertNwIsAvailable(c, "testDelMulti2")
  373. out, _ := dockerCmd(c, "run", "-d", "--net", "testDelMulti2", "busybox", "top")
  374. containerID := strings.TrimSpace(out)
  375. waitRun(containerID)
  376. // delete three networks at the same time, since testDelMulti2
  377. // contains active container, its deletion should fail.
  378. out, _, err := dockerCmdWithError("network", "rm", "testDelMulti0", "testDelMulti1", "testDelMulti2")
  379. // err should not be nil due to deleting testDelMulti2 failed.
  380. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  381. // testDelMulti2 should fail due to network has active endpoints
  382. c.Assert(out, checker.Contains, "has active endpoints")
  383. assertNwNotAvailable(c, "testDelMulti0")
  384. assertNwNotAvailable(c, "testDelMulti1")
  385. // testDelMulti2 can't be deleted, so it should exist
  386. assertNwIsAvailable(c, "testDelMulti2")
  387. }
  388. func (s *DockerSuite) TestDockerNetworkInspect(c *check.C) {
  389. out, _ := dockerCmd(c, "network", "inspect", "host")
  390. networkResources := []types.NetworkResource{}
  391. err := json.Unmarshal([]byte(out), &networkResources)
  392. c.Assert(err, check.IsNil)
  393. c.Assert(networkResources, checker.HasLen, 1)
  394. out, _ = dockerCmd(c, "network", "inspect", "--format={{ .Name }}", "host")
  395. c.Assert(strings.TrimSpace(out), check.Equals, "host")
  396. }
  397. func (s *DockerSuite) TestDockerNetworkInspectWithID(c *check.C) {
  398. out, _ := dockerCmd(c, "network", "create", "test2")
  399. networkID := strings.TrimSpace(out)
  400. assertNwIsAvailable(c, "test2")
  401. out, _ = dockerCmd(c, "network", "inspect", "--format={{ .Id }}", "test2")
  402. c.Assert(strings.TrimSpace(out), check.Equals, networkID)
  403. out, _ = dockerCmd(c, "network", "inspect", "--format={{ .ID }}", "test2")
  404. c.Assert(strings.TrimSpace(out), check.Equals, networkID)
  405. }
  406. func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) {
  407. result := dockerCmdWithResult("network", "inspect", "host", "none")
  408. c.Assert(result, icmd.Matches, icmd.Success)
  409. networkResources := []types.NetworkResource{}
  410. err := json.Unmarshal([]byte(result.Stdout()), &networkResources)
  411. c.Assert(err, check.IsNil)
  412. c.Assert(networkResources, checker.HasLen, 2)
  413. }
  414. func (s *DockerSuite) TestDockerInspectMultipleNetworksIncludingNonexistent(c *check.C) {
  415. // non-existent network was not at the beginning of the inspect list
  416. // This should print an error, return an exitCode 1 and print the host network
  417. result := dockerCmdWithResult("network", "inspect", "host", "nonexistent")
  418. c.Assert(result, icmd.Matches, icmd.Expected{
  419. ExitCode: 1,
  420. Err: "Error: No such network: nonexistent",
  421. Out: "host",
  422. })
  423. networkResources := []types.NetworkResource{}
  424. err := json.Unmarshal([]byte(result.Stdout()), &networkResources)
  425. c.Assert(err, check.IsNil)
  426. c.Assert(networkResources, checker.HasLen, 1)
  427. // Only one non-existent network to inspect
  428. // Should print an error and return an exitCode, nothing else
  429. result = dockerCmdWithResult("network", "inspect", "nonexistent")
  430. c.Assert(result, icmd.Matches, icmd.Expected{
  431. ExitCode: 1,
  432. Err: "Error: No such network: nonexistent",
  433. Out: "[]",
  434. })
  435. // non-existent network was at the beginning of the inspect list
  436. // Should not fail fast, and still print host network but print an error
  437. result = dockerCmdWithResult("network", "inspect", "nonexistent", "host")
  438. c.Assert(result, icmd.Matches, icmd.Expected{
  439. ExitCode: 1,
  440. Err: "Error: No such network: nonexistent",
  441. Out: "host",
  442. })
  443. networkResources = []types.NetworkResource{}
  444. err = json.Unmarshal([]byte(result.Stdout()), &networkResources)
  445. c.Assert(err, check.IsNil)
  446. c.Assert(networkResources, checker.HasLen, 1)
  447. }
  448. func (s *DockerSuite) TestDockerInspectNetworkWithContainerName(c *check.C) {
  449. dockerCmd(c, "network", "create", "brNetForInspect")
  450. assertNwIsAvailable(c, "brNetForInspect")
  451. defer func() {
  452. dockerCmd(c, "network", "rm", "brNetForInspect")
  453. assertNwNotAvailable(c, "brNetForInspect")
  454. }()
  455. out, _ := dockerCmd(c, "run", "-d", "--name", "testNetInspect1", "--net", "brNetForInspect", "busybox", "top")
  456. c.Assert(waitRun("testNetInspect1"), check.IsNil)
  457. containerID := strings.TrimSpace(out)
  458. defer func() {
  459. // we don't stop container by name, because we'll rename it later
  460. dockerCmd(c, "stop", containerID)
  461. }()
  462. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  463. networkResources := []types.NetworkResource{}
  464. err := json.Unmarshal([]byte(out), &networkResources)
  465. c.Assert(err, check.IsNil)
  466. c.Assert(networkResources, checker.HasLen, 1)
  467. container, ok := networkResources[0].Containers[containerID]
  468. c.Assert(ok, checker.True)
  469. c.Assert(container.Name, checker.Equals, "testNetInspect1")
  470. // rename container and check docker inspect output update
  471. newName := "HappyNewName"
  472. dockerCmd(c, "rename", "testNetInspect1", newName)
  473. // check whether network inspect works properly
  474. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  475. newNetRes := []types.NetworkResource{}
  476. err = json.Unmarshal([]byte(out), &newNetRes)
  477. c.Assert(err, check.IsNil)
  478. c.Assert(newNetRes, checker.HasLen, 1)
  479. container1, ok := newNetRes[0].Containers[containerID]
  480. c.Assert(ok, checker.True)
  481. c.Assert(container1.Name, checker.Equals, newName)
  482. }
  483. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) {
  484. dockerCmd(c, "network", "create", "test")
  485. assertNwIsAvailable(c, "test")
  486. nr := getNwResource(c, "test")
  487. c.Assert(nr.Name, checker.Equals, "test")
  488. c.Assert(len(nr.Containers), checker.Equals, 0)
  489. // run a container
  490. out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  491. c.Assert(waitRun("test"), check.IsNil)
  492. containerID := strings.TrimSpace(out)
  493. // connect the container to the test network
  494. dockerCmd(c, "network", "connect", "test", containerID)
  495. // inspect the network to make sure container is connected
  496. nr = getNetworkResource(c, nr.ID)
  497. c.Assert(len(nr.Containers), checker.Equals, 1)
  498. c.Assert(nr.Containers[containerID], check.NotNil)
  499. // check if container IP matches network inspect
  500. ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address)
  501. c.Assert(err, check.IsNil)
  502. containerIP := findContainerIP(c, "test", "test")
  503. c.Assert(ip.String(), checker.Equals, containerIP)
  504. // disconnect container from the network
  505. dockerCmd(c, "network", "disconnect", "test", containerID)
  506. nr = getNwResource(c, "test")
  507. c.Assert(nr.Name, checker.Equals, "test")
  508. c.Assert(len(nr.Containers), checker.Equals, 0)
  509. // run another container
  510. out, _ = dockerCmd(c, "run", "-d", "--net", "test", "--name", "test2", "busybox", "top")
  511. c.Assert(waitRun("test2"), check.IsNil)
  512. containerID = strings.TrimSpace(out)
  513. nr = getNwResource(c, "test")
  514. c.Assert(nr.Name, checker.Equals, "test")
  515. c.Assert(len(nr.Containers), checker.Equals, 1)
  516. // force disconnect the container to the test network
  517. dockerCmd(c, "network", "disconnect", "-f", "test", containerID)
  518. nr = getNwResource(c, "test")
  519. c.Assert(nr.Name, checker.Equals, "test")
  520. c.Assert(len(nr.Containers), checker.Equals, 0)
  521. dockerCmd(c, "network", "rm", "test")
  522. assertNwNotAvailable(c, "test")
  523. }
  524. func (s *DockerNetworkSuite) TestDockerNetworkIPAMMultipleNetworks(c *check.C) {
  525. // test0 bridge network
  526. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
  527. assertNwIsAvailable(c, "test1")
  528. // test2 bridge network does not overlap
  529. dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
  530. assertNwIsAvailable(c, "test2")
  531. // for networks w/o ipam specified, docker will choose proper non-overlapping subnets
  532. dockerCmd(c, "network", "create", "test3")
  533. assertNwIsAvailable(c, "test3")
  534. dockerCmd(c, "network", "create", "test4")
  535. assertNwIsAvailable(c, "test4")
  536. dockerCmd(c, "network", "create", "test5")
  537. assertNwIsAvailable(c, "test5")
  538. // test network with multiple subnets
  539. // bridge network doesn't support multiple subnets. hence, use a dummy driver that supports
  540. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6")
  541. assertNwIsAvailable(c, "test6")
  542. // test network with multiple subnets with valid ipam combinations
  543. // also check same subnet across networks when the driver supports it.
  544. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
  545. "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16",
  546. "--gateway=192.168.0.100", "--gateway=192.170.0.100",
  547. "--ip-range=192.168.1.0/24",
  548. "--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6",
  549. "--aux-address", "c=192.170.1.5", "--aux-address", "d=192.170.1.6",
  550. "test7")
  551. assertNwIsAvailable(c, "test7")
  552. // cleanup
  553. for i := 1; i < 8; i++ {
  554. dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
  555. }
  556. }
  557. func (s *DockerNetworkSuite) TestDockerNetworkCustomIPAM(c *check.C) {
  558. // Create a bridge network using custom ipam driver
  559. dockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "br0")
  560. assertNwIsAvailable(c, "br0")
  561. // Verify expected network ipam fields are there
  562. nr := getNetworkResource(c, "br0")
  563. c.Assert(nr.Driver, checker.Equals, "bridge")
  564. c.Assert(nr.IPAM.Driver, checker.Equals, dummyIPAMDriver)
  565. // remove network and exercise remote ipam driver
  566. dockerCmd(c, "network", "rm", "br0")
  567. assertNwNotAvailable(c, "br0")
  568. }
  569. func (s *DockerNetworkSuite) TestDockerNetworkIPAMOptions(c *check.C) {
  570. // Create a bridge network using custom ipam driver and options
  571. dockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "--ipam-opt", "opt1=drv1", "--ipam-opt", "opt2=drv2", "br0")
  572. assertNwIsAvailable(c, "br0")
  573. // Verify expected network ipam options
  574. nr := getNetworkResource(c, "br0")
  575. opts := nr.IPAM.Options
  576. c.Assert(opts["opt1"], checker.Equals, "drv1")
  577. c.Assert(opts["opt2"], checker.Equals, "drv2")
  578. }
  579. func (s *DockerNetworkSuite) TestDockerNetworkInspectDefault(c *check.C) {
  580. nr := getNetworkResource(c, "none")
  581. c.Assert(nr.Driver, checker.Equals, "null")
  582. c.Assert(nr.Scope, checker.Equals, "local")
  583. c.Assert(nr.Internal, checker.Equals, false)
  584. c.Assert(nr.EnableIPv6, checker.Equals, false)
  585. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  586. c.Assert(len(nr.IPAM.Config), checker.Equals, 0)
  587. nr = getNetworkResource(c, "host")
  588. c.Assert(nr.Driver, checker.Equals, "host")
  589. c.Assert(nr.Scope, checker.Equals, "local")
  590. c.Assert(nr.Internal, checker.Equals, false)
  591. c.Assert(nr.EnableIPv6, checker.Equals, false)
  592. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  593. c.Assert(len(nr.IPAM.Config), checker.Equals, 0)
  594. nr = getNetworkResource(c, "bridge")
  595. c.Assert(nr.Driver, checker.Equals, "bridge")
  596. c.Assert(nr.Scope, checker.Equals, "local")
  597. c.Assert(nr.Internal, checker.Equals, false)
  598. c.Assert(nr.EnableIPv6, checker.Equals, false)
  599. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  600. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  601. c.Assert(nr.IPAM.Config[0].Subnet, checker.NotNil)
  602. c.Assert(nr.IPAM.Config[0].Gateway, checker.NotNil)
  603. }
  604. func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomUnspecified(c *check.C) {
  605. // if unspecified, network subnet will be selected from inside preferred pool
  606. dockerCmd(c, "network", "create", "test01")
  607. assertNwIsAvailable(c, "test01")
  608. nr := getNetworkResource(c, "test01")
  609. c.Assert(nr.Driver, checker.Equals, "bridge")
  610. c.Assert(nr.Scope, checker.Equals, "local")
  611. c.Assert(nr.Internal, checker.Equals, false)
  612. c.Assert(nr.EnableIPv6, checker.Equals, false)
  613. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  614. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  615. c.Assert(nr.IPAM.Config[0].Subnet, checker.NotNil)
  616. c.Assert(nr.IPAM.Config[0].Gateway, checker.NotNil)
  617. dockerCmd(c, "network", "rm", "test01")
  618. assertNwNotAvailable(c, "test01")
  619. }
  620. func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomSpecified(c *check.C) {
  621. 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")
  622. assertNwIsAvailable(c, "br0")
  623. nr := getNetworkResource(c, "br0")
  624. c.Assert(nr.Driver, checker.Equals, "bridge")
  625. c.Assert(nr.Scope, checker.Equals, "local")
  626. c.Assert(nr.Internal, checker.Equals, false)
  627. c.Assert(nr.EnableIPv6, checker.Equals, true)
  628. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  629. c.Assert(len(nr.IPAM.Config), checker.Equals, 2)
  630. c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16")
  631. c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24")
  632. c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254")
  633. c.Assert(nr.Internal, checker.False)
  634. dockerCmd(c, "network", "rm", "br0")
  635. assertNwNotAvailable(c, "test01")
  636. }
  637. func (s *DockerNetworkSuite) TestDockerNetworkIPAMInvalidCombinations(c *check.C) {
  638. // network with ip-range out of subnet range
  639. _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
  640. c.Assert(err, check.NotNil)
  641. // network with multiple gateways for a single subnet
  642. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
  643. c.Assert(err, check.NotNil)
  644. // Multiple overlapping subnets in the same network must fail
  645. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
  646. c.Assert(err, check.NotNil)
  647. // overlapping subnets across networks must fail
  648. // create a valid test0 network
  649. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
  650. assertNwIsAvailable(c, "test0")
  651. // create an overlapping test1 network
  652. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
  653. c.Assert(err, check.NotNil)
  654. dockerCmd(c, "network", "rm", "test0")
  655. assertNwNotAvailable(c, "test0")
  656. }
  657. func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) {
  658. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
  659. assertNwIsAvailable(c, "testopt")
  660. gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
  661. c.Assert(gopts, checker.NotNil)
  662. opts, ok := gopts.(map[string]interface{})
  663. c.Assert(ok, checker.Equals, true)
  664. c.Assert(opts["opt1"], checker.Equals, "drv1")
  665. c.Assert(opts["opt2"], checker.Equals, "drv2")
  666. dockerCmd(c, "network", "rm", "testopt")
  667. assertNwNotAvailable(c, "testopt")
  668. }
  669. func (s *DockerNetworkSuite) TestDockerPluginV2NetworkDriver(c *check.C) {
  670. testRequires(c, DaemonIsLinux, IsAmd64, Network)
  671. var (
  672. npName = "tiborvass/test-docker-netplugin"
  673. npTag = "latest"
  674. npNameWithTag = npName + ":" + npTag
  675. )
  676. _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", npNameWithTag)
  677. c.Assert(err, checker.IsNil)
  678. out, _, err := dockerCmdWithError("plugin", "ls")
  679. c.Assert(err, checker.IsNil)
  680. c.Assert(out, checker.Contains, npName)
  681. c.Assert(out, checker.Contains, npTag)
  682. c.Assert(out, checker.Contains, "true")
  683. dockerCmd(c, "network", "create", "-d", npNameWithTag, "v2net")
  684. assertNwIsAvailable(c, "v2net")
  685. dockerCmd(c, "network", "rm", "v2net")
  686. assertNwNotAvailable(c, "v2net")
  687. }
  688. func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *check.C) {
  689. testRequires(c, ExecSupport)
  690. // On default bridge network built-in service discovery should not happen
  691. hostsFile := "/etc/hosts"
  692. bridgeName := "external-bridge"
  693. bridgeIP := "192.169.255.254/24"
  694. createInterface(c, "bridge", bridgeName, bridgeIP)
  695. defer deleteInterface(c, bridgeName)
  696. s.d.StartWithBusybox(c, "--bridge", bridgeName)
  697. defer s.d.Restart(c)
  698. // run two containers and store first container's etc/hosts content
  699. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  700. c.Assert(err, check.IsNil)
  701. cid1 := strings.TrimSpace(out)
  702. defer s.d.Cmd("stop", cid1)
  703. hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  704. c.Assert(err, checker.IsNil)
  705. out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top")
  706. c.Assert(err, check.IsNil)
  707. cid2 := strings.TrimSpace(out)
  708. // verify first container's etc/hosts file has not changed after spawning the second named container
  709. hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  710. c.Assert(err, checker.IsNil)
  711. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  712. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  713. // stop container 2 and verify first container's etc/hosts has not changed
  714. _, err = s.d.Cmd("stop", cid2)
  715. c.Assert(err, check.IsNil)
  716. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  717. c.Assert(err, checker.IsNil)
  718. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  719. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  720. // but discovery is on when connecting to non default bridge network
  721. network := "anotherbridge"
  722. out, err = s.d.Cmd("network", "create", network)
  723. c.Assert(err, check.IsNil, check.Commentf(out))
  724. defer s.d.Cmd("network", "rm", network)
  725. out, err = s.d.Cmd("network", "connect", network, cid1)
  726. c.Assert(err, check.IsNil, check.Commentf(out))
  727. hosts, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  728. c.Assert(err, checker.IsNil)
  729. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  730. c.Assert(err, checker.IsNil)
  731. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  732. check.Commentf("Unexpected %s change on second network connection", hostsFile))
  733. }
  734. func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
  735. testRequires(c, ExecSupport, NotArm)
  736. hostsFile := "/etc/hosts"
  737. cstmBridgeNw := "custom-bridge-nw"
  738. cstmBridgeNw1 := "custom-bridge-nw1"
  739. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw)
  740. assertNwIsAvailable(c, cstmBridgeNw)
  741. // run two anonymous containers and store their etc/hosts content
  742. out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  743. cid1 := strings.TrimSpace(out)
  744. hosts1 := readContainerFileWithExec(c, cid1, hostsFile)
  745. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  746. cid2 := strings.TrimSpace(out)
  747. hosts2 := readContainerFileWithExec(c, cid2, hostsFile)
  748. // verify first container etc/hosts file has not changed
  749. hosts1post := readContainerFileWithExec(c, cid1, hostsFile)
  750. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  751. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  752. // Connect the 2nd container to a new network and verify the
  753. // first container /etc/hosts file still hasn't changed.
  754. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1)
  755. assertNwIsAvailable(c, cstmBridgeNw1)
  756. dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2)
  757. hosts2 = readContainerFileWithExec(c, cid2, hostsFile)
  758. hosts1post = readContainerFileWithExec(c, cid1, hostsFile)
  759. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  760. check.Commentf("Unexpected %s change on container connect", hostsFile))
  761. // start a named container
  762. cName := "AnyName"
  763. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top")
  764. cid3 := strings.TrimSpace(out)
  765. // verify that container 1 and 2 can ping the named container
  766. dockerCmd(c, "exec", cid1, "ping", "-c", "1", cName)
  767. dockerCmd(c, "exec", cid2, "ping", "-c", "1", cName)
  768. // Stop named container and verify first two containers' etc/hosts file hasn't changed
  769. dockerCmd(c, "stop", cid3)
  770. hosts1post = readContainerFileWithExec(c, cid1, hostsFile)
  771. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  772. check.Commentf("Unexpected %s change on name container creation", hostsFile))
  773. hosts2post := readContainerFileWithExec(c, cid2, hostsFile)
  774. c.Assert(string(hosts2), checker.Equals, string(hosts2post),
  775. check.Commentf("Unexpected %s change on name container creation", hostsFile))
  776. // verify that container 1 and 2 can't ping the named container now
  777. _, _, err := dockerCmdWithError("exec", cid1, "ping", "-c", "1", cName)
  778. c.Assert(err, check.NotNil)
  779. _, _, err = dockerCmdWithError("exec", cid2, "ping", "-c", "1", cName)
  780. c.Assert(err, check.NotNil)
  781. }
  782. func (s *DockerNetworkSuite) TestDockerNetworkLinkOnDefaultNetworkOnly(c *check.C) {
  783. // Legacy Link feature must work only on default network, and not across networks
  784. cnt1 := "container1"
  785. cnt2 := "container2"
  786. network := "anotherbridge"
  787. // Run first container on default network
  788. dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top")
  789. // Create another network and run the second container on it
  790. dockerCmd(c, "network", "create", network)
  791. assertNwIsAvailable(c, network)
  792. dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top")
  793. // Try launching a container on default network, linking to the first container. Must succeed
  794. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top")
  795. // Try launching a container on default network, linking to the second container. Must fail
  796. _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  797. c.Assert(err, checker.NotNil)
  798. // Connect second container to default network. Now a container on default network can link to it
  799. dockerCmd(c, "network", "connect", "bridge", cnt2)
  800. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  801. }
  802. func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) {
  803. // Verify exposed ports are present in ps output when running a container on
  804. // a network managed by a driver which does not provide the default gateway
  805. // for the container
  806. nwn := "ov"
  807. ctn := "bb"
  808. port1 := 80
  809. port2 := 443
  810. expose1 := fmt.Sprintf("--expose=%d", port1)
  811. expose2 := fmt.Sprintf("--expose=%d", port2)
  812. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  813. assertNwIsAvailable(c, nwn)
  814. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top")
  815. // Check docker ps o/p for last created container reports the unpublished ports
  816. unpPort1 := fmt.Sprintf("%d/tcp", port1)
  817. unpPort2 := fmt.Sprintf("%d/tcp", port2)
  818. out, _ := dockerCmd(c, "ps", "-n=1")
  819. // Missing unpublished ports in docker ps output
  820. c.Assert(out, checker.Contains, unpPort1)
  821. // Missing unpublished ports in docker ps output
  822. c.Assert(out, checker.Contains, unpPort2)
  823. }
  824. func (s *DockerNetworkSuite) TestDockerNetworkDriverUngracefulRestart(c *check.C) {
  825. testRequires(c, DaemonIsLinux, NotUserNamespace)
  826. dnd := "dnd"
  827. did := "did"
  828. mux := http.NewServeMux()
  829. server := httptest.NewServer(mux)
  830. setupRemoteNetworkDrivers(c, mux, server.URL, dnd, did)
  831. s.d.StartWithBusybox(c)
  832. _, err := s.d.Cmd("network", "create", "-d", dnd, "--subnet", "1.1.1.0/24", "net1")
  833. c.Assert(err, checker.IsNil)
  834. _, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "foo", "--ip", "1.1.1.10", "busybox", "sh")
  835. c.Assert(err, checker.IsNil)
  836. // Kill daemon and restart
  837. c.Assert(s.d.Kill(), checker.IsNil)
  838. server.Close()
  839. startTime := time.Now().Unix()
  840. s.d.Restart(c)
  841. lapse := time.Now().Unix() - startTime
  842. if lapse > 60 {
  843. // In normal scenarios, daemon restart takes ~1 second.
  844. // Plugin retry mechanism can delay the daemon start. systemd may not like it.
  845. // Avoid accessing plugins during daemon bootup
  846. c.Logf("daemon restart took too long : %d seconds", lapse)
  847. }
  848. // Restart the custom dummy plugin
  849. mux = http.NewServeMux()
  850. server = httptest.NewServer(mux)
  851. setupRemoteNetworkDrivers(c, mux, server.URL, dnd, did)
  852. // trying to reuse the same ip must succeed
  853. _, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "bar", "--ip", "1.1.1.10", "busybox", "sh")
  854. c.Assert(err, checker.IsNil)
  855. }
  856. func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) {
  857. // Verify endpoint MAC address is correctly populated in container's network settings
  858. nwn := "ov"
  859. ctn := "bb"
  860. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  861. assertNwIsAvailable(c, nwn)
  862. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top")
  863. mac := inspectField(c, ctn, "NetworkSettings.Networks."+nwn+".MacAddress")
  864. c.Assert(mac, checker.Equals, "a0:b1:c2:d3:e4:f5")
  865. }
  866. func (s *DockerSuite) TestInspectAPIMultipleNetworks(c *check.C) {
  867. dockerCmd(c, "network", "create", "mybridge1")
  868. dockerCmd(c, "network", "create", "mybridge2")
  869. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  870. id := strings.TrimSpace(out)
  871. c.Assert(waitRun(id), check.IsNil)
  872. dockerCmd(c, "network", "connect", "mybridge1", id)
  873. dockerCmd(c, "network", "connect", "mybridge2", id)
  874. body := getInspectBody(c, "v1.20", id)
  875. var inspect120 v1p20.ContainerJSON
  876. err := json.Unmarshal(body, &inspect120)
  877. c.Assert(err, checker.IsNil)
  878. versionedIP := inspect120.NetworkSettings.IPAddress
  879. body = getInspectBody(c, "v1.21", id)
  880. var inspect121 types.ContainerJSON
  881. err = json.Unmarshal(body, &inspect121)
  882. c.Assert(err, checker.IsNil)
  883. c.Assert(inspect121.NetworkSettings.Networks, checker.HasLen, 3)
  884. bridge := inspect121.NetworkSettings.Networks["bridge"]
  885. c.Assert(bridge.IPAddress, checker.Equals, versionedIP)
  886. c.Assert(bridge.IPAddress, checker.Equals, inspect121.NetworkSettings.IPAddress)
  887. }
  888. func connectContainerToNetworks(c *check.C, d *daemon.Daemon, cName string, nws []string) {
  889. // Run a container on the default network
  890. out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
  891. c.Assert(err, checker.IsNil, check.Commentf(out))
  892. // Attach the container to other networks
  893. for _, nw := range nws {
  894. out, err = d.Cmd("network", "create", nw)
  895. c.Assert(err, checker.IsNil, check.Commentf(out))
  896. out, err = d.Cmd("network", "connect", nw, cName)
  897. c.Assert(err, checker.IsNil, check.Commentf(out))
  898. }
  899. }
  900. func verifyContainerIsConnectedToNetworks(c *check.C, d *daemon.Daemon, cName string, nws []string) {
  901. // Verify container is connected to all the networks
  902. for _, nw := range nws {
  903. out, err := d.Cmd("inspect", "-f", fmt.Sprintf("{{.NetworkSettings.Networks.%s}}", nw), cName)
  904. c.Assert(err, checker.IsNil, check.Commentf(out))
  905. c.Assert(out, checker.Not(checker.Equals), "<no value>\n")
  906. }
  907. }
  908. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRestart(c *check.C) {
  909. cName := "bb"
  910. nwList := []string{"nw1", "nw2", "nw3"}
  911. s.d.StartWithBusybox(c)
  912. connectContainerToNetworks(c, s.d, cName, nwList)
  913. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  914. // Reload daemon
  915. s.d.Restart(c)
  916. _, err := s.d.Cmd("start", cName)
  917. c.Assert(err, checker.IsNil)
  918. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  919. }
  920. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksUngracefulDaemonRestart(c *check.C) {
  921. cName := "cc"
  922. nwList := []string{"nw1", "nw2", "nw3"}
  923. s.d.StartWithBusybox(c)
  924. connectContainerToNetworks(c, s.d, cName, nwList)
  925. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  926. // Kill daemon and restart
  927. c.Assert(s.d.Kill(), checker.IsNil)
  928. s.d.Restart(c)
  929. // Restart container
  930. _, err := s.d.Cmd("start", cName)
  931. c.Assert(err, checker.IsNil)
  932. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  933. }
  934. func (s *DockerNetworkSuite) TestDockerNetworkRunNetByID(c *check.C) {
  935. out, _ := dockerCmd(c, "network", "create", "one")
  936. containerOut, _, err := dockerCmdWithError("run", "-d", "--net", strings.TrimSpace(out), "busybox", "top")
  937. c.Assert(err, checker.IsNil, check.Commentf(containerOut))
  938. }
  939. func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c *check.C) {
  940. testRequires(c, DaemonIsLinux, NotUserNamespace)
  941. s.d.StartWithBusybox(c)
  942. // Run a few containers on host network
  943. for i := 0; i < 10; i++ {
  944. cName := fmt.Sprintf("hostc-%d", i)
  945. out, err := s.d.Cmd("run", "-d", "--name", cName, "--net=host", "--restart=always", "busybox", "top")
  946. c.Assert(err, checker.IsNil, check.Commentf(out))
  947. // verfiy container has finished starting before killing daemon
  948. err = s.d.WaitRun(cName)
  949. c.Assert(err, checker.IsNil)
  950. }
  951. // Kill daemon ungracefully and restart
  952. c.Assert(s.d.Kill(), checker.IsNil)
  953. s.d.Restart(c)
  954. // make sure all the containers are up and running
  955. for i := 0; i < 10; i++ {
  956. err := s.d.WaitRun(fmt.Sprintf("hostc-%d", i))
  957. c.Assert(err, checker.IsNil)
  958. }
  959. }
  960. func (s *DockerNetworkSuite) TestDockerNetworkConnectToHostFromOtherNetwork(c *check.C) {
  961. dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
  962. c.Assert(waitRun("container1"), check.IsNil)
  963. dockerCmd(c, "network", "disconnect", "bridge", "container1")
  964. out, _, err := dockerCmdWithError("network", "connect", "host", "container1")
  965. c.Assert(err, checker.NotNil, check.Commentf(out))
  966. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  967. }
  968. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromHost(c *check.C) {
  969. dockerCmd(c, "run", "-d", "--name", "container1", "--net=host", "busybox", "top")
  970. c.Assert(waitRun("container1"), check.IsNil)
  971. out, _, err := dockerCmdWithError("network", "disconnect", "host", "container1")
  972. c.Assert(err, checker.NotNil, check.Commentf("Should err out disconnect from host"))
  973. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  974. }
  975. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithPortMapping(c *check.C) {
  976. testRequires(c, NotArm)
  977. dockerCmd(c, "network", "create", "test1")
  978. dockerCmd(c, "run", "-d", "--name", "c1", "-p", "5000:5000", "busybox", "top")
  979. c.Assert(waitRun("c1"), check.IsNil)
  980. dockerCmd(c, "network", "connect", "test1", "c1")
  981. }
  982. func verifyPortMap(c *check.C, container, port, originalMapping string, mustBeEqual bool) {
  983. chk := checker.Equals
  984. if !mustBeEqual {
  985. chk = checker.Not(checker.Equals)
  986. }
  987. currentMapping, _ := dockerCmd(c, "port", container, port)
  988. c.Assert(currentMapping, chk, originalMapping)
  989. }
  990. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectWithPortMapping(c *check.C) {
  991. // Connect and disconnect a container with explicit and non-explicit
  992. // host port mapping to/from networks which do cause and do not cause
  993. // the container default gateway to change, and verify docker port cmd
  994. // returns congruent information
  995. testRequires(c, NotArm)
  996. cnt := "c1"
  997. dockerCmd(c, "network", "create", "aaa")
  998. dockerCmd(c, "network", "create", "ccc")
  999. dockerCmd(c, "run", "-d", "--name", cnt, "-p", "9000:90", "-p", "70", "busybox", "top")
  1000. c.Assert(waitRun(cnt), check.IsNil)
  1001. curPortMap, _ := dockerCmd(c, "port", cnt, "70")
  1002. curExplPortMap, _ := dockerCmd(c, "port", cnt, "90")
  1003. // Connect to a network which causes the container's default gw switch
  1004. dockerCmd(c, "network", "connect", "aaa", cnt)
  1005. verifyPortMap(c, cnt, "70", curPortMap, false)
  1006. verifyPortMap(c, cnt, "90", curExplPortMap, true)
  1007. // Read current mapping
  1008. curPortMap, _ = dockerCmd(c, "port", cnt, "70")
  1009. // Disconnect from a network which causes the container's default gw switch
  1010. dockerCmd(c, "network", "disconnect", "aaa", cnt)
  1011. verifyPortMap(c, cnt, "70", curPortMap, false)
  1012. verifyPortMap(c, cnt, "90", curExplPortMap, true)
  1013. // Read current mapping
  1014. curPortMap, _ = dockerCmd(c, "port", cnt, "70")
  1015. // Connect to a network which does not cause the container's default gw switch
  1016. dockerCmd(c, "network", "connect", "ccc", cnt)
  1017. verifyPortMap(c, cnt, "70", curPortMap, true)
  1018. verifyPortMap(c, cnt, "90", curExplPortMap, true)
  1019. }
  1020. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithMac(c *check.C) {
  1021. macAddress := "02:42:ac:11:00:02"
  1022. dockerCmd(c, "network", "create", "mynetwork")
  1023. dockerCmd(c, "run", "--name=test", "-d", "--mac-address", macAddress, "busybox", "top")
  1024. c.Assert(waitRun("test"), check.IsNil)
  1025. mac1 := inspectField(c, "test", "NetworkSettings.Networks.bridge.MacAddress")
  1026. c.Assert(strings.TrimSpace(mac1), checker.Equals, macAddress)
  1027. dockerCmd(c, "network", "connect", "mynetwork", "test")
  1028. mac2 := inspectField(c, "test", "NetworkSettings.Networks.mynetwork.MacAddress")
  1029. c.Assert(strings.TrimSpace(mac2), checker.Not(checker.Equals), strings.TrimSpace(mac1))
  1030. }
  1031. func (s *DockerNetworkSuite) TestDockerNetworkInspectCreatedContainer(c *check.C) {
  1032. dockerCmd(c, "create", "--name", "test", "busybox")
  1033. networks := inspectField(c, "test", "NetworkSettings.Networks")
  1034. c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should return 'bridge' network"))
  1035. }
  1036. func (s *DockerNetworkSuite) TestDockerNetworkRestartWithMultipleNetworks(c *check.C) {
  1037. dockerCmd(c, "network", "create", "test")
  1038. dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
  1039. c.Assert(waitRun("foo"), checker.IsNil)
  1040. dockerCmd(c, "network", "connect", "test", "foo")
  1041. dockerCmd(c, "restart", "foo")
  1042. networks := inspectField(c, "foo", "NetworkSettings.Networks")
  1043. c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should contain 'bridge' network"))
  1044. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  1045. }
  1046. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectToStoppedContainer(c *check.C) {
  1047. dockerCmd(c, "network", "create", "test")
  1048. dockerCmd(c, "create", "--name=foo", "busybox", "top")
  1049. dockerCmd(c, "network", "connect", "test", "foo")
  1050. networks := inspectField(c, "foo", "NetworkSettings.Networks")
  1051. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  1052. // Restart docker daemon to test the config has persisted to disk
  1053. s.d.Restart(c)
  1054. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  1055. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  1056. // start the container and test if we can ping it from another container in the same network
  1057. dockerCmd(c, "start", "foo")
  1058. c.Assert(waitRun("foo"), checker.IsNil)
  1059. ip := inspectField(c, "foo", "NetworkSettings.Networks.test.IPAddress")
  1060. ip = strings.TrimSpace(ip)
  1061. dockerCmd(c, "run", "--net=test", "busybox", "sh", "-c", fmt.Sprintf("ping -c 1 %s", ip))
  1062. dockerCmd(c, "stop", "foo")
  1063. // Test disconnect
  1064. dockerCmd(c, "network", "disconnect", "test", "foo")
  1065. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  1066. c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
  1067. // Restart docker daemon to test the config has persisted to disk
  1068. s.d.Restart(c)
  1069. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  1070. c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
  1071. }
  1072. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectContainerNonexistingNetwork(c *check.C) {
  1073. dockerCmd(c, "network", "create", "test")
  1074. dockerCmd(c, "run", "--net=test", "-d", "--name=foo", "busybox", "top")
  1075. networks := inspectField(c, "foo", "NetworkSettings.Networks")
  1076. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  1077. // Stop container and remove network
  1078. dockerCmd(c, "stop", "foo")
  1079. dockerCmd(c, "network", "rm", "test")
  1080. // Test disconnecting stopped container from nonexisting network
  1081. dockerCmd(c, "network", "disconnect", "-f", "test", "foo")
  1082. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  1083. c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
  1084. }
  1085. func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIP(c *check.C) {
  1086. // create two networks
  1087. dockerCmd(c, "network", "create", "--ipv6", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "n0")
  1088. assertNwIsAvailable(c, "n0")
  1089. dockerCmd(c, "network", "create", "--ipv6", "--subnet=172.30.0.0/16", "--ip-range=172.30.5.0/24", "--subnet=2001:db8:abcd::/64", "--ip-range=2001:db8:abcd::/80", "n1")
  1090. assertNwIsAvailable(c, "n1")
  1091. // run a container on first network specifying the ip addresses
  1092. dockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  1093. c.Assert(waitRun("c0"), check.IsNil)
  1094. verifyIPAddressConfig(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  1095. verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  1096. // connect the container to the second network specifying an ip addresses
  1097. dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n1", "c0")
  1098. verifyIPAddressConfig(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  1099. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  1100. // Stop and restart the container
  1101. dockerCmd(c, "stop", "c0")
  1102. dockerCmd(c, "start", "c0")
  1103. // verify requested addresses are applied and configs are still there
  1104. verifyIPAddressConfig(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  1105. verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  1106. verifyIPAddressConfig(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  1107. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  1108. // Still it should fail to connect to the default network with a specified IP (whatever ip)
  1109. out, _, err := dockerCmdWithError("network", "connect", "--ip", "172.21.55.44", "bridge", "c0")
  1110. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1111. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
  1112. }
  1113. func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIPStoppedContainer(c *check.C) {
  1114. // create a container
  1115. dockerCmd(c, "create", "--name", "c0", "busybox", "top")
  1116. // create a network
  1117. dockerCmd(c, "network", "create", "--ipv6", "--subnet=172.30.0.0/16", "--subnet=2001:db8:abcd::/64", "n0")
  1118. assertNwIsAvailable(c, "n0")
  1119. // connect the container to the network specifying an ip addresses
  1120. dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n0", "c0")
  1121. verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  1122. // start the container, verify config has not changed and ip addresses are assigned
  1123. dockerCmd(c, "start", "c0")
  1124. c.Assert(waitRun("c0"), check.IsNil)
  1125. verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  1126. verifyIPAddresses(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  1127. // stop the container and check ip config has not changed
  1128. dockerCmd(c, "stop", "c0")
  1129. verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  1130. }
  1131. func (s *DockerNetworkSuite) TestDockerNetworkUnsupportedRequiredIP(c *check.C) {
  1132. // requested IP is not supported on predefined networks
  1133. for _, mode := range []string{"none", "host", "bridge", "default"} {
  1134. checkUnsupportedNetworkAndIP(c, mode)
  1135. }
  1136. // requested IP is not supported on networks with no user defined subnets
  1137. dockerCmd(c, "network", "create", "n0")
  1138. assertNwIsAvailable(c, "n0")
  1139. out, _, err := dockerCmdWithError("run", "-d", "--ip", "172.28.99.88", "--net", "n0", "busybox", "top")
  1140. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1141. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
  1142. out, _, err = dockerCmdWithError("run", "-d", "--ip6", "2001:db8:1234::9988", "--net", "n0", "busybox", "top")
  1143. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1144. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
  1145. dockerCmd(c, "network", "rm", "n0")
  1146. assertNwNotAvailable(c, "n0")
  1147. }
  1148. func checkUnsupportedNetworkAndIP(c *check.C, nwMode string) {
  1149. out, _, err := dockerCmdWithError("run", "-d", "--net", nwMode, "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  1150. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1151. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
  1152. }
  1153. func verifyIPAddressConfig(c *check.C, cName, nwname, ipv4, ipv6 string) {
  1154. if ipv4 != "" {
  1155. out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAMConfig.IPv4Address", nwname))
  1156. c.Assert(strings.TrimSpace(out), check.Equals, ipv4)
  1157. }
  1158. if ipv6 != "" {
  1159. out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAMConfig.IPv6Address", nwname))
  1160. c.Assert(strings.TrimSpace(out), check.Equals, ipv6)
  1161. }
  1162. }
  1163. func verifyIPAddresses(c *check.C, cName, nwname, ipv4, ipv6 string) {
  1164. out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAddress", nwname))
  1165. c.Assert(strings.TrimSpace(out), check.Equals, ipv4)
  1166. out = inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.GlobalIPv6Address", nwname))
  1167. c.Assert(strings.TrimSpace(out), check.Equals, ipv6)
  1168. }
  1169. func (s *DockerNetworkSuite) TestDockerNetworkConnectLinkLocalIP(c *check.C) {
  1170. // create one test network
  1171. dockerCmd(c, "network", "create", "--ipv6", "--subnet=2001:db8:1234::/64", "n0")
  1172. assertNwIsAvailable(c, "n0")
  1173. // run a container with incorrect link-local address
  1174. _, _, err := dockerCmdWithError("run", "--link-local-ip", "169.253.5.5", "busybox", "top")
  1175. c.Assert(err, check.NotNil)
  1176. _, _, err = dockerCmdWithError("run", "--link-local-ip", "2001:db8::89", "busybox", "top")
  1177. c.Assert(err, check.NotNil)
  1178. // run two containers with link-local ip on the test network
  1179. dockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--link-local-ip", "169.254.7.7", "--link-local-ip", "fe80::254:77", "busybox", "top")
  1180. c.Assert(waitRun("c0"), check.IsNil)
  1181. dockerCmd(c, "run", "-d", "--name", "c1", "--net=n0", "--link-local-ip", "169.254.8.8", "--link-local-ip", "fe80::254:88", "busybox", "top")
  1182. c.Assert(waitRun("c1"), check.IsNil)
  1183. // run a container on the default network and connect it to the test network specifying a link-local address
  1184. dockerCmd(c, "run", "-d", "--name", "c2", "busybox", "top")
  1185. c.Assert(waitRun("c2"), check.IsNil)
  1186. dockerCmd(c, "network", "connect", "--link-local-ip", "169.254.9.9", "n0", "c2")
  1187. // verify the three containers can ping each other via the link-local addresses
  1188. _, _, err = dockerCmdWithError("exec", "c0", "ping", "-c", "1", "169.254.8.8")
  1189. c.Assert(err, check.IsNil)
  1190. _, _, err = dockerCmdWithError("exec", "c1", "ping", "-c", "1", "169.254.9.9")
  1191. c.Assert(err, check.IsNil)
  1192. _, _, err = dockerCmdWithError("exec", "c2", "ping", "-c", "1", "169.254.7.7")
  1193. c.Assert(err, check.IsNil)
  1194. // Stop and restart the three containers
  1195. dockerCmd(c, "stop", "c0")
  1196. dockerCmd(c, "stop", "c1")
  1197. dockerCmd(c, "stop", "c2")
  1198. dockerCmd(c, "start", "c0")
  1199. dockerCmd(c, "start", "c1")
  1200. dockerCmd(c, "start", "c2")
  1201. // verify the ping again
  1202. _, _, err = dockerCmdWithError("exec", "c0", "ping", "-c", "1", "169.254.8.8")
  1203. c.Assert(err, check.IsNil)
  1204. _, _, err = dockerCmdWithError("exec", "c1", "ping", "-c", "1", "169.254.9.9")
  1205. c.Assert(err, check.IsNil)
  1206. _, _, err = dockerCmdWithError("exec", "c2", "ping", "-c", "1", "169.254.7.7")
  1207. c.Assert(err, check.IsNil)
  1208. }
  1209. func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectLink(c *check.C) {
  1210. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  1211. dockerCmd(c, "network", "create", "-d", "bridge", "foo1")
  1212. dockerCmd(c, "network", "create", "-d", "bridge", "foo2")
  1213. dockerCmd(c, "run", "-d", "--net=foo1", "--name=first", "busybox", "top")
  1214. c.Assert(waitRun("first"), check.IsNil)
  1215. // run a container in a user-defined network with a link for an existing container
  1216. // and a link for a container that doesn't exist
  1217. dockerCmd(c, "run", "-d", "--net=foo1", "--name=second", "--link=first:FirstInFoo1",
  1218. "--link=third:bar", "busybox", "top")
  1219. c.Assert(waitRun("second"), check.IsNil)
  1220. // ping to first and its alias FirstInFoo1 must succeed
  1221. _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  1222. c.Assert(err, check.IsNil)
  1223. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1")
  1224. c.Assert(err, check.IsNil)
  1225. // connect first container to foo2 network
  1226. dockerCmd(c, "network", "connect", "foo2", "first")
  1227. // connect second container to foo2 network with a different alias for first container
  1228. dockerCmd(c, "network", "connect", "--link=first:FirstInFoo2", "foo2", "second")
  1229. // ping the new alias in network foo2
  1230. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2")
  1231. c.Assert(err, check.IsNil)
  1232. // disconnect first container from foo1 network
  1233. dockerCmd(c, "network", "disconnect", "foo1", "first")
  1234. // link in foo1 network must fail
  1235. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1")
  1236. c.Assert(err, check.NotNil)
  1237. // link in foo2 network must succeed
  1238. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2")
  1239. c.Assert(err, check.IsNil)
  1240. }
  1241. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectDefault(c *check.C) {
  1242. netWorkName1 := "test1"
  1243. netWorkName2 := "test2"
  1244. containerName := "foo"
  1245. dockerCmd(c, "network", "create", netWorkName1)
  1246. dockerCmd(c, "network", "create", netWorkName2)
  1247. dockerCmd(c, "create", "--name", containerName, "busybox", "top")
  1248. dockerCmd(c, "network", "connect", netWorkName1, containerName)
  1249. dockerCmd(c, "network", "connect", netWorkName2, containerName)
  1250. dockerCmd(c, "network", "disconnect", "bridge", containerName)
  1251. dockerCmd(c, "start", containerName)
  1252. c.Assert(waitRun(containerName), checker.IsNil)
  1253. networks := inspectField(c, containerName, "NetworkSettings.Networks")
  1254. c.Assert(networks, checker.Contains, netWorkName1, check.Commentf(fmt.Sprintf("Should contain '%s' network", netWorkName1)))
  1255. c.Assert(networks, checker.Contains, netWorkName2, check.Commentf(fmt.Sprintf("Should contain '%s' network", netWorkName2)))
  1256. c.Assert(networks, checker.Not(checker.Contains), "bridge", check.Commentf("Should not contain 'bridge' network"))
  1257. }
  1258. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithAliasOnDefaultNetworks(c *check.C) {
  1259. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  1260. defaults := []string{"bridge", "host", "none"}
  1261. out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top")
  1262. containerID := strings.TrimSpace(out)
  1263. for _, net := range defaults {
  1264. res, _, err := dockerCmdWithError("network", "connect", "--alias", "alias"+net, net, containerID)
  1265. c.Assert(err, checker.NotNil)
  1266. c.Assert(res, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
  1267. }
  1268. }
  1269. func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectAlias(c *check.C) {
  1270. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  1271. dockerCmd(c, "network", "create", "-d", "bridge", "net1")
  1272. dockerCmd(c, "network", "create", "-d", "bridge", "net2")
  1273. cid, _ := dockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo", "busybox", "top")
  1274. c.Assert(waitRun("first"), check.IsNil)
  1275. dockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox", "top")
  1276. c.Assert(waitRun("second"), check.IsNil)
  1277. // ping first container and its alias
  1278. _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  1279. c.Assert(err, check.IsNil)
  1280. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
  1281. c.Assert(err, check.IsNil)
  1282. // ping first container's short-id alias
  1283. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid))
  1284. c.Assert(err, check.IsNil)
  1285. // connect first container to net2 network
  1286. dockerCmd(c, "network", "connect", "--alias=bar", "net2", "first")
  1287. // connect second container to foo2 network with a different alias for first container
  1288. dockerCmd(c, "network", "connect", "net2", "second")
  1289. // ping the new alias in network foo2
  1290. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
  1291. c.Assert(err, check.IsNil)
  1292. // disconnect first container from net1 network
  1293. dockerCmd(c, "network", "disconnect", "net1", "first")
  1294. // ping to net1 scoped alias "foo" must fail
  1295. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
  1296. c.Assert(err, check.NotNil)
  1297. // ping to net2 scoped alias "bar" must still succeed
  1298. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
  1299. c.Assert(err, check.IsNil)
  1300. // ping to net2 scoped alias short-id must still succeed
  1301. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid))
  1302. c.Assert(err, check.IsNil)
  1303. // verify the alias option is rejected when running on predefined network
  1304. out, _, err := dockerCmdWithError("run", "--rm", "--name=any", "--net-alias=any", "busybox", "top")
  1305. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1306. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
  1307. // verify the alias option is rejected when connecting to predefined network
  1308. out, _, err = dockerCmdWithError("network", "connect", "--alias=any", "bridge", "first")
  1309. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1310. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
  1311. }
  1312. func (s *DockerSuite) TestUserDefinedNetworkConnectivity(c *check.C) {
  1313. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1314. dockerCmd(c, "network", "create", "-d", "bridge", "br.net1")
  1315. dockerCmd(c, "run", "-d", "--net=br.net1", "--name=c1.net1", "busybox", "top")
  1316. c.Assert(waitRun("c1.net1"), check.IsNil)
  1317. dockerCmd(c, "run", "-d", "--net=br.net1", "--name=c2.net1", "busybox", "top")
  1318. c.Assert(waitRun("c2.net1"), check.IsNil)
  1319. // ping first container by its unqualified name
  1320. _, _, err := dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1")
  1321. c.Assert(err, check.IsNil)
  1322. // ping first container by its qualified name
  1323. _, _, err = dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1.br.net1")
  1324. c.Assert(err, check.IsNil)
  1325. // ping with first qualified name masked by an additional domain. should fail
  1326. _, _, err = dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1.br.net1.google.com")
  1327. c.Assert(err, check.NotNil)
  1328. }
  1329. func (s *DockerSuite) TestEmbeddedDNSInvalidInput(c *check.C) {
  1330. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1331. dockerCmd(c, "network", "create", "-d", "bridge", "nw1")
  1332. // Sending garbage to embedded DNS shouldn't crash the daemon
  1333. dockerCmd(c, "run", "-i", "--net=nw1", "--name=c1", "debian:jessie", "bash", "-c", "echo InvalidQuery > /dev/udp/127.0.0.11/53")
  1334. }
  1335. func (s *DockerSuite) TestDockerNetworkConnectFailsNoInspectChange(c *check.C) {
  1336. dockerCmd(c, "run", "-d", "--name=bb", "busybox", "top")
  1337. c.Assert(waitRun("bb"), check.IsNil)
  1338. ns0 := inspectField(c, "bb", "NetworkSettings.Networks.bridge")
  1339. // A failing redundant network connect should not alter current container's endpoint settings
  1340. _, _, err := dockerCmdWithError("network", "connect", "bridge", "bb")
  1341. c.Assert(err, check.NotNil)
  1342. ns1 := inspectField(c, "bb", "NetworkSettings.Networks.bridge")
  1343. c.Assert(ns1, check.Equals, ns0)
  1344. }
  1345. func (s *DockerSuite) TestDockerNetworkInternalMode(c *check.C) {
  1346. dockerCmd(c, "network", "create", "--driver=bridge", "--internal", "internal")
  1347. assertNwIsAvailable(c, "internal")
  1348. nr := getNetworkResource(c, "internal")
  1349. c.Assert(nr.Internal, checker.True)
  1350. dockerCmd(c, "run", "-d", "--net=internal", "--name=first", "busybox", "top")
  1351. c.Assert(waitRun("first"), check.IsNil)
  1352. dockerCmd(c, "run", "-d", "--net=internal", "--name=second", "busybox", "top")
  1353. c.Assert(waitRun("second"), check.IsNil)
  1354. out, _, err := dockerCmdWithError("exec", "first", "ping", "-W", "4", "-c", "1", "www.google.com")
  1355. c.Assert(err, check.NotNil)
  1356. c.Assert(out, checker.Contains, "ping: bad address")
  1357. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  1358. c.Assert(err, check.IsNil)
  1359. }
  1360. // Test for #21401
  1361. func (s *DockerNetworkSuite) TestDockerNetworkCreateDeleteSpecialCharacters(c *check.C) {
  1362. dockerCmd(c, "network", "create", "test@#$")
  1363. assertNwIsAvailable(c, "test@#$")
  1364. dockerCmd(c, "network", "rm", "test@#$")
  1365. assertNwNotAvailable(c, "test@#$")
  1366. dockerCmd(c, "network", "create", "kiwl$%^")
  1367. assertNwIsAvailable(c, "kiwl$%^")
  1368. dockerCmd(c, "network", "rm", "kiwl$%^")
  1369. assertNwNotAvailable(c, "kiwl$%^")
  1370. }
  1371. func (s *DockerDaemonSuite) TestDaemonRestartRestoreBridgeNetwork(t *check.C) {
  1372. testRequires(t, DaemonIsLinux)
  1373. s.d.StartWithBusybox(t, "--live-restore")
  1374. defer s.d.Stop(t)
  1375. oldCon := "old"
  1376. _, err := s.d.Cmd("run", "-d", "--name", oldCon, "-p", "80:80", "busybox", "top")
  1377. if err != nil {
  1378. t.Fatal(err)
  1379. }
  1380. oldContainerIP, err := s.d.Cmd("inspect", "-f", "{{ .NetworkSettings.Networks.bridge.IPAddress }}", oldCon)
  1381. if err != nil {
  1382. t.Fatal(err)
  1383. }
  1384. // Kill the daemon
  1385. if err := s.d.Kill(); err != nil {
  1386. t.Fatal(err)
  1387. }
  1388. // restart the daemon
  1389. s.d.Start(t, "--live-restore")
  1390. // start a new container, the new container's ip should not be the same with
  1391. // old running container.
  1392. newCon := "new"
  1393. _, err = s.d.Cmd("run", "-d", "--name", newCon, "busybox", "top")
  1394. if err != nil {
  1395. t.Fatal(err)
  1396. }
  1397. newContainerIP, err := s.d.Cmd("inspect", "-f", "{{ .NetworkSettings.Networks.bridge.IPAddress }}", newCon)
  1398. if err != nil {
  1399. t.Fatal(err)
  1400. }
  1401. if strings.Compare(strings.TrimSpace(oldContainerIP), strings.TrimSpace(newContainerIP)) == 0 {
  1402. t.Fatalf("new container ip should not equal to old running container ip")
  1403. }
  1404. // start a new container, the new container should ping old running container
  1405. _, err = s.d.Cmd("run", "-t", "busybox", "ping", "-c", "1", oldContainerIP)
  1406. if err != nil {
  1407. t.Fatal(err)
  1408. }
  1409. // start a new container, trying to publish port 80:80 should fail
  1410. out, err := s.d.Cmd("run", "-p", "80:80", "-d", "busybox", "top")
  1411. if err == nil || !strings.Contains(out, "Bind for 0.0.0.0:80 failed: port is already allocated") {
  1412. t.Fatalf("80 port is allocated to old running container, it should failed on allocating to new container")
  1413. }
  1414. // kill old running container and try to allocate again
  1415. _, err = s.d.Cmd("kill", oldCon)
  1416. if err != nil {
  1417. t.Fatal(err)
  1418. }
  1419. id, err := s.d.Cmd("run", "-p", "80:80", "-d", "busybox", "top")
  1420. if err != nil {
  1421. t.Fatal(err)
  1422. }
  1423. // Cleanup because these containers will not be shut down by daemon
  1424. out, err = s.d.Cmd("stop", newCon)
  1425. if err != nil {
  1426. t.Fatalf("err: %v %v", err, string(out))
  1427. }
  1428. _, err = s.d.Cmd("stop", strings.TrimSpace(id))
  1429. if err != nil {
  1430. t.Fatal(err)
  1431. }
  1432. }
  1433. func (s *DockerNetworkSuite) TestDockerNetworkFlagAlias(c *check.C) {
  1434. dockerCmd(c, "network", "create", "user")
  1435. output, status := dockerCmd(c, "run", "--rm", "--network=user", "--network-alias=foo", "busybox", "true")
  1436. c.Assert(status, checker.Equals, 0, check.Commentf("unexpected status code %d (%s)", status, output))
  1437. output, status, _ = dockerCmdWithError("run", "--rm", "--net=user", "--network=user", "busybox", "true")
  1438. c.Assert(status, checker.Equals, 0, check.Commentf("unexpected status code %d (%s)", status, output))
  1439. output, status, _ = dockerCmdWithError("run", "--rm", "--network=user", "--net-alias=foo", "--network-alias=bar", "busybox", "true")
  1440. c.Assert(status, checker.Equals, 0, check.Commentf("unexpected status code %d (%s)", status, output))
  1441. }
  1442. func (s *DockerNetworkSuite) TestDockerNetworkValidateIP(c *check.C) {
  1443. _, _, err := dockerCmdWithError("network", "create", "--ipv6", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "mynet")
  1444. c.Assert(err, check.IsNil)
  1445. assertNwIsAvailable(c, "mynet")
  1446. _, _, err = dockerCmdWithError("run", "-d", "--name", "mynet0", "--net=mynet", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  1447. c.Assert(err, check.IsNil)
  1448. c.Assert(waitRun("mynet0"), check.IsNil)
  1449. verifyIPAddressConfig(c, "mynet0", "mynet", "172.28.99.88", "2001:db8:1234::9988")
  1450. verifyIPAddresses(c, "mynet0", "mynet", "172.28.99.88", "2001:db8:1234::9988")
  1451. _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip", "mynet_ip", "--ip6", "2001:db8:1234::9999", "busybox", "top")
  1452. c.Assert(err.Error(), checker.Contains, "invalid IPv4 address")
  1453. _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip", "172.28.99.99", "--ip6", "mynet_ip6", "busybox", "top")
  1454. c.Assert(err.Error(), checker.Contains, "invalid IPv6 address")
  1455. // This is a case of IPv4 address to `--ip6`
  1456. _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip6", "172.28.99.99", "busybox", "top")
  1457. c.Assert(err.Error(), checker.Contains, "invalid IPv6 address")
  1458. // This is a special case of an IPv4-mapped IPv6 address
  1459. _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip6", "::ffff:172.28.99.99", "busybox", "top")
  1460. c.Assert(err.Error(), checker.Contains, "invalid IPv6 address")
  1461. }
  1462. // Test case for 26220
  1463. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromBridge(c *check.C) {
  1464. out, _ := dockerCmd(c, "network", "inspect", "--format", "{{.Id}}", "bridge")
  1465. network := strings.TrimSpace(out)
  1466. name := "test"
  1467. dockerCmd(c, "create", "--name", name, "busybox", "top")
  1468. _, _, err := dockerCmdWithError("network", "disconnect", network, name)
  1469. c.Assert(err, check.IsNil)
  1470. }
  1471. // TestConntrackFlowsLeak covers the failure scenario of ticket: https://github.com/docker/docker/issues/8795
  1472. // Validates that conntrack is correctly cleaned once a container is destroyed
  1473. func (s *DockerNetworkSuite) TestConntrackFlowsLeak(c *check.C) {
  1474. testRequires(c, IsAmd64, DaemonIsLinux, Network)
  1475. // Create a new network
  1476. cli.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")
  1477. assertNwIsAvailable(c, "testbind")
  1478. // Launch the server, this will remain listening on an exposed port and reply to any request in a ping/pong fashion
  1479. cmd := "while true; do echo hello | nc -w 1 -lu 8080; done"
  1480. cli.DockerCmd(c, "run", "-d", "--name", "server", "--net", "testbind", "-p", "8080:8080/udp", "appropriate/nc", "sh", "-c", cmd)
  1481. // Launch a container client, here the objective is to create a flow that is natted in order to expose the bug
  1482. cmd = "echo world | nc -q 1 -u 192.168.10.1 8080"
  1483. cli.DockerCmd(c, "run", "-d", "--name", "client", "--net=host", "appropriate/nc", "sh", "-c", cmd)
  1484. // Get all the flows using netlink
  1485. flows, err := netlink.ConntrackTableList(netlink.ConntrackTable, syscall.AF_INET)
  1486. c.Assert(err, check.IsNil)
  1487. var flowMatch int
  1488. for _, flow := range flows {
  1489. // count only the flows that we are interested in, skipping others that can be laying around the host
  1490. if flow.Forward.Protocol == syscall.IPPROTO_UDP &&
  1491. flow.Forward.DstIP.Equal(net.ParseIP("192.168.10.1")) &&
  1492. flow.Forward.DstPort == 8080 {
  1493. flowMatch++
  1494. }
  1495. }
  1496. // The client should have created only 1 flow
  1497. c.Assert(flowMatch, checker.Equals, 1)
  1498. // Now delete the server, this will trigger the conntrack cleanup
  1499. cli.DockerCmd(c, "rm", "-fv", "server")
  1500. // Fetch again all the flows and validate that there is no server flow in the conntrack laying around
  1501. flows, err = netlink.ConntrackTableList(netlink.ConntrackTable, syscall.AF_INET)
  1502. c.Assert(err, check.IsNil)
  1503. flowMatch = 0
  1504. for _, flow := range flows {
  1505. if flow.Forward.Protocol == syscall.IPPROTO_UDP &&
  1506. flow.Forward.DstIP.Equal(net.ParseIP("192.168.10.1")) &&
  1507. flow.Forward.DstPort == 8080 {
  1508. flowMatch++
  1509. }
  1510. }
  1511. // All the flows have to be gone
  1512. c.Assert(flowMatch, checker.Equals, 0)
  1513. }