docker_cli_network_unix_test.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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. "sort"
  12. "strings"
  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. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  50. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  51. fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType)
  52. })
  53. // Network driver implementation
  54. mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  55. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  56. fmt.Fprintf(w, `{"Scope":"local"}`)
  57. })
  58. mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  59. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  60. if err != nil {
  61. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  62. return
  63. }
  64. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  65. fmt.Fprintf(w, "null")
  66. })
  67. mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", 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, "null")
  70. })
  71. mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  72. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  73. fmt.Fprintf(w, `{"Interface":{"MacAddress":"a0:b1:c2:d3:e4:f5"}}`)
  74. })
  75. mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  76. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  77. veth := &netlink.Veth{
  78. LinkAttrs: netlink.LinkAttrs{Name: "randomIfName", TxQLen: 0}, PeerName: "cnt0"}
  79. if err := netlink.LinkAdd(veth); err != nil {
  80. fmt.Fprintf(w, `{"Error":"failed to add veth pair: `+err.Error()+`"}`)
  81. } else {
  82. fmt.Fprintf(w, `{"InterfaceName":{ "SrcName":"cnt0", "DstPrefix":"veth"}}`)
  83. }
  84. })
  85. mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  86. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  87. fmt.Fprintf(w, "null")
  88. })
  89. mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  90. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  91. if link, err := netlink.LinkByName("cnt0"); err == nil {
  92. netlink.LinkDel(link)
  93. }
  94. fmt.Fprintf(w, "null")
  95. })
  96. // Ipam Driver implementation
  97. var (
  98. poolRequest remoteipam.RequestPoolRequest
  99. poolReleaseReq remoteipam.ReleasePoolRequest
  100. addressRequest remoteipam.RequestAddressRequest
  101. addressReleaseReq remoteipam.ReleaseAddressRequest
  102. lAS = "localAS"
  103. gAS = "globalAS"
  104. pool = "172.28.0.0/16"
  105. poolID = lAS + "/" + pool
  106. gw = "172.28.255.254/16"
  107. )
  108. mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  109. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  110. fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`)
  111. })
  112. mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  113. err := json.NewDecoder(r.Body).Decode(&poolRequest)
  114. if err != nil {
  115. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  116. return
  117. }
  118. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  119. if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS {
  120. fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`)
  121. } else if poolRequest.Pool != "" && poolRequest.Pool != pool {
  122. fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`)
  123. } else {
  124. fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`)
  125. }
  126. })
  127. mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  128. err := json.NewDecoder(r.Body).Decode(&addressRequest)
  129. if err != nil {
  130. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  131. return
  132. }
  133. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  134. // make sure libnetwork is now querying on the expected pool id
  135. if addressRequest.PoolID != poolID {
  136. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  137. } else if addressRequest.Address != "" {
  138. fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`)
  139. } else {
  140. fmt.Fprintf(w, `{"Address":"`+gw+`"}`)
  141. }
  142. })
  143. mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  144. err := json.NewDecoder(r.Body).Decode(&addressReleaseReq)
  145. if err != nil {
  146. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  147. return
  148. }
  149. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  150. // make sure libnetwork is now asking to release the expected address from the expected poolid
  151. if addressRequest.PoolID != poolID {
  152. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  153. } else if addressReleaseReq.Address != gw {
  154. fmt.Fprintf(w, `{"Error":"unknown address"}`)
  155. } else {
  156. fmt.Fprintf(w, "null")
  157. }
  158. })
  159. mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  160. err := json.NewDecoder(r.Body).Decode(&poolReleaseReq)
  161. if err != nil {
  162. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  163. return
  164. }
  165. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  166. // make sure libnetwork is now asking to release the expected poolid
  167. if addressRequest.PoolID != poolID {
  168. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  169. } else {
  170. fmt.Fprintf(w, "null")
  171. }
  172. })
  173. err := os.MkdirAll("/etc/docker/plugins", 0755)
  174. c.Assert(err, checker.IsNil)
  175. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", dummyNetworkDriver)
  176. err = ioutil.WriteFile(fileName, []byte(s.server.URL), 0644)
  177. c.Assert(err, checker.IsNil)
  178. ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", dummyIpamDriver)
  179. err = ioutil.WriteFile(ipamFileName, []byte(s.server.URL), 0644)
  180. c.Assert(err, checker.IsNil)
  181. }
  182. func (s *DockerNetworkSuite) TearDownSuite(c *check.C) {
  183. if s.server == nil {
  184. return
  185. }
  186. s.server.Close()
  187. err := os.RemoveAll("/etc/docker/plugins")
  188. c.Assert(err, checker.IsNil)
  189. }
  190. func assertNwIsAvailable(c *check.C, name string) {
  191. if !isNwPresent(c, name) {
  192. c.Fatalf("Network %s not found in network ls o/p", name)
  193. }
  194. }
  195. func assertNwNotAvailable(c *check.C, name string) {
  196. if isNwPresent(c, name) {
  197. c.Fatalf("Found network %s in network ls o/p", name)
  198. }
  199. }
  200. func isNwPresent(c *check.C, name string) bool {
  201. out, _ := dockerCmd(c, "network", "ls")
  202. lines := strings.Split(out, "\n")
  203. for i := 1; i < len(lines)-1; i++ {
  204. netFields := strings.Fields(lines[i])
  205. if netFields[1] == name {
  206. return true
  207. }
  208. }
  209. return false
  210. }
  211. // assertNwList checks network list retrived with ls command
  212. // equals to expected network list
  213. // note: out should be `network ls [option]` result
  214. func assertNwList(c *check.C, out string, expectNws []string) {
  215. lines := strings.Split(out, "\n")
  216. var nwList []string
  217. for _, line := range lines[1 : len(lines)-1] {
  218. netFields := strings.Fields(line)
  219. // wrap all network name in nwList
  220. nwList = append(nwList, netFields[1])
  221. }
  222. // first need to sort out and expected
  223. sort.StringSlice(nwList).Sort()
  224. sort.StringSlice(expectNws).Sort()
  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) TestDockerNetworkLsFilter(c *check.C) {
  242. out, _ := dockerCmd(c, "network", "create", "dev")
  243. defer func() {
  244. dockerCmd(c, "network", "rm", "dev")
  245. }()
  246. containerID := strings.TrimSpace(out)
  247. // filter with partial ID and partial name
  248. // only show 'bridge' and 'dev' network
  249. out, _ = dockerCmd(c, "network", "ls", "-f", "id="+containerID[0:5], "-f", "name=dge")
  250. assertNwList(c, out, []string{"dev", "bridge"})
  251. // only show built-in network (bridge, none, host)
  252. out, _ = dockerCmd(c, "network", "ls", "-f", "type=builtin")
  253. assertNwList(c, out, []string{"bridge", "none", "host"})
  254. // only show custom networks (dev)
  255. out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom")
  256. assertNwList(c, out, []string{"dev"})
  257. // show all networks with filter
  258. // it should be equivalent of ls without option
  259. out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom", "-f", "type=builtin")
  260. assertNwList(c, out, []string{"dev", "bridge", "host", "none"})
  261. }
  262. func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *check.C) {
  263. dockerCmd(c, "network", "create", "test")
  264. assertNwIsAvailable(c, "test")
  265. dockerCmd(c, "network", "rm", "test")
  266. assertNwNotAvailable(c, "test")
  267. }
  268. func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *check.C) {
  269. out, _, err := dockerCmdWithError("network", "rm", "test")
  270. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  271. }
  272. func (s *DockerSuite) TestDockerNetworkDeleteMultiple(c *check.C) {
  273. dockerCmd(c, "network", "create", "testDelMulti0")
  274. assertNwIsAvailable(c, "testDelMulti0")
  275. dockerCmd(c, "network", "create", "testDelMulti1")
  276. assertNwIsAvailable(c, "testDelMulti1")
  277. dockerCmd(c, "network", "create", "testDelMulti2")
  278. assertNwIsAvailable(c, "testDelMulti2")
  279. out, _ := dockerCmd(c, "run", "-d", "--net", "testDelMulti2", "busybox", "top")
  280. waitRun(strings.TrimSpace(out))
  281. // delete three networks at the same time, since testDelMulti2
  282. // contains active container, it's deletion should fail.
  283. out, _, err := dockerCmdWithError("network", "rm", "testDelMulti0", "testDelMulti1", "testDelMulti2")
  284. // err should not be nil due to deleting testDelMulti2 failed.
  285. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  286. // testDelMulti2 should fail due to network has active endpoints
  287. c.Assert(out, checker.Contains, "has active endpoints")
  288. assertNwNotAvailable(c, "testDelMulti0")
  289. assertNwNotAvailable(c, "testDelMulti1")
  290. // testDelMulti2 can't be deleted, so it should exists
  291. assertNwIsAvailable(c, "testDelMulti2")
  292. }
  293. func (s *DockerSuite) TestDockerNetworkInspect(c *check.C) {
  294. out, _ := dockerCmd(c, "network", "inspect", "host")
  295. networkResources := []types.NetworkResource{}
  296. err := json.Unmarshal([]byte(out), &networkResources)
  297. c.Assert(err, check.IsNil)
  298. c.Assert(networkResources, checker.HasLen, 1)
  299. out, _ = dockerCmd(c, "network", "inspect", "--format='{{ .Name }}'", "host")
  300. c.Assert(strings.TrimSpace(out), check.Equals, "host")
  301. }
  302. func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) {
  303. out, _ := dockerCmd(c, "network", "inspect", "host", "none")
  304. networkResources := []types.NetworkResource{}
  305. err := json.Unmarshal([]byte(out), &networkResources)
  306. c.Assert(err, check.IsNil)
  307. c.Assert(networkResources, checker.HasLen, 2)
  308. // Should print an error, return an exitCode 1 *but* should print the host network
  309. out, exitCode, err := dockerCmdWithError("network", "inspect", "host", "nonexistent")
  310. c.Assert(err, checker.NotNil)
  311. c.Assert(exitCode, checker.Equals, 1)
  312. c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
  313. networkResources = []types.NetworkResource{}
  314. inspectOut := strings.SplitN(out, "\nError: No such network: nonexistent\n", 2)[0]
  315. err = json.Unmarshal([]byte(inspectOut), &networkResources)
  316. c.Assert(networkResources, checker.HasLen, 1)
  317. // Should print an error and return an exitCode, nothing else
  318. out, exitCode, err = dockerCmdWithError("network", "inspect", "nonexistent")
  319. c.Assert(err, checker.NotNil)
  320. c.Assert(exitCode, checker.Equals, 1)
  321. c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
  322. }
  323. func (s *DockerSuite) TestDockerInspectNetworkWithContainerName(c *check.C) {
  324. dockerCmd(c, "network", "create", "brNetForInspect")
  325. assertNwIsAvailable(c, "brNetForInspect")
  326. defer func() {
  327. dockerCmd(c, "network", "rm", "brNetForInspect")
  328. assertNwNotAvailable(c, "brNetForInspect")
  329. }()
  330. out, _ := dockerCmd(c, "run", "-d", "--name", "testNetInspect1", "--net", "brNetForInspect", "busybox", "top")
  331. c.Assert(waitRun("testNetInspect1"), check.IsNil)
  332. containerID := strings.TrimSpace(out)
  333. defer func() {
  334. // we don't stop container by name, because we'll rename it later
  335. dockerCmd(c, "stop", containerID)
  336. }()
  337. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  338. networkResources := []types.NetworkResource{}
  339. err := json.Unmarshal([]byte(out), &networkResources)
  340. c.Assert(err, check.IsNil)
  341. c.Assert(networkResources, checker.HasLen, 1)
  342. container, ok := networkResources[0].Containers[containerID]
  343. c.Assert(ok, checker.True)
  344. c.Assert(container.Name, checker.Equals, "testNetInspect1")
  345. // rename container and check docker inspect output update
  346. newName := "HappyNewName"
  347. dockerCmd(c, "rename", "testNetInspect1", newName)
  348. // check whether network inspect works properly
  349. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  350. newNetRes := []types.NetworkResource{}
  351. err = json.Unmarshal([]byte(out), &newNetRes)
  352. c.Assert(err, check.IsNil)
  353. c.Assert(newNetRes, checker.HasLen, 1)
  354. container1, ok := newNetRes[0].Containers[containerID]
  355. c.Assert(ok, checker.True)
  356. c.Assert(container1.Name, checker.Equals, newName)
  357. }
  358. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) {
  359. dockerCmd(c, "network", "create", "test")
  360. assertNwIsAvailable(c, "test")
  361. nr := getNwResource(c, "test")
  362. c.Assert(nr.Name, checker.Equals, "test")
  363. c.Assert(len(nr.Containers), checker.Equals, 0)
  364. // run a container
  365. out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  366. c.Assert(waitRun("test"), check.IsNil)
  367. containerID := strings.TrimSpace(out)
  368. // connect the container to the test network
  369. dockerCmd(c, "network", "connect", "test", containerID)
  370. // inspect the network to make sure container is connected
  371. nr = getNetworkResource(c, nr.ID)
  372. c.Assert(len(nr.Containers), checker.Equals, 1)
  373. c.Assert(nr.Containers[containerID], check.NotNil)
  374. // check if container IP matches network inspect
  375. ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address)
  376. c.Assert(err, check.IsNil)
  377. containerIP := findContainerIP(c, "test", "test")
  378. c.Assert(ip.String(), checker.Equals, containerIP)
  379. // disconnect container from the network
  380. dockerCmd(c, "network", "disconnect", "test", containerID)
  381. nr = getNwResource(c, "test")
  382. c.Assert(nr.Name, checker.Equals, "test")
  383. c.Assert(len(nr.Containers), checker.Equals, 0)
  384. // run another container
  385. out, _ = dockerCmd(c, "run", "-d", "--net", "test", "--name", "test2", "busybox", "top")
  386. c.Assert(waitRun("test2"), check.IsNil)
  387. containerID = strings.TrimSpace(out)
  388. nr = getNwResource(c, "test")
  389. c.Assert(nr.Name, checker.Equals, "test")
  390. c.Assert(len(nr.Containers), checker.Equals, 1)
  391. // force disconnect the container to the test network
  392. dockerCmd(c, "network", "disconnect", "-f", "test", containerID)
  393. nr = getNwResource(c, "test")
  394. c.Assert(nr.Name, checker.Equals, "test")
  395. c.Assert(len(nr.Containers), checker.Equals, 0)
  396. dockerCmd(c, "network", "rm", "test")
  397. assertNwNotAvailable(c, "test")
  398. }
  399. func (s *DockerNetworkSuite) TestDockerNetworkIpamMultipleNetworks(c *check.C) {
  400. // test0 bridge network
  401. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
  402. assertNwIsAvailable(c, "test1")
  403. // test2 bridge network does not overlap
  404. dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
  405. assertNwIsAvailable(c, "test2")
  406. // for networks w/o ipam specified, docker will choose proper non-overlapping subnets
  407. dockerCmd(c, "network", "create", "test3")
  408. assertNwIsAvailable(c, "test3")
  409. dockerCmd(c, "network", "create", "test4")
  410. assertNwIsAvailable(c, "test4")
  411. dockerCmd(c, "network", "create", "test5")
  412. assertNwIsAvailable(c, "test5")
  413. // test network with multiple subnets
  414. // bridge network doesn't support multiple subnets. hence, use a dummy driver that supports
  415. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6")
  416. assertNwIsAvailable(c, "test6")
  417. // test network with multiple subnets with valid ipam combinations
  418. // also check same subnet across networks when the driver supports it.
  419. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
  420. "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16",
  421. "--gateway=192.168.0.100", "--gateway=192.170.0.100",
  422. "--ip-range=192.168.1.0/24",
  423. "--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6",
  424. "--aux-address", "a=192.170.1.5", "--aux-address", "b=192.170.1.6",
  425. "test7")
  426. assertNwIsAvailable(c, "test7")
  427. // cleanup
  428. for i := 1; i < 8; i++ {
  429. dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
  430. }
  431. }
  432. func (s *DockerNetworkSuite) TestDockerNetworkCustomIpam(c *check.C) {
  433. // Create a bridge network using custom ipam driver
  434. dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "br0")
  435. assertNwIsAvailable(c, "br0")
  436. // Verify expected network ipam fields are there
  437. nr := getNetworkResource(c, "br0")
  438. c.Assert(nr.Driver, checker.Equals, "bridge")
  439. c.Assert(nr.IPAM.Driver, checker.Equals, dummyIpamDriver)
  440. // remove network and exercise remote ipam driver
  441. dockerCmd(c, "network", "rm", "br0")
  442. assertNwNotAvailable(c, "br0")
  443. }
  444. func (s *DockerNetworkSuite) TestDockerNetworkInspect(c *check.C) {
  445. // if unspecified, network gateway will be selected from inside preferred pool
  446. dockerCmd(c, "network", "create", "--driver=bridge", "--subnet=172.28.0.0/16", "--ip-range=172.28.5.0/24", "--gateway=172.28.5.254", "br0")
  447. assertNwIsAvailable(c, "br0")
  448. nr := getNetworkResource(c, "br0")
  449. c.Assert(nr.Driver, checker.Equals, "bridge")
  450. c.Assert(nr.Scope, checker.Equals, "local")
  451. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  452. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  453. c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16")
  454. c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24")
  455. c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254")
  456. dockerCmd(c, "network", "rm", "br0")
  457. }
  458. func (s *DockerNetworkSuite) TestDockerNetworkIpamInvalidCombinations(c *check.C) {
  459. // network with ip-range out of subnet range
  460. _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
  461. c.Assert(err, check.NotNil)
  462. // network with multiple gateways for a single subnet
  463. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
  464. c.Assert(err, check.NotNil)
  465. // Multiple overlapping subnets in the same network must fail
  466. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
  467. c.Assert(err, check.NotNil)
  468. // overlapping subnets across networks must fail
  469. // create a valid test0 network
  470. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
  471. assertNwIsAvailable(c, "test0")
  472. // create an overlapping test1 network
  473. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
  474. c.Assert(err, check.NotNil)
  475. dockerCmd(c, "network", "rm", "test0")
  476. }
  477. func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) {
  478. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
  479. assertNwIsAvailable(c, "testopt")
  480. gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
  481. c.Assert(gopts, checker.NotNil)
  482. opts, ok := gopts.(map[string]interface{})
  483. c.Assert(ok, checker.Equals, true)
  484. c.Assert(opts["opt1"], checker.Equals, "drv1")
  485. c.Assert(opts["opt2"], checker.Equals, "drv2")
  486. dockerCmd(c, "network", "rm", "testopt")
  487. }
  488. func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *check.C) {
  489. testRequires(c, ExecSupport)
  490. // On default bridge network built-in service discovery should not happen
  491. hostsFile := "/etc/hosts"
  492. bridgeName := "external-bridge"
  493. bridgeIP := "192.169.255.254/24"
  494. out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
  495. c.Assert(err, check.IsNil, check.Commentf(out))
  496. defer deleteInterface(c, bridgeName)
  497. err = s.d.StartWithBusybox("--bridge", bridgeName)
  498. c.Assert(err, check.IsNil)
  499. defer s.d.Restart()
  500. // run two containers and store first container's etc/hosts content
  501. out, err = s.d.Cmd("run", "-d", "busybox", "top")
  502. c.Assert(err, check.IsNil)
  503. cid1 := strings.TrimSpace(out)
  504. defer s.d.Cmd("stop", cid1)
  505. hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  506. c.Assert(err, checker.IsNil)
  507. out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top")
  508. c.Assert(err, check.IsNil)
  509. cid2 := strings.TrimSpace(out)
  510. // verify first container's etc/hosts file has not changed after spawning the second named container
  511. hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  512. c.Assert(err, checker.IsNil)
  513. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  514. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  515. // stop container 2 and verify first container's etc/hosts has not changed
  516. _, err = s.d.Cmd("stop", cid2)
  517. c.Assert(err, check.IsNil)
  518. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  519. c.Assert(err, checker.IsNil)
  520. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  521. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  522. // but discovery is on when connecting to non default bridge network
  523. network := "anotherbridge"
  524. out, err = s.d.Cmd("network", "create", network)
  525. c.Assert(err, check.IsNil, check.Commentf(out))
  526. defer s.d.Cmd("network", "rm", network)
  527. out, err = s.d.Cmd("network", "connect", network, cid1)
  528. c.Assert(err, check.IsNil, check.Commentf(out))
  529. hosts, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  530. c.Assert(err, checker.IsNil)
  531. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  532. c.Assert(err, checker.IsNil)
  533. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  534. check.Commentf("Unexpected %s change on second network connection", hostsFile))
  535. }
  536. func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
  537. testRequires(c, ExecSupport)
  538. hostsFile := "/etc/hosts"
  539. cstmBridgeNw := "custom-bridge-nw"
  540. cstmBridgeNw1 := "custom-bridge-nw1"
  541. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw)
  542. assertNwIsAvailable(c, cstmBridgeNw)
  543. // run two anonymous containers and store their etc/hosts content
  544. out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  545. cid1 := strings.TrimSpace(out)
  546. hosts1, err := readContainerFileWithExec(cid1, hostsFile)
  547. c.Assert(err, checker.IsNil)
  548. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  549. cid2 := strings.TrimSpace(out)
  550. hosts2, err := readContainerFileWithExec(cid2, hostsFile)
  551. c.Assert(err, checker.IsNil)
  552. // verify first container etc/hosts file has not changed
  553. hosts1post, err := readContainerFileWithExec(cid1, hostsFile)
  554. c.Assert(err, checker.IsNil)
  555. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  556. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  557. // Connect the 2nd container to a new network and verify the
  558. // first container /etc/hosts file still hasn't changed.
  559. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1)
  560. assertNwIsAvailable(c, cstmBridgeNw1)
  561. dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2)
  562. hosts2, err = readContainerFileWithExec(cid2, hostsFile)
  563. c.Assert(err, checker.IsNil)
  564. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  565. c.Assert(err, checker.IsNil)
  566. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  567. check.Commentf("Unexpected %s change on container connect", hostsFile))
  568. // start a named container
  569. cName := "AnyName"
  570. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top")
  571. cid3 := strings.TrimSpace(out)
  572. // verify that container 1 and 2 can ping the named container
  573. dockerCmd(c, "exec", cid1, "ping", "-c", "1", cName)
  574. dockerCmd(c, "exec", cid2, "ping", "-c", "1", cName)
  575. // Stop named container and verify first two containers' etc/hosts file hasn't changed
  576. dockerCmd(c, "stop", cid3)
  577. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  578. c.Assert(err, checker.IsNil)
  579. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  580. check.Commentf("Unexpected %s change on name container creation", hostsFile))
  581. hosts2post, err := readContainerFileWithExec(cid2, hostsFile)
  582. c.Assert(err, checker.IsNil)
  583. c.Assert(string(hosts2), checker.Equals, string(hosts2post),
  584. check.Commentf("Unexpected %s change on name container creation", hostsFile))
  585. // verify that container 1 and 2 can't ping the named container now
  586. _, _, err = dockerCmdWithError("exec", cid1, "ping", "-c", "1", cName)
  587. c.Assert(err, check.NotNil)
  588. _, _, err = dockerCmdWithError("exec", cid2, "ping", "-c", "1", cName)
  589. c.Assert(err, check.NotNil)
  590. }
  591. func (s *DockerNetworkSuite) TestDockerNetworkLinkOndefaultNetworkOnly(c *check.C) {
  592. // Link feature must work only on default network, and not across networks
  593. cnt1 := "container1"
  594. cnt2 := "container2"
  595. network := "anotherbridge"
  596. // Run first container on default network
  597. dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top")
  598. // Create another network and run the second container on it
  599. dockerCmd(c, "network", "create", network)
  600. assertNwIsAvailable(c, network)
  601. dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top")
  602. // Try launching a container on default network, linking to the first container. Must succeed
  603. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top")
  604. // Try launching a container on default network, linking to the second container. Must fail
  605. _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  606. c.Assert(err, checker.NotNil)
  607. // Connect second container to default network. Now a container on default network can link to it
  608. dockerCmd(c, "network", "connect", "bridge", cnt2)
  609. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  610. }
  611. func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) {
  612. // Verify exposed ports are present in ps output when running a container on
  613. // a network managed by a driver which does not provide the default gateway
  614. // for the container
  615. nwn := "ov"
  616. ctn := "bb"
  617. port1 := 80
  618. port2 := 443
  619. expose1 := fmt.Sprintf("--expose=%d", port1)
  620. expose2 := fmt.Sprintf("--expose=%d", port2)
  621. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  622. assertNwIsAvailable(c, nwn)
  623. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top")
  624. // Check docker ps o/p for last created container reports the unpublished ports
  625. unpPort1 := fmt.Sprintf("%d/tcp", port1)
  626. unpPort2 := fmt.Sprintf("%d/tcp", port2)
  627. out, _ := dockerCmd(c, "ps", "-n=1")
  628. // Missing unpublished ports in docker ps output
  629. c.Assert(out, checker.Contains, unpPort1)
  630. // Missing unpublished ports in docker ps output
  631. c.Assert(out, checker.Contains, unpPort2)
  632. }
  633. func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) {
  634. // Verify endpoint MAC address is correctly populated in container's network settings
  635. nwn := "ov"
  636. ctn := "bb"
  637. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  638. assertNwIsAvailable(c, nwn)
  639. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top")
  640. mac, err := inspectField(ctn, "NetworkSettings.Networks."+nwn+".MacAddress")
  641. c.Assert(err, checker.IsNil)
  642. c.Assert(mac, checker.Equals, "a0:b1:c2:d3:e4:f5")
  643. }
  644. func (s *DockerSuite) TestInspectApiMultipleNetworks(c *check.C) {
  645. dockerCmd(c, "network", "create", "mybridge1")
  646. dockerCmd(c, "network", "create", "mybridge2")
  647. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  648. id := strings.TrimSpace(out)
  649. c.Assert(waitRun(id), check.IsNil)
  650. dockerCmd(c, "network", "connect", "mybridge1", id)
  651. dockerCmd(c, "network", "connect", "mybridge2", id)
  652. body := getInspectBody(c, "v1.20", id)
  653. var inspect120 v1p20.ContainerJSON
  654. err := json.Unmarshal(body, &inspect120)
  655. c.Assert(err, checker.IsNil)
  656. versionedIP := inspect120.NetworkSettings.IPAddress
  657. body = getInspectBody(c, "v1.21", id)
  658. var inspect121 types.ContainerJSON
  659. err = json.Unmarshal(body, &inspect121)
  660. c.Assert(err, checker.IsNil)
  661. c.Assert(inspect121.NetworkSettings.Networks, checker.HasLen, 3)
  662. bridge := inspect121.NetworkSettings.Networks["bridge"]
  663. c.Assert(bridge.IPAddress, checker.Equals, versionedIP)
  664. c.Assert(bridge.IPAddress, checker.Equals, inspect121.NetworkSettings.IPAddress)
  665. }
  666. func connectContainerToNetworks(c *check.C, d *Daemon, cName string, nws []string) {
  667. // Run a container on the default network
  668. out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
  669. c.Assert(err, checker.IsNil, check.Commentf(out))
  670. // Attach the container to other three networks
  671. for _, nw := range nws {
  672. out, err = d.Cmd("network", "create", nw)
  673. c.Assert(err, checker.IsNil, check.Commentf(out))
  674. out, err = d.Cmd("network", "connect", nw, cName)
  675. c.Assert(err, checker.IsNil, check.Commentf(out))
  676. }
  677. }
  678. func verifyContainerIsConnectedToNetworks(c *check.C, d *Daemon, cName string, nws []string) {
  679. // Verify container is connected to all three networks
  680. for _, nw := range nws {
  681. out, err := d.Cmd("inspect", "-f", fmt.Sprintf("{{.NetworkSettings.Networks.%s}}", nw), cName)
  682. c.Assert(err, checker.IsNil, check.Commentf(out))
  683. c.Assert(out, checker.Not(checker.Equals), "<no value>\n")
  684. }
  685. }
  686. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRestart(c *check.C) {
  687. cName := "bb"
  688. nwList := []string{"nw1", "nw2", "nw3"}
  689. s.d.StartWithBusybox()
  690. connectContainerToNetworks(c, s.d, cName, nwList)
  691. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  692. // Reload daemon
  693. s.d.Restart()
  694. _, err := s.d.Cmd("start", cName)
  695. c.Assert(err, checker.IsNil)
  696. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  697. }
  698. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksUngracefulDaemonRestart(c *check.C) {
  699. cName := "cc"
  700. nwList := []string{"nw1", "nw2", "nw3"}
  701. s.d.StartWithBusybox()
  702. connectContainerToNetworks(c, s.d, cName, nwList)
  703. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  704. // Kill daemon and restart
  705. if err := s.d.cmd.Process.Kill(); err != nil {
  706. c.Fatal(err)
  707. }
  708. s.d.Restart()
  709. // Restart container
  710. _, err := s.d.Cmd("start", cName)
  711. c.Assert(err, checker.IsNil)
  712. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  713. }
  714. func (s *DockerNetworkSuite) TestDockerNetworkRunNetByID(c *check.C) {
  715. out, _ := dockerCmd(c, "network", "create", "one")
  716. dockerCmd(c, "run", "-d", "--net", strings.TrimSpace(out), "busybox", "top")
  717. }
  718. func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c *check.C) {
  719. testRequires(c, DaemonIsLinux, NotUserNamespace)
  720. s.d.StartWithBusybox()
  721. // Run a few containers on host network
  722. for i := 0; i < 10; i++ {
  723. cName := fmt.Sprintf("hostc-%d", i)
  724. out, err := s.d.Cmd("run", "-d", "--name", cName, "--net=host", "--restart=always", "busybox", "top")
  725. c.Assert(err, checker.IsNil, check.Commentf(out))
  726. }
  727. // Kill daemon ungracefully and restart
  728. if err := s.d.cmd.Process.Kill(); err != nil {
  729. c.Fatal(err)
  730. }
  731. s.d.Restart()
  732. // make sure all the containers are up and running
  733. for i := 0; i < 10; i++ {
  734. cName := fmt.Sprintf("hostc-%d", i)
  735. runningOut, err := s.d.Cmd("inspect", "--format='{{.State.Running}}'", cName)
  736. c.Assert(err, checker.IsNil)
  737. c.Assert(strings.TrimSpace(runningOut), checker.Equals, "true")
  738. }
  739. }
  740. func (s *DockerNetworkSuite) TestDockerNetworkConnectToHostFromOtherNetwork(c *check.C) {
  741. dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
  742. c.Assert(waitRun("container1"), check.IsNil)
  743. dockerCmd(c, "network", "disconnect", "bridge", "container1")
  744. out, _, err := dockerCmdWithError("network", "connect", "host", "container1")
  745. c.Assert(err, checker.NotNil, check.Commentf(out))
  746. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  747. }
  748. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromHost(c *check.C) {
  749. dockerCmd(c, "run", "-d", "--name", "container1", "--net=host", "busybox", "top")
  750. c.Assert(waitRun("container1"), check.IsNil)
  751. out, _, err := dockerCmdWithError("network", "disconnect", "host", "container1")
  752. c.Assert(err, checker.NotNil, check.Commentf("Should err out disconnect from host"))
  753. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  754. }
  755. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithPortMapping(c *check.C) {
  756. dockerCmd(c, "network", "create", "test1")
  757. dockerCmd(c, "run", "-d", "--name", "c1", "-p", "5000:5000", "busybox", "top")
  758. c.Assert(waitRun("c1"), check.IsNil)
  759. dockerCmd(c, "network", "connect", "test1", "c1")
  760. }
  761. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithMac(c *check.C) {
  762. macAddress := "02:42:ac:11:00:02"
  763. dockerCmd(c, "network", "create", "mynetwork")
  764. dockerCmd(c, "run", "--name=test", "-d", "--mac-address", macAddress, "busybox", "top")
  765. c.Assert(waitRun("test"), check.IsNil)
  766. mac1, err := inspectField("test", "NetworkSettings.Networks.bridge.MacAddress")
  767. c.Assert(err, checker.IsNil)
  768. c.Assert(strings.TrimSpace(mac1), checker.Equals, macAddress)
  769. dockerCmd(c, "network", "connect", "mynetwork", "test")
  770. mac2, err := inspectField("test", "NetworkSettings.Networks.mynetwork.MacAddress")
  771. c.Assert(err, checker.IsNil)
  772. c.Assert(strings.TrimSpace(mac2), checker.Not(checker.Equals), strings.TrimSpace(mac1))
  773. }
  774. func (s *DockerNetworkSuite) TestDockerNetworkInspectCreatedContainer(c *check.C) {
  775. dockerCmd(c, "create", "--name", "test", "busybox")
  776. networks, err := inspectField("test", "NetworkSettings.Networks")
  777. c.Assert(err, checker.IsNil)
  778. c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should return 'bridge' network"))
  779. }
  780. func (s *DockerNetworkSuite) TestDockerNetworkRestartWithMulipleNetworks(c *check.C) {
  781. dockerCmd(c, "network", "create", "test")
  782. dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
  783. c.Assert(waitRun("foo"), checker.IsNil)
  784. dockerCmd(c, "network", "connect", "test", "foo")
  785. dockerCmd(c, "restart", "foo")
  786. networks, err := inspectField("foo", "NetworkSettings.Networks")
  787. c.Assert(err, checker.IsNil)
  788. c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should contain 'bridge' network"))
  789. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  790. }
  791. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectToStoppedContainer(c *check.C) {
  792. dockerCmd(c, "network", "create", "test")
  793. dockerCmd(c, "create", "--name=foo", "busybox", "top")
  794. dockerCmd(c, "network", "connect", "test", "foo")
  795. networks, err := inspectField("foo", "NetworkSettings.Networks")
  796. c.Assert(err, checker.IsNil)
  797. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  798. // Restart docker daemon to test the config has persisted to disk
  799. s.d.Restart()
  800. networks, err = inspectField("foo", "NetworkSettings.Networks")
  801. c.Assert(err, checker.IsNil)
  802. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  803. // start the container and test if we can ping it from another container in the same network
  804. dockerCmd(c, "start", "foo")
  805. c.Assert(waitRun("foo"), checker.IsNil)
  806. ip, err := inspectField("foo", "NetworkSettings.Networks.test.IPAddress")
  807. ip = strings.TrimSpace(ip)
  808. dockerCmd(c, "run", "--net=test", "busybox", "sh", "-c", fmt.Sprintf("ping -c 1 %s", ip))
  809. dockerCmd(c, "stop", "foo")
  810. // Test disconnect
  811. dockerCmd(c, "network", "disconnect", "test", "foo")
  812. networks, err = inspectField("foo", "NetworkSettings.Networks")
  813. c.Assert(err, checker.IsNil)
  814. c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
  815. // Restart docker daemon to test the config has persisted to disk
  816. s.d.Restart()
  817. networks, err = inspectField("foo", "NetworkSettings.Networks")
  818. c.Assert(err, checker.IsNil)
  819. c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
  820. }
  821. func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIP(c *check.C) {
  822. // create two networks
  823. dockerCmd(c, "network", "create", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "n0")
  824. assertNwIsAvailable(c, "n0")
  825. 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")
  826. assertNwIsAvailable(c, "n1")
  827. // run a container on first network specifying the ip addresses
  828. dockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  829. c.Assert(waitRun("c0"), check.IsNil)
  830. verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  831. // connect the container to the second network specifying the preferred ip addresses
  832. dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n1", "c0")
  833. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  834. // Stop and restart the container
  835. dockerCmd(c, "stop", "c0")
  836. dockerCmd(c, "start", "c0")
  837. // verify preferred addresses are applied
  838. verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  839. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  840. // Still it should fail to connect to the default network with a specified IP (whatever ip)
  841. out, _, err := dockerCmdWithError("network", "connect", "--ip", "172.21.55.44", "bridge", "c0")
  842. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  843. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
  844. }
  845. func (s *DockerNetworkSuite) TestDockerNetworkUnsupportedPreferredIP(c *check.C) {
  846. // preferred IP is not supported on predefined networks
  847. for _, mode := range []string{"none", "host", "bridge"} {
  848. checkUnsupportedNetworkAndIP(c, mode)
  849. }
  850. // preferred IP is not supported on networks with no user defined subnets
  851. dockerCmd(c, "network", "create", "n0")
  852. assertNwIsAvailable(c, "n0")
  853. out, _, err := dockerCmdWithError("run", "-d", "--ip", "172.28.99.88", "--net", "n0", "busybox", "top")
  854. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  855. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
  856. out, _, err = dockerCmdWithError("run", "-d", "--ip6", "2001:db8:1234::9988", "--net", "n0", "busybox", "top")
  857. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  858. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
  859. dockerCmd(c, "network", "rm", "n0")
  860. assertNwNotAvailable(c, "n0")
  861. }
  862. func checkUnsupportedNetworkAndIP(c *check.C, nwMode string) {
  863. out, _, err := dockerCmdWithError("run", "-d", "--net", nwMode, "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  864. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  865. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
  866. }
  867. func verifyIPAddresses(c *check.C, cName, nwname, ipv4, ipv6 string) {
  868. out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", nwname), cName)
  869. c.Assert(strings.TrimSpace(out), check.Equals, ipv4)
  870. out, _ = dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.GlobalIPv6Address }}'", nwname), cName)
  871. c.Assert(strings.TrimSpace(out), check.Equals, ipv6)
  872. }
  873. func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectLink(c *check.C) {
  874. testRequires(c, DaemonIsLinux, NotUserNamespace)
  875. dockerCmd(c, "network", "create", "-d", "bridge", "foo1")
  876. dockerCmd(c, "network", "create", "-d", "bridge", "foo2")
  877. dockerCmd(c, "run", "-d", "--net=foo1", "--name=first", "busybox", "top")
  878. c.Assert(waitRun("first"), check.IsNil)
  879. // run a container in user-defined network udlinkNet with a link for an existing container
  880. // and a link for a container that doesnt exist
  881. dockerCmd(c, "run", "-d", "--net=foo1", "--name=second", "--link=first:FirstInFoo1",
  882. "--link=third:bar", "busybox", "top")
  883. c.Assert(waitRun("second"), check.IsNil)
  884. // ping to first and its alias FirstInFoo1 must succeed
  885. _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  886. c.Assert(err, check.IsNil)
  887. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1")
  888. c.Assert(err, check.IsNil)
  889. // connect first container to foo2 network
  890. dockerCmd(c, "network", "connect", "foo2", "first")
  891. // connect second container to foo2 network with a different alias for first container
  892. dockerCmd(c, "network", "connect", "--link=first:FirstInFoo2", "foo2", "second")
  893. // ping the new alias in network foo2
  894. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2")
  895. c.Assert(err, check.IsNil)
  896. // disconnect first container from foo1 network
  897. dockerCmd(c, "network", "disconnect", "foo1", "first")
  898. // link in foo1 network must fail
  899. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1")
  900. c.Assert(err, check.NotNil)
  901. // link in foo2 network must succeed
  902. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2")
  903. c.Assert(err, check.IsNil)
  904. }