docker_cli_network_unix_test.go 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  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. "strings"
  12. "time"
  13. "github.com/docker/docker/pkg/integration/checker"
  14. "github.com/docker/docker/runconfig"
  15. "github.com/docker/engine-api/types"
  16. "github.com/docker/engine-api/types/versions/v1p20"
  17. "github.com/docker/libnetwork/driverapi"
  18. remoteapi "github.com/docker/libnetwork/drivers/remote/api"
  19. "github.com/docker/libnetwork/ipamapi"
  20. remoteipam "github.com/docker/libnetwork/ipams/remote/api"
  21. "github.com/docker/libnetwork/netlabel"
  22. "github.com/go-check/check"
  23. "github.com/vishvananda/netlink"
  24. )
  25. const dummyNetworkDriver = "dummy-network-driver"
  26. const dummyIpamDriver = "dummy-ipam-driver"
  27. var remoteDriverNetworkRequest remoteapi.CreateNetworkRequest
  28. func init() {
  29. check.Suite(&DockerNetworkSuite{
  30. ds: &DockerSuite{},
  31. })
  32. }
  33. type DockerNetworkSuite struct {
  34. server *httptest.Server
  35. ds *DockerSuite
  36. d *Daemon
  37. }
  38. func (s *DockerNetworkSuite) SetUpTest(c *check.C) {
  39. s.d = NewDaemon(c)
  40. }
  41. func (s *DockerNetworkSuite) TearDownTest(c *check.C) {
  42. s.d.Stop()
  43. s.ds.TearDownTest(c)
  44. }
  45. func (s *DockerNetworkSuite) SetUpSuite(c *check.C) {
  46. mux := http.NewServeMux()
  47. s.server = httptest.NewServer(mux)
  48. c.Assert(s.server, check.NotNil, check.Commentf("Failed to start a HTTP Server"))
  49. setupRemoteNetworkDrivers(c, mux, s.server.URL, dummyNetworkDriver, dummyIpamDriver)
  50. }
  51. func setupRemoteNetworkDrivers(c *check.C, mux *http.ServeMux, url, netDrv, ipamDrv string) {
  52. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  53. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  54. fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType)
  55. })
  56. // Network driver implementation
  57. mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  58. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  59. fmt.Fprintf(w, `{"Scope":"local"}`)
  60. })
  61. mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  62. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  63. if err != nil {
  64. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  65. return
  66. }
  67. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  68. fmt.Fprintf(w, "null")
  69. })
  70. mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  71. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  72. fmt.Fprintf(w, "null")
  73. })
  74. mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  75. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  76. fmt.Fprintf(w, `{"Interface":{"MacAddress":"a0:b1:c2:d3:e4:f5"}}`)
  77. })
  78. mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  79. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  80. veth := &netlink.Veth{
  81. LinkAttrs: netlink.LinkAttrs{Name: "randomIfName", TxQLen: 0}, PeerName: "cnt0"}
  82. if err := netlink.LinkAdd(veth); err != nil {
  83. fmt.Fprintf(w, `{"Error":"failed to add veth pair: `+err.Error()+`"}`)
  84. } else {
  85. fmt.Fprintf(w, `{"InterfaceName":{ "SrcName":"cnt0", "DstPrefix":"veth"}}`)
  86. }
  87. })
  88. mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  89. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  90. fmt.Fprintf(w, "null")
  91. })
  92. mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  93. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  94. if link, err := netlink.LinkByName("cnt0"); err == nil {
  95. netlink.LinkDel(link)
  96. }
  97. fmt.Fprintf(w, "null")
  98. })
  99. // Ipam Driver implementation
  100. var (
  101. poolRequest remoteipam.RequestPoolRequest
  102. poolReleaseReq remoteipam.ReleasePoolRequest
  103. addressRequest remoteipam.RequestAddressRequest
  104. addressReleaseReq remoteipam.ReleaseAddressRequest
  105. lAS = "localAS"
  106. gAS = "globalAS"
  107. pool = "172.28.0.0/16"
  108. poolID = lAS + "/" + pool
  109. gw = "172.28.255.254/16"
  110. )
  111. mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  112. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  113. fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`)
  114. })
  115. mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  116. err := json.NewDecoder(r.Body).Decode(&poolRequest)
  117. if err != nil {
  118. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  119. return
  120. }
  121. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  122. if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS {
  123. fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`)
  124. } else if poolRequest.Pool != "" && poolRequest.Pool != pool {
  125. fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`)
  126. } else {
  127. fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`)
  128. }
  129. })
  130. mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  131. err := json.NewDecoder(r.Body).Decode(&addressRequest)
  132. if err != nil {
  133. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  134. return
  135. }
  136. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  137. // make sure libnetwork is now querying on the expected pool id
  138. if addressRequest.PoolID != poolID {
  139. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  140. } else if addressRequest.Address != "" {
  141. fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`)
  142. } else {
  143. fmt.Fprintf(w, `{"Address":"`+gw+`"}`)
  144. }
  145. })
  146. mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  147. err := json.NewDecoder(r.Body).Decode(&addressReleaseReq)
  148. if err != nil {
  149. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  150. return
  151. }
  152. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  153. // make sure libnetwork is now asking to release the expected address from the expected poolid
  154. if addressRequest.PoolID != poolID {
  155. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  156. } else if addressReleaseReq.Address != gw {
  157. fmt.Fprintf(w, `{"Error":"unknown address"}`)
  158. } else {
  159. fmt.Fprintf(w, "null")
  160. }
  161. })
  162. mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  163. err := json.NewDecoder(r.Body).Decode(&poolReleaseReq)
  164. if err != nil {
  165. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  166. return
  167. }
  168. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  169. // make sure libnetwork is now asking to release the expected poolid
  170. if addressRequest.PoolID != poolID {
  171. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  172. } else {
  173. fmt.Fprintf(w, "null")
  174. }
  175. })
  176. err := os.MkdirAll("/etc/docker/plugins", 0755)
  177. c.Assert(err, checker.IsNil)
  178. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", netDrv)
  179. err = ioutil.WriteFile(fileName, []byte(url), 0644)
  180. c.Assert(err, checker.IsNil)
  181. ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", ipamDrv)
  182. err = ioutil.WriteFile(ipamFileName, []byte(url), 0644)
  183. c.Assert(err, checker.IsNil)
  184. }
  185. func (s *DockerNetworkSuite) TearDownSuite(c *check.C) {
  186. if s.server == nil {
  187. return
  188. }
  189. s.server.Close()
  190. err := os.RemoveAll("/etc/docker/plugins")
  191. c.Assert(err, checker.IsNil)
  192. }
  193. func assertNwIsAvailable(c *check.C, name string) {
  194. if !isNwPresent(c, name) {
  195. c.Fatalf("Network %s not found in network ls o/p", name)
  196. }
  197. }
  198. func assertNwNotAvailable(c *check.C, name string) {
  199. if isNwPresent(c, name) {
  200. c.Fatalf("Found network %s in network ls o/p", name)
  201. }
  202. }
  203. func isNwPresent(c *check.C, name string) bool {
  204. out, _ := dockerCmd(c, "network", "ls")
  205. lines := strings.Split(out, "\n")
  206. for i := 1; i < len(lines)-1; i++ {
  207. netFields := strings.Fields(lines[i])
  208. if netFields[1] == name {
  209. return true
  210. }
  211. }
  212. return false
  213. }
  214. // assertNwList checks network list retrieved with ls command
  215. // equals to expected network list
  216. // note: out should be `network ls [option]` result
  217. func assertNwList(c *check.C, out string, expectNws []string) {
  218. lines := strings.Split(out, "\n")
  219. var nwList []string
  220. for _, line := range lines[1 : len(lines)-1] {
  221. netFields := strings.Fields(line)
  222. // wrap all network name in nwList
  223. nwList = append(nwList, netFields[1])
  224. }
  225. // network ls should contains all expected networks
  226. c.Assert(nwList, checker.DeepEquals, expectNws)
  227. }
  228. func getNwResource(c *check.C, name string) *types.NetworkResource {
  229. out, _ := dockerCmd(c, "network", "inspect", name)
  230. nr := []types.NetworkResource{}
  231. err := json.Unmarshal([]byte(out), &nr)
  232. c.Assert(err, check.IsNil)
  233. return &nr[0]
  234. }
  235. func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) {
  236. defaults := []string{"bridge", "host", "none"}
  237. for _, nn := range defaults {
  238. assertNwIsAvailable(c, nn)
  239. }
  240. }
  241. func (s *DockerNetworkSuite) TestDockerNetworkCreatePredefined(c *check.C) {
  242. predefined := []string{"bridge", "host", "none", "default"}
  243. for _, net := range predefined {
  244. // predefined networks can't be created again
  245. out, _, err := dockerCmdWithError("network", "create", net)
  246. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  247. }
  248. }
  249. func (s *DockerNetworkSuite) TestDockerNetworkCreateHostBind(c *check.C) {
  250. 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")
  251. assertNwIsAvailable(c, "testbind")
  252. out, _ := runSleepingContainer(c, "--net=testbind", "-p", "5000:5000")
  253. id := strings.TrimSpace(out)
  254. c.Assert(waitRun(id), checker.IsNil)
  255. out, _ = dockerCmd(c, "ps")
  256. c.Assert(out, checker.Contains, "192.168.10.1:5000->5000/tcp")
  257. }
  258. func (s *DockerNetworkSuite) TestDockerNetworkRmPredefined(c *check.C) {
  259. predefined := []string{"bridge", "host", "none", "default"}
  260. for _, net := range predefined {
  261. // predefined networks can't be removed
  262. out, _, err := dockerCmdWithError("network", "rm", net)
  263. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  264. }
  265. }
  266. func (s *DockerNetworkSuite) TestDockerNetworkLsFilter(c *check.C) {
  267. out, _ := dockerCmd(c, "network", "create", "dev")
  268. defer func() {
  269. dockerCmd(c, "network", "rm", "dev")
  270. }()
  271. networkID := strings.TrimSpace(out)
  272. // filter with partial ID and partial name
  273. // only show 'bridge' and 'dev' network
  274. out, _ = dockerCmd(c, "network", "ls", "-f", "id="+networkID[0:5], "-f", "name=dge")
  275. assertNwList(c, out, []string{"bridge", "dev"})
  276. // only show built-in network (bridge, none, host)
  277. out, _ = dockerCmd(c, "network", "ls", "-f", "type=builtin")
  278. assertNwList(c, out, []string{"bridge", "host", "none"})
  279. // only show custom networks (dev)
  280. out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom")
  281. assertNwList(c, out, []string{"dev"})
  282. // show all networks with filter
  283. // it should be equivalent of ls without option
  284. out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom", "-f", "type=builtin")
  285. assertNwList(c, out, []string{"bridge", "dev", "host", "none"})
  286. }
  287. func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *check.C) {
  288. dockerCmd(c, "network", "create", "test")
  289. assertNwIsAvailable(c, "test")
  290. dockerCmd(c, "network", "rm", "test")
  291. assertNwNotAvailable(c, "test")
  292. }
  293. func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *check.C) {
  294. out, _, err := dockerCmdWithError("network", "rm", "test")
  295. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  296. }
  297. func (s *DockerSuite) TestDockerNetworkDeleteMultiple(c *check.C) {
  298. dockerCmd(c, "network", "create", "testDelMulti0")
  299. assertNwIsAvailable(c, "testDelMulti0")
  300. dockerCmd(c, "network", "create", "testDelMulti1")
  301. assertNwIsAvailable(c, "testDelMulti1")
  302. dockerCmd(c, "network", "create", "testDelMulti2")
  303. assertNwIsAvailable(c, "testDelMulti2")
  304. out, _ := dockerCmd(c, "run", "-d", "--net", "testDelMulti2", "busybox", "top")
  305. containerID := strings.TrimSpace(out)
  306. waitRun(containerID)
  307. // delete three networks at the same time, since testDelMulti2
  308. // contains active container, its deletion should fail.
  309. out, _, err := dockerCmdWithError("network", "rm", "testDelMulti0", "testDelMulti1", "testDelMulti2")
  310. // err should not be nil due to deleting testDelMulti2 failed.
  311. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  312. // testDelMulti2 should fail due to network has active endpoints
  313. c.Assert(out, checker.Contains, "has active endpoints")
  314. assertNwNotAvailable(c, "testDelMulti0")
  315. assertNwNotAvailable(c, "testDelMulti1")
  316. // testDelMulti2 can't be deleted, so it should exist
  317. assertNwIsAvailable(c, "testDelMulti2")
  318. }
  319. func (s *DockerSuite) TestDockerNetworkInspect(c *check.C) {
  320. out, _ := dockerCmd(c, "network", "inspect", "host")
  321. networkResources := []types.NetworkResource{}
  322. err := json.Unmarshal([]byte(out), &networkResources)
  323. c.Assert(err, check.IsNil)
  324. c.Assert(networkResources, checker.HasLen, 1)
  325. out, _ = dockerCmd(c, "network", "inspect", "--format='{{ .Name }}'", "host")
  326. c.Assert(strings.TrimSpace(out), check.Equals, "host")
  327. }
  328. func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) {
  329. out, _ := dockerCmd(c, "network", "inspect", "host", "none")
  330. networkResources := []types.NetworkResource{}
  331. err := json.Unmarshal([]byte(out), &networkResources)
  332. c.Assert(err, check.IsNil)
  333. c.Assert(networkResources, checker.HasLen, 2)
  334. // Should print an error, return an exitCode 1 *but* should print the host network
  335. out, exitCode, err := dockerCmdWithError("network", "inspect", "host", "nonexistent")
  336. c.Assert(err, checker.NotNil)
  337. c.Assert(exitCode, checker.Equals, 1)
  338. c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
  339. networkResources = []types.NetworkResource{}
  340. inspectOut := strings.SplitN(out, "\nError: No such network: nonexistent\n", 2)[0]
  341. err = json.Unmarshal([]byte(inspectOut), &networkResources)
  342. c.Assert(networkResources, checker.HasLen, 1)
  343. // Should print an error and return an exitCode, nothing else
  344. out, exitCode, err = dockerCmdWithError("network", "inspect", "nonexistent")
  345. c.Assert(err, checker.NotNil)
  346. c.Assert(exitCode, checker.Equals, 1)
  347. c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
  348. }
  349. func (s *DockerSuite) TestDockerInspectNetworkWithContainerName(c *check.C) {
  350. dockerCmd(c, "network", "create", "brNetForInspect")
  351. assertNwIsAvailable(c, "brNetForInspect")
  352. defer func() {
  353. dockerCmd(c, "network", "rm", "brNetForInspect")
  354. assertNwNotAvailable(c, "brNetForInspect")
  355. }()
  356. out, _ := dockerCmd(c, "run", "-d", "--name", "testNetInspect1", "--net", "brNetForInspect", "busybox", "top")
  357. c.Assert(waitRun("testNetInspect1"), check.IsNil)
  358. containerID := strings.TrimSpace(out)
  359. defer func() {
  360. // we don't stop container by name, because we'll rename it later
  361. dockerCmd(c, "stop", containerID)
  362. }()
  363. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  364. networkResources := []types.NetworkResource{}
  365. err := json.Unmarshal([]byte(out), &networkResources)
  366. c.Assert(err, check.IsNil)
  367. c.Assert(networkResources, checker.HasLen, 1)
  368. container, ok := networkResources[0].Containers[containerID]
  369. c.Assert(ok, checker.True)
  370. c.Assert(container.Name, checker.Equals, "testNetInspect1")
  371. // rename container and check docker inspect output update
  372. newName := "HappyNewName"
  373. dockerCmd(c, "rename", "testNetInspect1", newName)
  374. // check whether network inspect works properly
  375. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  376. newNetRes := []types.NetworkResource{}
  377. err = json.Unmarshal([]byte(out), &newNetRes)
  378. c.Assert(err, check.IsNil)
  379. c.Assert(newNetRes, checker.HasLen, 1)
  380. container1, ok := newNetRes[0].Containers[containerID]
  381. c.Assert(ok, checker.True)
  382. c.Assert(container1.Name, checker.Equals, newName)
  383. }
  384. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) {
  385. dockerCmd(c, "network", "create", "test")
  386. assertNwIsAvailable(c, "test")
  387. nr := getNwResource(c, "test")
  388. c.Assert(nr.Name, checker.Equals, "test")
  389. c.Assert(len(nr.Containers), checker.Equals, 0)
  390. // run a container
  391. out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  392. c.Assert(waitRun("test"), check.IsNil)
  393. containerID := strings.TrimSpace(out)
  394. // connect the container to the test network
  395. dockerCmd(c, "network", "connect", "test", containerID)
  396. // inspect the network to make sure container is connected
  397. nr = getNetworkResource(c, nr.ID)
  398. c.Assert(len(nr.Containers), checker.Equals, 1)
  399. c.Assert(nr.Containers[containerID], check.NotNil)
  400. // check if container IP matches network inspect
  401. ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address)
  402. c.Assert(err, check.IsNil)
  403. containerIP := findContainerIP(c, "test", "test")
  404. c.Assert(ip.String(), checker.Equals, containerIP)
  405. // disconnect container from the network
  406. dockerCmd(c, "network", "disconnect", "test", containerID)
  407. nr = getNwResource(c, "test")
  408. c.Assert(nr.Name, checker.Equals, "test")
  409. c.Assert(len(nr.Containers), checker.Equals, 0)
  410. // run another container
  411. out, _ = dockerCmd(c, "run", "-d", "--net", "test", "--name", "test2", "busybox", "top")
  412. c.Assert(waitRun("test2"), check.IsNil)
  413. containerID = strings.TrimSpace(out)
  414. nr = getNwResource(c, "test")
  415. c.Assert(nr.Name, checker.Equals, "test")
  416. c.Assert(len(nr.Containers), checker.Equals, 1)
  417. // force disconnect the container to the test network
  418. dockerCmd(c, "network", "disconnect", "-f", "test", containerID)
  419. nr = getNwResource(c, "test")
  420. c.Assert(nr.Name, checker.Equals, "test")
  421. c.Assert(len(nr.Containers), checker.Equals, 0)
  422. dockerCmd(c, "network", "rm", "test")
  423. assertNwNotAvailable(c, "test")
  424. }
  425. func (s *DockerNetworkSuite) TestDockerNetworkIpamMultipleNetworks(c *check.C) {
  426. // test0 bridge network
  427. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
  428. assertNwIsAvailable(c, "test1")
  429. // test2 bridge network does not overlap
  430. dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
  431. assertNwIsAvailable(c, "test2")
  432. // for networks w/o ipam specified, docker will choose proper non-overlapping subnets
  433. dockerCmd(c, "network", "create", "test3")
  434. assertNwIsAvailable(c, "test3")
  435. dockerCmd(c, "network", "create", "test4")
  436. assertNwIsAvailable(c, "test4")
  437. dockerCmd(c, "network", "create", "test5")
  438. assertNwIsAvailable(c, "test5")
  439. // test network with multiple subnets
  440. // bridge network doesn't support multiple subnets. hence, use a dummy driver that supports
  441. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6")
  442. assertNwIsAvailable(c, "test6")
  443. // test network with multiple subnets with valid ipam combinations
  444. // also check same subnet across networks when the driver supports it.
  445. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
  446. "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16",
  447. "--gateway=192.168.0.100", "--gateway=192.170.0.100",
  448. "--ip-range=192.168.1.0/24",
  449. "--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6",
  450. "--aux-address", "a=192.170.1.5", "--aux-address", "b=192.170.1.6",
  451. "test7")
  452. assertNwIsAvailable(c, "test7")
  453. // cleanup
  454. for i := 1; i < 8; i++ {
  455. dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
  456. }
  457. }
  458. func (s *DockerNetworkSuite) TestDockerNetworkCustomIpam(c *check.C) {
  459. // Create a bridge network using custom ipam driver
  460. dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "br0")
  461. assertNwIsAvailable(c, "br0")
  462. // Verify expected network ipam fields are there
  463. nr := getNetworkResource(c, "br0")
  464. c.Assert(nr.Driver, checker.Equals, "bridge")
  465. c.Assert(nr.IPAM.Driver, checker.Equals, dummyIpamDriver)
  466. // remove network and exercise remote ipam driver
  467. dockerCmd(c, "network", "rm", "br0")
  468. assertNwNotAvailable(c, "br0")
  469. }
  470. func (s *DockerNetworkSuite) TestDockerNetworkIpamOptions(c *check.C) {
  471. // Create a bridge network using custom ipam driver and options
  472. dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "--ipam-opt", "opt1=drv1", "--ipam-opt", "opt2=drv2", "br0")
  473. assertNwIsAvailable(c, "br0")
  474. // Verify expected network ipam options
  475. nr := getNetworkResource(c, "br0")
  476. opts := nr.IPAM.Options
  477. c.Assert(opts["opt1"], checker.Equals, "drv1")
  478. c.Assert(opts["opt2"], checker.Equals, "drv2")
  479. }
  480. func (s *DockerNetworkSuite) TestDockerNetworkInspectDefault(c *check.C) {
  481. nr := getNetworkResource(c, "none")
  482. c.Assert(nr.Driver, checker.Equals, "null")
  483. c.Assert(nr.Scope, checker.Equals, "local")
  484. c.Assert(nr.Internal, checker.Equals, false)
  485. c.Assert(nr.EnableIPv6, checker.Equals, false)
  486. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  487. c.Assert(len(nr.IPAM.Config), checker.Equals, 0)
  488. nr = getNetworkResource(c, "host")
  489. c.Assert(nr.Driver, checker.Equals, "host")
  490. c.Assert(nr.Scope, checker.Equals, "local")
  491. c.Assert(nr.Internal, checker.Equals, false)
  492. c.Assert(nr.EnableIPv6, checker.Equals, false)
  493. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  494. c.Assert(len(nr.IPAM.Config), checker.Equals, 0)
  495. nr = getNetworkResource(c, "bridge")
  496. c.Assert(nr.Driver, checker.Equals, "bridge")
  497. c.Assert(nr.Scope, checker.Equals, "local")
  498. c.Assert(nr.Internal, checker.Equals, false)
  499. c.Assert(nr.EnableIPv6, checker.Equals, false)
  500. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  501. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  502. c.Assert(nr.IPAM.Config[0].Subnet, checker.NotNil)
  503. c.Assert(nr.IPAM.Config[0].Gateway, checker.NotNil)
  504. }
  505. func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomUnspecified(c *check.C) {
  506. // if unspecified, network subnet will be selected from inside preferred pool
  507. dockerCmd(c, "network", "create", "test01")
  508. assertNwIsAvailable(c, "test01")
  509. nr := getNetworkResource(c, "test01")
  510. c.Assert(nr.Driver, checker.Equals, "bridge")
  511. c.Assert(nr.Scope, checker.Equals, "local")
  512. c.Assert(nr.Internal, checker.Equals, false)
  513. c.Assert(nr.EnableIPv6, checker.Equals, false)
  514. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  515. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  516. c.Assert(nr.IPAM.Config[0].Subnet, checker.NotNil)
  517. c.Assert(nr.IPAM.Config[0].Gateway, checker.NotNil)
  518. dockerCmd(c, "network", "rm", "test01")
  519. assertNwNotAvailable(c, "test01")
  520. }
  521. func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomSpecified(c *check.C) {
  522. dockerCmd(c, "network", "create", "--driver=bridge", "--ipv6", "--subnet=172.28.0.0/16", "--ip-range=172.28.5.0/24", "--gateway=172.28.5.254", "br0")
  523. assertNwIsAvailable(c, "br0")
  524. nr := getNetworkResource(c, "br0")
  525. c.Assert(nr.Driver, checker.Equals, "bridge")
  526. c.Assert(nr.Scope, checker.Equals, "local")
  527. c.Assert(nr.Internal, checker.Equals, false)
  528. c.Assert(nr.EnableIPv6, checker.Equals, true)
  529. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  530. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  531. c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16")
  532. c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24")
  533. c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254")
  534. c.Assert(nr.Internal, checker.False)
  535. dockerCmd(c, "network", "rm", "br0")
  536. assertNwNotAvailable(c, "test01")
  537. }
  538. func (s *DockerNetworkSuite) TestDockerNetworkIpamInvalidCombinations(c *check.C) {
  539. // network with ip-range out of subnet range
  540. _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
  541. c.Assert(err, check.NotNil)
  542. // network with multiple gateways for a single subnet
  543. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
  544. c.Assert(err, check.NotNil)
  545. // Multiple overlapping subnets in the same network must fail
  546. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
  547. c.Assert(err, check.NotNil)
  548. // overlapping subnets across networks must fail
  549. // create a valid test0 network
  550. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
  551. assertNwIsAvailable(c, "test0")
  552. // create an overlapping test1 network
  553. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
  554. c.Assert(err, check.NotNil)
  555. dockerCmd(c, "network", "rm", "test0")
  556. assertNwNotAvailable(c, "test0")
  557. }
  558. func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) {
  559. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
  560. assertNwIsAvailable(c, "testopt")
  561. gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
  562. c.Assert(gopts, checker.NotNil)
  563. opts, ok := gopts.(map[string]interface{})
  564. c.Assert(ok, checker.Equals, true)
  565. c.Assert(opts["opt1"], checker.Equals, "drv1")
  566. c.Assert(opts["opt2"], checker.Equals, "drv2")
  567. dockerCmd(c, "network", "rm", "testopt")
  568. assertNwNotAvailable(c, "testopt")
  569. }
  570. func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *check.C) {
  571. testRequires(c, ExecSupport)
  572. // On default bridge network built-in service discovery should not happen
  573. hostsFile := "/etc/hosts"
  574. bridgeName := "external-bridge"
  575. bridgeIP := "192.169.255.254/24"
  576. out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
  577. c.Assert(err, check.IsNil, check.Commentf(out))
  578. defer deleteInterface(c, bridgeName)
  579. err = s.d.StartWithBusybox("--bridge", bridgeName)
  580. c.Assert(err, check.IsNil)
  581. defer s.d.Restart()
  582. // run two containers and store first container's etc/hosts content
  583. out, err = s.d.Cmd("run", "-d", "busybox", "top")
  584. c.Assert(err, check.IsNil)
  585. cid1 := strings.TrimSpace(out)
  586. defer s.d.Cmd("stop", cid1)
  587. hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  588. c.Assert(err, checker.IsNil)
  589. out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top")
  590. c.Assert(err, check.IsNil)
  591. cid2 := strings.TrimSpace(out)
  592. // verify first container's etc/hosts file has not changed after spawning the second named container
  593. hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  594. c.Assert(err, checker.IsNil)
  595. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  596. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  597. // stop container 2 and verify first container's etc/hosts has not changed
  598. _, err = s.d.Cmd("stop", cid2)
  599. c.Assert(err, check.IsNil)
  600. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  601. c.Assert(err, checker.IsNil)
  602. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  603. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  604. // but discovery is on when connecting to non default bridge network
  605. network := "anotherbridge"
  606. out, err = s.d.Cmd("network", "create", network)
  607. c.Assert(err, check.IsNil, check.Commentf(out))
  608. defer s.d.Cmd("network", "rm", network)
  609. out, err = s.d.Cmd("network", "connect", network, cid1)
  610. c.Assert(err, check.IsNil, check.Commentf(out))
  611. hosts, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  612. c.Assert(err, checker.IsNil)
  613. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  614. c.Assert(err, checker.IsNil)
  615. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  616. check.Commentf("Unexpected %s change on second network connection", hostsFile))
  617. }
  618. func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
  619. testRequires(c, ExecSupport, NotArm)
  620. hostsFile := "/etc/hosts"
  621. cstmBridgeNw := "custom-bridge-nw"
  622. cstmBridgeNw1 := "custom-bridge-nw1"
  623. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw)
  624. assertNwIsAvailable(c, cstmBridgeNw)
  625. // run two anonymous containers and store their etc/hosts content
  626. out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  627. cid1 := strings.TrimSpace(out)
  628. hosts1, err := readContainerFileWithExec(cid1, hostsFile)
  629. c.Assert(err, checker.IsNil)
  630. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  631. cid2 := strings.TrimSpace(out)
  632. hosts2, err := readContainerFileWithExec(cid2, hostsFile)
  633. c.Assert(err, checker.IsNil)
  634. // verify first container etc/hosts file has not changed
  635. hosts1post, err := readContainerFileWithExec(cid1, hostsFile)
  636. c.Assert(err, checker.IsNil)
  637. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  638. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  639. // Connect the 2nd container to a new network and verify the
  640. // first container /etc/hosts file still hasn't changed.
  641. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1)
  642. assertNwIsAvailable(c, cstmBridgeNw1)
  643. dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2)
  644. hosts2, err = readContainerFileWithExec(cid2, hostsFile)
  645. c.Assert(err, checker.IsNil)
  646. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  647. c.Assert(err, checker.IsNil)
  648. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  649. check.Commentf("Unexpected %s change on container connect", hostsFile))
  650. // start a named container
  651. cName := "AnyName"
  652. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top")
  653. cid3 := strings.TrimSpace(out)
  654. // verify that container 1 and 2 can ping the named container
  655. dockerCmd(c, "exec", cid1, "ping", "-c", "1", cName)
  656. dockerCmd(c, "exec", cid2, "ping", "-c", "1", cName)
  657. // Stop named container and verify first two containers' etc/hosts file hasn't changed
  658. dockerCmd(c, "stop", cid3)
  659. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  660. c.Assert(err, checker.IsNil)
  661. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  662. check.Commentf("Unexpected %s change on name container creation", hostsFile))
  663. hosts2post, err := readContainerFileWithExec(cid2, hostsFile)
  664. c.Assert(err, checker.IsNil)
  665. c.Assert(string(hosts2), checker.Equals, string(hosts2post),
  666. check.Commentf("Unexpected %s change on name container creation", hostsFile))
  667. // verify that container 1 and 2 can't ping the named container now
  668. _, _, err = dockerCmdWithError("exec", cid1, "ping", "-c", "1", cName)
  669. c.Assert(err, check.NotNil)
  670. _, _, err = dockerCmdWithError("exec", cid2, "ping", "-c", "1", cName)
  671. c.Assert(err, check.NotNil)
  672. }
  673. func (s *DockerNetworkSuite) TestDockerNetworkLinkOnDefaultNetworkOnly(c *check.C) {
  674. // Legacy Link feature must work only on default network, and not across networks
  675. cnt1 := "container1"
  676. cnt2 := "container2"
  677. network := "anotherbridge"
  678. // Run first container on default network
  679. dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top")
  680. // Create another network and run the second container on it
  681. dockerCmd(c, "network", "create", network)
  682. assertNwIsAvailable(c, network)
  683. dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top")
  684. // Try launching a container on default network, linking to the first container. Must succeed
  685. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top")
  686. // Try launching a container on default network, linking to the second container. Must fail
  687. _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  688. c.Assert(err, checker.NotNil)
  689. // Connect second container to default network. Now a container on default network can link to it
  690. dockerCmd(c, "network", "connect", "bridge", cnt2)
  691. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  692. }
  693. func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) {
  694. // Verify exposed ports are present in ps output when running a container on
  695. // a network managed by a driver which does not provide the default gateway
  696. // for the container
  697. nwn := "ov"
  698. ctn := "bb"
  699. port1 := 80
  700. port2 := 443
  701. expose1 := fmt.Sprintf("--expose=%d", port1)
  702. expose2 := fmt.Sprintf("--expose=%d", port2)
  703. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  704. assertNwIsAvailable(c, nwn)
  705. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top")
  706. // Check docker ps o/p for last created container reports the unpublished ports
  707. unpPort1 := fmt.Sprintf("%d/tcp", port1)
  708. unpPort2 := fmt.Sprintf("%d/tcp", port2)
  709. out, _ := dockerCmd(c, "ps", "-n=1")
  710. // Missing unpublished ports in docker ps output
  711. c.Assert(out, checker.Contains, unpPort1)
  712. // Missing unpublished ports in docker ps output
  713. c.Assert(out, checker.Contains, unpPort2)
  714. }
  715. func (s *DockerNetworkSuite) TestDockerNetworkDriverUngracefulRestart(c *check.C) {
  716. testRequires(c, DaemonIsLinux, NotUserNamespace)
  717. dnd := "dnd"
  718. did := "did"
  719. mux := http.NewServeMux()
  720. server := httptest.NewServer(mux)
  721. setupRemoteNetworkDrivers(c, mux, server.URL, dnd, did)
  722. s.d.StartWithBusybox()
  723. _, err := s.d.Cmd("network", "create", "-d", dnd, "--subnet", "1.1.1.0/24", "net1")
  724. c.Assert(err, checker.IsNil)
  725. _, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "foo", "--ip", "1.1.1.10", "busybox", "sh")
  726. c.Assert(err, checker.IsNil)
  727. // Kill daemon and restart
  728. if err = s.d.cmd.Process.Kill(); err != nil {
  729. c.Fatal(err)
  730. }
  731. server.Close()
  732. startTime := time.Now().Unix()
  733. if err = s.d.Restart(); err != nil {
  734. c.Fatal(err)
  735. }
  736. lapse := time.Now().Unix() - startTime
  737. if lapse > 60 {
  738. // In normal scenarios, daemon restart takes ~1 second.
  739. // Plugin retry mechanism can delay the daemon start. systemd may not like it.
  740. // Avoid accessing plugins during daemon bootup
  741. c.Logf("daemon restart took too long : %d seconds", lapse)
  742. }
  743. // Restart the custom dummy plugin
  744. mux = http.NewServeMux()
  745. server = httptest.NewServer(mux)
  746. setupRemoteNetworkDrivers(c, mux, server.URL, dnd, did)
  747. // trying to reuse the same ip must succeed
  748. _, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "bar", "--ip", "1.1.1.10", "busybox", "sh")
  749. c.Assert(err, checker.IsNil)
  750. }
  751. func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) {
  752. // Verify endpoint MAC address is correctly populated in container's network settings
  753. nwn := "ov"
  754. ctn := "bb"
  755. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  756. assertNwIsAvailable(c, nwn)
  757. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top")
  758. mac := inspectField(c, ctn, "NetworkSettings.Networks."+nwn+".MacAddress")
  759. c.Assert(mac, checker.Equals, "a0:b1:c2:d3:e4:f5")
  760. }
  761. func (s *DockerSuite) TestInspectApiMultipleNetworks(c *check.C) {
  762. dockerCmd(c, "network", "create", "mybridge1")
  763. dockerCmd(c, "network", "create", "mybridge2")
  764. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  765. id := strings.TrimSpace(out)
  766. c.Assert(waitRun(id), check.IsNil)
  767. dockerCmd(c, "network", "connect", "mybridge1", id)
  768. dockerCmd(c, "network", "connect", "mybridge2", id)
  769. body := getInspectBody(c, "v1.20", id)
  770. var inspect120 v1p20.ContainerJSON
  771. err := json.Unmarshal(body, &inspect120)
  772. c.Assert(err, checker.IsNil)
  773. versionedIP := inspect120.NetworkSettings.IPAddress
  774. body = getInspectBody(c, "v1.21", id)
  775. var inspect121 types.ContainerJSON
  776. err = json.Unmarshal(body, &inspect121)
  777. c.Assert(err, checker.IsNil)
  778. c.Assert(inspect121.NetworkSettings.Networks, checker.HasLen, 3)
  779. bridge := inspect121.NetworkSettings.Networks["bridge"]
  780. c.Assert(bridge.IPAddress, checker.Equals, versionedIP)
  781. c.Assert(bridge.IPAddress, checker.Equals, inspect121.NetworkSettings.IPAddress)
  782. }
  783. func connectContainerToNetworks(c *check.C, d *Daemon, cName string, nws []string) {
  784. // Run a container on the default network
  785. out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
  786. c.Assert(err, checker.IsNil, check.Commentf(out))
  787. // Attach the container to other networks
  788. for _, nw := range nws {
  789. out, err = d.Cmd("network", "create", nw)
  790. c.Assert(err, checker.IsNil, check.Commentf(out))
  791. out, err = d.Cmd("network", "connect", nw, cName)
  792. c.Assert(err, checker.IsNil, check.Commentf(out))
  793. }
  794. }
  795. func verifyContainerIsConnectedToNetworks(c *check.C, d *Daemon, cName string, nws []string) {
  796. // Verify container is connected to all the networks
  797. for _, nw := range nws {
  798. out, err := d.Cmd("inspect", "-f", fmt.Sprintf("{{.NetworkSettings.Networks.%s}}", nw), cName)
  799. c.Assert(err, checker.IsNil, check.Commentf(out))
  800. c.Assert(out, checker.Not(checker.Equals), "<no value>\n")
  801. }
  802. }
  803. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRestart(c *check.C) {
  804. cName := "bb"
  805. nwList := []string{"nw1", "nw2", "nw3"}
  806. s.d.StartWithBusybox()
  807. connectContainerToNetworks(c, s.d, cName, nwList)
  808. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  809. // Reload daemon
  810. s.d.Restart()
  811. _, err := s.d.Cmd("start", cName)
  812. c.Assert(err, checker.IsNil)
  813. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  814. }
  815. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksUngracefulDaemonRestart(c *check.C) {
  816. cName := "cc"
  817. nwList := []string{"nw1", "nw2", "nw3"}
  818. s.d.StartWithBusybox()
  819. connectContainerToNetworks(c, s.d, cName, nwList)
  820. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  821. // Kill daemon and restart
  822. if err := s.d.cmd.Process.Kill(); err != nil {
  823. c.Fatal(err)
  824. }
  825. s.d.Restart()
  826. // Restart container
  827. _, err := s.d.Cmd("start", cName)
  828. c.Assert(err, checker.IsNil)
  829. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  830. }
  831. func (s *DockerNetworkSuite) TestDockerNetworkRunNetByID(c *check.C) {
  832. out, _ := dockerCmd(c, "network", "create", "one")
  833. containerOut, _, err := dockerCmdWithError("run", "-d", "--net", strings.TrimSpace(out), "busybox", "top")
  834. c.Assert(err, checker.IsNil, check.Commentf(containerOut))
  835. }
  836. func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c *check.C) {
  837. testRequires(c, DaemonIsLinux, NotUserNamespace)
  838. s.d.StartWithBusybox()
  839. // Run a few containers on host network
  840. for i := 0; i < 10; i++ {
  841. cName := fmt.Sprintf("hostc-%d", i)
  842. out, err := s.d.Cmd("run", "-d", "--name", cName, "--net=host", "--restart=always", "busybox", "top")
  843. c.Assert(err, checker.IsNil, check.Commentf(out))
  844. // verfiy container has finished starting before killing daemon
  845. err = s.d.waitRun(cName)
  846. c.Assert(err, checker.IsNil)
  847. }
  848. // Kill daemon ungracefully and restart
  849. if err := s.d.cmd.Process.Kill(); err != nil {
  850. c.Fatal(err)
  851. }
  852. if err := s.d.Restart(); err != nil {
  853. c.Fatal(err)
  854. }
  855. // make sure all the containers are up and running
  856. for i := 0; i < 10; i++ {
  857. err := s.d.waitRun(fmt.Sprintf("hostc-%d", i))
  858. c.Assert(err, checker.IsNil)
  859. }
  860. }
  861. func (s *DockerNetworkSuite) TestDockerNetworkConnectToHostFromOtherNetwork(c *check.C) {
  862. dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
  863. c.Assert(waitRun("container1"), check.IsNil)
  864. dockerCmd(c, "network", "disconnect", "bridge", "container1")
  865. out, _, err := dockerCmdWithError("network", "connect", "host", "container1")
  866. c.Assert(err, checker.NotNil, check.Commentf(out))
  867. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  868. }
  869. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromHost(c *check.C) {
  870. dockerCmd(c, "run", "-d", "--name", "container1", "--net=host", "busybox", "top")
  871. c.Assert(waitRun("container1"), check.IsNil)
  872. out, _, err := dockerCmdWithError("network", "disconnect", "host", "container1")
  873. c.Assert(err, checker.NotNil, check.Commentf("Should err out disconnect from host"))
  874. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  875. }
  876. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithPortMapping(c *check.C) {
  877. testRequires(c, NotArm)
  878. dockerCmd(c, "network", "create", "test1")
  879. dockerCmd(c, "run", "-d", "--name", "c1", "-p", "5000:5000", "busybox", "top")
  880. c.Assert(waitRun("c1"), check.IsNil)
  881. dockerCmd(c, "network", "connect", "test1", "c1")
  882. }
  883. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithMac(c *check.C) {
  884. macAddress := "02:42:ac:11:00:02"
  885. dockerCmd(c, "network", "create", "mynetwork")
  886. dockerCmd(c, "run", "--name=test", "-d", "--mac-address", macAddress, "busybox", "top")
  887. c.Assert(waitRun("test"), check.IsNil)
  888. mac1 := inspectField(c, "test", "NetworkSettings.Networks.bridge.MacAddress")
  889. c.Assert(strings.TrimSpace(mac1), checker.Equals, macAddress)
  890. dockerCmd(c, "network", "connect", "mynetwork", "test")
  891. mac2 := inspectField(c, "test", "NetworkSettings.Networks.mynetwork.MacAddress")
  892. c.Assert(strings.TrimSpace(mac2), checker.Not(checker.Equals), strings.TrimSpace(mac1))
  893. }
  894. func (s *DockerNetworkSuite) TestDockerNetworkInspectCreatedContainer(c *check.C) {
  895. dockerCmd(c, "create", "--name", "test", "busybox")
  896. networks := inspectField(c, "test", "NetworkSettings.Networks")
  897. c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should return 'bridge' network"))
  898. }
  899. func (s *DockerNetworkSuite) TestDockerNetworkRestartWithMultipleNetworks(c *check.C) {
  900. dockerCmd(c, "network", "create", "test")
  901. dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
  902. c.Assert(waitRun("foo"), checker.IsNil)
  903. dockerCmd(c, "network", "connect", "test", "foo")
  904. dockerCmd(c, "restart", "foo")
  905. networks := inspectField(c, "foo", "NetworkSettings.Networks")
  906. c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should contain 'bridge' network"))
  907. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  908. }
  909. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectToStoppedContainer(c *check.C) {
  910. dockerCmd(c, "network", "create", "test")
  911. dockerCmd(c, "create", "--name=foo", "busybox", "top")
  912. dockerCmd(c, "network", "connect", "test", "foo")
  913. networks := inspectField(c, "foo", "NetworkSettings.Networks")
  914. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  915. // Restart docker daemon to test the config has persisted to disk
  916. s.d.Restart()
  917. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  918. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  919. // start the container and test if we can ping it from another container in the same network
  920. dockerCmd(c, "start", "foo")
  921. c.Assert(waitRun("foo"), checker.IsNil)
  922. ip := inspectField(c, "foo", "NetworkSettings.Networks.test.IPAddress")
  923. ip = strings.TrimSpace(ip)
  924. dockerCmd(c, "run", "--net=test", "busybox", "sh", "-c", fmt.Sprintf("ping -c 1 %s", ip))
  925. dockerCmd(c, "stop", "foo")
  926. // Test disconnect
  927. dockerCmd(c, "network", "disconnect", "test", "foo")
  928. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  929. c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
  930. // Restart docker daemon to test the config has persisted to disk
  931. s.d.Restart()
  932. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  933. c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
  934. }
  935. func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIP(c *check.C) {
  936. // create two networks
  937. dockerCmd(c, "network", "create", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "n0")
  938. assertNwIsAvailable(c, "n0")
  939. dockerCmd(c, "network", "create", "--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")
  940. assertNwIsAvailable(c, "n1")
  941. // run a container on first network specifying the ip addresses
  942. dockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  943. c.Assert(waitRun("c0"), check.IsNil)
  944. verifyIPAddressConfig(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  945. verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  946. // connect the container to the second network specifying an ip addresses
  947. dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n1", "c0")
  948. verifyIPAddressConfig(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  949. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  950. // Stop and restart the container
  951. dockerCmd(c, "stop", "c0")
  952. dockerCmd(c, "start", "c0")
  953. // verify requested addresses are applied and configs are still there
  954. verifyIPAddressConfig(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  955. verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  956. verifyIPAddressConfig(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  957. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  958. // Still it should fail to connect to the default network with a specified IP (whatever ip)
  959. out, _, err := dockerCmdWithError("network", "connect", "--ip", "172.21.55.44", "bridge", "c0")
  960. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  961. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
  962. }
  963. func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIPStoppedContainer(c *check.C) {
  964. // create a container
  965. dockerCmd(c, "create", "--name", "c0", "busybox", "top")
  966. // create a network
  967. dockerCmd(c, "network", "create", "--subnet=172.30.0.0/16", "--subnet=2001:db8:abcd::/64", "n0")
  968. assertNwIsAvailable(c, "n0")
  969. // connect the container to the network specifying an ip addresses
  970. dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n0", "c0")
  971. verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  972. // start the container, verify config has not changed and ip addresses are assigned
  973. dockerCmd(c, "start", "c0")
  974. c.Assert(waitRun("c0"), check.IsNil)
  975. verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  976. verifyIPAddresses(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  977. // stop the container and check ip config has not changed
  978. dockerCmd(c, "stop", "c0")
  979. verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  980. }
  981. func (s *DockerNetworkSuite) TestDockerNetworkUnsupportedRequiredIP(c *check.C) {
  982. // requested IP is not supported on predefined networks
  983. for _, mode := range []string{"none", "host", "bridge", "default"} {
  984. checkUnsupportedNetworkAndIP(c, mode)
  985. }
  986. // requested IP is not supported on networks with no user defined subnets
  987. dockerCmd(c, "network", "create", "n0")
  988. assertNwIsAvailable(c, "n0")
  989. out, _, err := dockerCmdWithError("run", "-d", "--ip", "172.28.99.88", "--net", "n0", "busybox", "top")
  990. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  991. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
  992. out, _, err = dockerCmdWithError("run", "-d", "--ip6", "2001:db8:1234::9988", "--net", "n0", "busybox", "top")
  993. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  994. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
  995. dockerCmd(c, "network", "rm", "n0")
  996. assertNwNotAvailable(c, "n0")
  997. }
  998. func checkUnsupportedNetworkAndIP(c *check.C, nwMode string) {
  999. out, _, err := dockerCmdWithError("run", "-d", "--net", nwMode, "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  1000. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1001. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
  1002. }
  1003. func verifyIPAddressConfig(c *check.C, cName, nwname, ipv4, ipv6 string) {
  1004. if ipv4 != "" {
  1005. out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAMConfig.IPv4Address", nwname))
  1006. c.Assert(strings.TrimSpace(out), check.Equals, ipv4)
  1007. }
  1008. if ipv6 != "" {
  1009. out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAMConfig.IPv6Address", nwname))
  1010. c.Assert(strings.TrimSpace(out), check.Equals, ipv6)
  1011. }
  1012. }
  1013. func verifyIPAddresses(c *check.C, cName, nwname, ipv4, ipv6 string) {
  1014. out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAddress", nwname))
  1015. c.Assert(strings.TrimSpace(out), check.Equals, ipv4)
  1016. out = inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.GlobalIPv6Address", nwname))
  1017. c.Assert(strings.TrimSpace(out), check.Equals, ipv6)
  1018. }
  1019. func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectLink(c *check.C) {
  1020. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  1021. dockerCmd(c, "network", "create", "-d", "bridge", "foo1")
  1022. dockerCmd(c, "network", "create", "-d", "bridge", "foo2")
  1023. dockerCmd(c, "run", "-d", "--net=foo1", "--name=first", "busybox", "top")
  1024. c.Assert(waitRun("first"), check.IsNil)
  1025. // run a container in a user-defined network with a link for an existing container
  1026. // and a link for a container that doesn't exist
  1027. dockerCmd(c, "run", "-d", "--net=foo1", "--name=second", "--link=first:FirstInFoo1",
  1028. "--link=third:bar", "busybox", "top")
  1029. c.Assert(waitRun("second"), check.IsNil)
  1030. // ping to first and its alias FirstInFoo1 must succeed
  1031. _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  1032. c.Assert(err, check.IsNil)
  1033. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1")
  1034. c.Assert(err, check.IsNil)
  1035. // connect first container to foo2 network
  1036. dockerCmd(c, "network", "connect", "foo2", "first")
  1037. // connect second container to foo2 network with a different alias for first container
  1038. dockerCmd(c, "network", "connect", "--link=first:FirstInFoo2", "foo2", "second")
  1039. // ping the new alias in network foo2
  1040. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2")
  1041. c.Assert(err, check.IsNil)
  1042. // disconnect first container from foo1 network
  1043. dockerCmd(c, "network", "disconnect", "foo1", "first")
  1044. // link in foo1 network must fail
  1045. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1")
  1046. c.Assert(err, check.NotNil)
  1047. // link in foo2 network must succeed
  1048. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2")
  1049. c.Assert(err, check.IsNil)
  1050. }
  1051. // #19100 This is a deprecated feature test, it should be removed in Docker 1.12
  1052. func (s *DockerNetworkSuite) TestDockerNetworkStartAPIWithHostconfig(c *check.C) {
  1053. netName := "test"
  1054. conName := "foo"
  1055. dockerCmd(c, "network", "create", netName)
  1056. dockerCmd(c, "create", "--name", conName, "busybox", "top")
  1057. config := map[string]interface{}{
  1058. "HostConfig": map[string]interface{}{
  1059. "NetworkMode": netName,
  1060. },
  1061. }
  1062. _, _, err := sockRequest("POST", "/containers/"+conName+"/start", config)
  1063. c.Assert(err, checker.IsNil)
  1064. c.Assert(waitRun(conName), checker.IsNil)
  1065. networks := inspectField(c, conName, "NetworkSettings.Networks")
  1066. c.Assert(networks, checker.Contains, netName, check.Commentf(fmt.Sprintf("Should contain '%s' network", netName)))
  1067. c.Assert(networks, checker.Not(checker.Contains), "bridge", check.Commentf("Should not contain 'bridge' network"))
  1068. }
  1069. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectDefault(c *check.C) {
  1070. netWorkName1 := "test1"
  1071. netWorkName2 := "test2"
  1072. containerName := "foo"
  1073. dockerCmd(c, "network", "create", netWorkName1)
  1074. dockerCmd(c, "network", "create", netWorkName2)
  1075. dockerCmd(c, "create", "--name", containerName, "busybox", "top")
  1076. dockerCmd(c, "network", "connect", netWorkName1, containerName)
  1077. dockerCmd(c, "network", "connect", netWorkName2, containerName)
  1078. dockerCmd(c, "network", "disconnect", "bridge", containerName)
  1079. dockerCmd(c, "start", containerName)
  1080. c.Assert(waitRun(containerName), checker.IsNil)
  1081. networks := inspectField(c, containerName, "NetworkSettings.Networks")
  1082. c.Assert(networks, checker.Contains, netWorkName1, check.Commentf(fmt.Sprintf("Should contain '%s' network", netWorkName1)))
  1083. c.Assert(networks, checker.Contains, netWorkName2, check.Commentf(fmt.Sprintf("Should contain '%s' network", netWorkName2)))
  1084. c.Assert(networks, checker.Not(checker.Contains), "bridge", check.Commentf("Should not contain 'bridge' network"))
  1085. }
  1086. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithAliasOnDefaultNetworks(c *check.C) {
  1087. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  1088. defaults := []string{"bridge", "host", "none"}
  1089. out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top")
  1090. containerID := strings.TrimSpace(out)
  1091. for _, net := range defaults {
  1092. res, _, err := dockerCmdWithError("network", "connect", "--alias", "alias"+net, net, containerID)
  1093. c.Assert(err, checker.NotNil)
  1094. c.Assert(res, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
  1095. }
  1096. }
  1097. func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectAlias(c *check.C) {
  1098. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  1099. dockerCmd(c, "network", "create", "-d", "bridge", "net1")
  1100. dockerCmd(c, "network", "create", "-d", "bridge", "net2")
  1101. dockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo", "busybox", "top")
  1102. c.Assert(waitRun("first"), check.IsNil)
  1103. dockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox", "top")
  1104. c.Assert(waitRun("second"), check.IsNil)
  1105. // ping first container and its alias
  1106. _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  1107. c.Assert(err, check.IsNil)
  1108. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
  1109. c.Assert(err, check.IsNil)
  1110. // connect first container to net2 network
  1111. dockerCmd(c, "network", "connect", "--alias=bar", "net2", "first")
  1112. // connect second container to foo2 network with a different alias for first container
  1113. dockerCmd(c, "network", "connect", "net2", "second")
  1114. // ping the new alias in network foo2
  1115. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
  1116. c.Assert(err, check.IsNil)
  1117. // disconnect first container from net1 network
  1118. dockerCmd(c, "network", "disconnect", "net1", "first")
  1119. // ping to net1 scoped alias "foo" must fail
  1120. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
  1121. c.Assert(err, check.NotNil)
  1122. // ping to net2 scoped alias "bar" must still succeed
  1123. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
  1124. c.Assert(err, check.IsNil)
  1125. // verify the alias option is rejected when running on predefined network
  1126. out, _, err := dockerCmdWithError("run", "--rm", "--name=any", "--net-alias=any", "busybox", "top")
  1127. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1128. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
  1129. // verify the alias option is rejected when connecting to predefined network
  1130. out, _, err = dockerCmdWithError("network", "connect", "--alias=any", "bridge", "first")
  1131. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1132. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
  1133. }
  1134. func (s *DockerSuite) TestUserDefinedNetworkConnectivity(c *check.C) {
  1135. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1136. dockerCmd(c, "network", "create", "-d", "bridge", "br.net1")
  1137. dockerCmd(c, "run", "-d", "--net=br.net1", "--name=c1.net1", "busybox", "top")
  1138. c.Assert(waitRun("c1.net1"), check.IsNil)
  1139. dockerCmd(c, "run", "-d", "--net=br.net1", "--name=c2.net1", "busybox", "top")
  1140. c.Assert(waitRun("c2.net1"), check.IsNil)
  1141. // ping first container by its unqualified name
  1142. _, _, err := dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1")
  1143. c.Assert(err, check.IsNil)
  1144. // ping first container by its qualified name
  1145. _, _, err = dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1.br.net1")
  1146. c.Assert(err, check.IsNil)
  1147. // ping with first qualified name masked by an additional domain. should fail
  1148. _, _, err = dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1.br.net1.google.com")
  1149. c.Assert(err, check.NotNil)
  1150. }
  1151. func (s *DockerSuite) TestEmbeddedDNSInvalidInput(c *check.C) {
  1152. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1153. dockerCmd(c, "network", "create", "-d", "bridge", "nw1")
  1154. // Sending garbage to embedded DNS shouldn't crash the daemon
  1155. dockerCmd(c, "run", "-i", "--net=nw1", "--name=c1", "debian:jessie", "bash", "-c", "echo InvalidQuery > /dev/udp/127.0.0.11/53")
  1156. }
  1157. func (s *DockerSuite) TestDockerNetworkConnectFailsNoInspectChange(c *check.C) {
  1158. dockerCmd(c, "run", "-d", "--name=bb", "busybox", "top")
  1159. c.Assert(waitRun("bb"), check.IsNil)
  1160. ns0 := inspectField(c, "bb", "NetworkSettings.Networks.bridge")
  1161. // A failing redundant network connect should not alter current container's endpoint settings
  1162. _, _, err := dockerCmdWithError("network", "connect", "bridge", "bb")
  1163. c.Assert(err, check.NotNil)
  1164. ns1 := inspectField(c, "bb", "NetworkSettings.Networks.bridge")
  1165. c.Assert(ns1, check.Equals, ns0)
  1166. }
  1167. func (s *DockerSuite) TestDockerNetworkInternalMode(c *check.C) {
  1168. dockerCmd(c, "network", "create", "--driver=bridge", "--internal", "internal")
  1169. assertNwIsAvailable(c, "internal")
  1170. nr := getNetworkResource(c, "internal")
  1171. c.Assert(nr.Internal, checker.True)
  1172. dockerCmd(c, "run", "-d", "--net=internal", "--name=first", "busybox", "top")
  1173. c.Assert(waitRun("first"), check.IsNil)
  1174. dockerCmd(c, "run", "-d", "--net=internal", "--name=second", "busybox", "top")
  1175. c.Assert(waitRun("second"), check.IsNil)
  1176. out, _, err := dockerCmdWithError("exec", "first", "ping", "-W", "4", "-c", "1", "www.google.com")
  1177. c.Assert(err, check.NotNil)
  1178. c.Assert(out, checker.Contains, "100% packet loss")
  1179. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  1180. c.Assert(err, check.IsNil)
  1181. }