docker_cli_network_unix_test.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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. // check if network connect fails for inactive containers
  385. dockerCmd(c, "stop", containerID)
  386. _, _, err = dockerCmdWithError("network", "connect", "test", containerID)
  387. c.Assert(err, check.NotNil)
  388. dockerCmd(c, "network", "rm", "test")
  389. assertNwNotAvailable(c, "test")
  390. }
  391. func (s *DockerNetworkSuite) TestDockerNetworkIpamMultipleNetworks(c *check.C) {
  392. // test0 bridge network
  393. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
  394. assertNwIsAvailable(c, "test1")
  395. // test2 bridge network does not overlap
  396. dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
  397. assertNwIsAvailable(c, "test2")
  398. // for networks w/o ipam specified, docker will choose proper non-overlapping subnets
  399. dockerCmd(c, "network", "create", "test3")
  400. assertNwIsAvailable(c, "test3")
  401. dockerCmd(c, "network", "create", "test4")
  402. assertNwIsAvailable(c, "test4")
  403. dockerCmd(c, "network", "create", "test5")
  404. assertNwIsAvailable(c, "test5")
  405. // test network with multiple subnets
  406. // bridge network doesn't support multiple subnets. hence, use a dummy driver that supports
  407. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6")
  408. assertNwIsAvailable(c, "test6")
  409. // test network with multiple subnets with valid ipam combinations
  410. // also check same subnet across networks when the driver supports it.
  411. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
  412. "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16",
  413. "--gateway=192.168.0.100", "--gateway=192.170.0.100",
  414. "--ip-range=192.168.1.0/24",
  415. "--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6",
  416. "--aux-address", "a=192.170.1.5", "--aux-address", "b=192.170.1.6",
  417. "test7")
  418. assertNwIsAvailable(c, "test7")
  419. // cleanup
  420. for i := 1; i < 8; i++ {
  421. dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
  422. }
  423. }
  424. func (s *DockerNetworkSuite) TestDockerNetworkCustomIpam(c *check.C) {
  425. // Create a bridge network using custom ipam driver
  426. dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "br0")
  427. assertNwIsAvailable(c, "br0")
  428. // Verify expected network ipam fields are there
  429. nr := getNetworkResource(c, "br0")
  430. c.Assert(nr.Driver, checker.Equals, "bridge")
  431. c.Assert(nr.IPAM.Driver, checker.Equals, dummyIpamDriver)
  432. // remove network and exercise remote ipam driver
  433. dockerCmd(c, "network", "rm", "br0")
  434. assertNwNotAvailable(c, "br0")
  435. }
  436. func (s *DockerNetworkSuite) TestDockerNetworkInspect(c *check.C) {
  437. // if unspecified, network gateway will be selected from inside preferred pool
  438. 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")
  439. assertNwIsAvailable(c, "br0")
  440. nr := getNetworkResource(c, "br0")
  441. c.Assert(nr.Driver, checker.Equals, "bridge")
  442. c.Assert(nr.Scope, checker.Equals, "local")
  443. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  444. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  445. c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16")
  446. c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24")
  447. c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254")
  448. dockerCmd(c, "network", "rm", "br0")
  449. }
  450. func (s *DockerNetworkSuite) TestDockerNetworkIpamInvalidCombinations(c *check.C) {
  451. // network with ip-range out of subnet range
  452. _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
  453. c.Assert(err, check.NotNil)
  454. // network with multiple gateways for a single subnet
  455. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
  456. c.Assert(err, check.NotNil)
  457. // Multiple overlapping subnets in the same network must fail
  458. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
  459. c.Assert(err, check.NotNil)
  460. // overlapping subnets across networks must fail
  461. // create a valid test0 network
  462. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
  463. assertNwIsAvailable(c, "test0")
  464. // create an overlapping test1 network
  465. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
  466. c.Assert(err, check.NotNil)
  467. dockerCmd(c, "network", "rm", "test0")
  468. }
  469. func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) {
  470. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
  471. assertNwIsAvailable(c, "testopt")
  472. gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
  473. c.Assert(gopts, checker.NotNil)
  474. opts, ok := gopts.(map[string]interface{})
  475. c.Assert(ok, checker.Equals, true)
  476. c.Assert(opts["opt1"], checker.Equals, "drv1")
  477. c.Assert(opts["opt2"], checker.Equals, "drv2")
  478. dockerCmd(c, "network", "rm", "testopt")
  479. }
  480. func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *check.C) {
  481. testRequires(c, ExecSupport)
  482. // On default bridge network built-in service discovery should not happen
  483. hostsFile := "/etc/hosts"
  484. bridgeName := "external-bridge"
  485. bridgeIP := "192.169.255.254/24"
  486. out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
  487. c.Assert(err, check.IsNil, check.Commentf(out))
  488. defer deleteInterface(c, bridgeName)
  489. err = s.d.StartWithBusybox("--bridge", bridgeName)
  490. c.Assert(err, check.IsNil)
  491. defer s.d.Restart()
  492. // run two containers and store first container's etc/hosts content
  493. out, err = s.d.Cmd("run", "-d", "busybox", "top")
  494. c.Assert(err, check.IsNil)
  495. cid1 := strings.TrimSpace(out)
  496. defer s.d.Cmd("stop", cid1)
  497. hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  498. c.Assert(err, checker.IsNil)
  499. out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top")
  500. c.Assert(err, check.IsNil)
  501. cid2 := strings.TrimSpace(out)
  502. // verify first container's etc/hosts file has not changed after spawning the second named container
  503. hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  504. c.Assert(err, checker.IsNil)
  505. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  506. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  507. // stop container 2 and verify first container's etc/hosts has not changed
  508. _, err = s.d.Cmd("stop", cid2)
  509. c.Assert(err, check.IsNil)
  510. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  511. c.Assert(err, checker.IsNil)
  512. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  513. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  514. // but discovery is on when connecting to non default bridge network
  515. network := "anotherbridge"
  516. out, err = s.d.Cmd("network", "create", network)
  517. c.Assert(err, check.IsNil, check.Commentf(out))
  518. defer s.d.Cmd("network", "rm", network)
  519. out, err = s.d.Cmd("network", "connect", network, cid1)
  520. c.Assert(err, check.IsNil, check.Commentf(out))
  521. hosts, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  522. c.Assert(err, checker.IsNil)
  523. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  524. c.Assert(err, checker.IsNil)
  525. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  526. check.Commentf("Unexpected %s change on second network connection", hostsFile))
  527. }
  528. func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
  529. testRequires(c, ExecSupport)
  530. hostsFile := "/etc/hosts"
  531. cstmBridgeNw := "custom-bridge-nw"
  532. cstmBridgeNw1 := "custom-bridge-nw1"
  533. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw)
  534. assertNwIsAvailable(c, cstmBridgeNw)
  535. // run two anonymous containers and store their etc/hosts content
  536. out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  537. cid1 := strings.TrimSpace(out)
  538. hosts1, err := readContainerFileWithExec(cid1, hostsFile)
  539. c.Assert(err, checker.IsNil)
  540. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  541. cid2 := strings.TrimSpace(out)
  542. hosts2, err := readContainerFileWithExec(cid2, hostsFile)
  543. c.Assert(err, checker.IsNil)
  544. // verify first container etc/hosts file has not changed
  545. hosts1post, err := readContainerFileWithExec(cid1, hostsFile)
  546. c.Assert(err, checker.IsNil)
  547. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  548. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  549. // Connect the 2nd container to a new network and verify the
  550. // first container /etc/hosts file still hasn't changed.
  551. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1)
  552. assertNwIsAvailable(c, cstmBridgeNw1)
  553. dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2)
  554. hosts2, err = readContainerFileWithExec(cid2, hostsFile)
  555. c.Assert(err, checker.IsNil)
  556. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  557. c.Assert(err, checker.IsNil)
  558. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  559. check.Commentf("Unexpected %s change on container connect", hostsFile))
  560. // start a named container
  561. cName := "AnyName"
  562. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top")
  563. cid3 := strings.TrimSpace(out)
  564. // verify that container 1 and 2 can ping the named container
  565. dockerCmd(c, "exec", cid1, "ping", "-c", "1", cName)
  566. dockerCmd(c, "exec", cid2, "ping", "-c", "1", cName)
  567. // Stop named container and verify first two containers' etc/hosts file hasn't changed
  568. dockerCmd(c, "stop", cid3)
  569. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  570. c.Assert(err, checker.IsNil)
  571. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  572. check.Commentf("Unexpected %s change on name container creation", hostsFile))
  573. hosts2post, err := readContainerFileWithExec(cid2, hostsFile)
  574. c.Assert(err, checker.IsNil)
  575. c.Assert(string(hosts2), checker.Equals, string(hosts2post),
  576. check.Commentf("Unexpected %s change on name container creation", hostsFile))
  577. // verify that container 1 and 2 can't ping the named container now
  578. _, _, err = dockerCmdWithError("exec", cid1, "ping", "-c", "1", cName)
  579. c.Assert(err, check.NotNil)
  580. _, _, err = dockerCmdWithError("exec", cid2, "ping", "-c", "1", cName)
  581. c.Assert(err, check.NotNil)
  582. }
  583. func (s *DockerNetworkSuite) TestDockerNetworkLinkOndefaultNetworkOnly(c *check.C) {
  584. // Link feature must work only on default network, and not across networks
  585. cnt1 := "container1"
  586. cnt2 := "container2"
  587. network := "anotherbridge"
  588. // Run first container on default network
  589. dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top")
  590. // Create another network and run the second container on it
  591. dockerCmd(c, "network", "create", network)
  592. assertNwIsAvailable(c, network)
  593. dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top")
  594. // Try launching a container on default network, linking to the first container. Must succeed
  595. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top")
  596. // Try launching a container on default network, linking to the second container. Must fail
  597. _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  598. c.Assert(err, checker.NotNil)
  599. // Connect second container to default network. Now a container on default network can link to it
  600. dockerCmd(c, "network", "connect", "bridge", cnt2)
  601. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  602. }
  603. func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) {
  604. // Verify exposed ports are present in ps output when running a container on
  605. // a network managed by a driver which does not provide the default gateway
  606. // for the container
  607. nwn := "ov"
  608. ctn := "bb"
  609. port1 := 80
  610. port2 := 443
  611. expose1 := fmt.Sprintf("--expose=%d", port1)
  612. expose2 := fmt.Sprintf("--expose=%d", port2)
  613. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  614. assertNwIsAvailable(c, nwn)
  615. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top")
  616. // Check docker ps o/p for last created container reports the unpublished ports
  617. unpPort1 := fmt.Sprintf("%d/tcp", port1)
  618. unpPort2 := fmt.Sprintf("%d/tcp", port2)
  619. out, _ := dockerCmd(c, "ps", "-n=1")
  620. // Missing unpublished ports in docker ps output
  621. c.Assert(out, checker.Contains, unpPort1)
  622. // Missing unpublished ports in docker ps output
  623. c.Assert(out, checker.Contains, unpPort2)
  624. }
  625. func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) {
  626. // Verify endpoint MAC address is correctly populated in container's network settings
  627. nwn := "ov"
  628. ctn := "bb"
  629. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  630. assertNwIsAvailable(c, nwn)
  631. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top")
  632. mac, err := inspectField(ctn, "NetworkSettings.Networks."+nwn+".MacAddress")
  633. c.Assert(err, checker.IsNil)
  634. c.Assert(mac, checker.Equals, "a0:b1:c2:d3:e4:f5")
  635. }
  636. func (s *DockerSuite) TestInspectApiMultipleNetworks(c *check.C) {
  637. dockerCmd(c, "network", "create", "mybridge1")
  638. dockerCmd(c, "network", "create", "mybridge2")
  639. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  640. id := strings.TrimSpace(out)
  641. c.Assert(waitRun(id), check.IsNil)
  642. dockerCmd(c, "network", "connect", "mybridge1", id)
  643. dockerCmd(c, "network", "connect", "mybridge2", id)
  644. body := getInspectBody(c, "v1.20", id)
  645. var inspect120 v1p20.ContainerJSON
  646. err := json.Unmarshal(body, &inspect120)
  647. c.Assert(err, checker.IsNil)
  648. versionedIP := inspect120.NetworkSettings.IPAddress
  649. body = getInspectBody(c, "v1.21", id)
  650. var inspect121 types.ContainerJSON
  651. err = json.Unmarshal(body, &inspect121)
  652. c.Assert(err, checker.IsNil)
  653. c.Assert(inspect121.NetworkSettings.Networks, checker.HasLen, 3)
  654. bridge := inspect121.NetworkSettings.Networks["bridge"]
  655. c.Assert(bridge.IPAddress, checker.Equals, versionedIP)
  656. c.Assert(bridge.IPAddress, checker.Equals, inspect121.NetworkSettings.IPAddress)
  657. }
  658. func connectContainerToNetworks(c *check.C, d *Daemon, cName string, nws []string) {
  659. // Run a container on the default network
  660. out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
  661. c.Assert(err, checker.IsNil, check.Commentf(out))
  662. // Attach the container to other three networks
  663. for _, nw := range nws {
  664. out, err = d.Cmd("network", "create", nw)
  665. c.Assert(err, checker.IsNil, check.Commentf(out))
  666. out, err = d.Cmd("network", "connect", nw, cName)
  667. c.Assert(err, checker.IsNil, check.Commentf(out))
  668. }
  669. }
  670. func verifyContainerIsConnectedToNetworks(c *check.C, d *Daemon, cName string, nws []string) {
  671. // Verify container is connected to all three networks
  672. for _, nw := range nws {
  673. out, err := d.Cmd("inspect", "-f", fmt.Sprintf("{{.NetworkSettings.Networks.%s}}", nw), cName)
  674. c.Assert(err, checker.IsNil, check.Commentf(out))
  675. c.Assert(out, checker.Not(checker.Equals), "<no value>\n")
  676. }
  677. }
  678. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRestart(c *check.C) {
  679. cName := "bb"
  680. nwList := []string{"nw1", "nw2", "nw3"}
  681. s.d.StartWithBusybox()
  682. connectContainerToNetworks(c, s.d, cName, nwList)
  683. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  684. // Reload daemon
  685. s.d.Restart()
  686. _, err := s.d.Cmd("start", cName)
  687. c.Assert(err, checker.IsNil)
  688. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  689. }
  690. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksUngracefulDaemonRestart(c *check.C) {
  691. cName := "cc"
  692. nwList := []string{"nw1", "nw2", "nw3"}
  693. s.d.StartWithBusybox()
  694. connectContainerToNetworks(c, s.d, cName, nwList)
  695. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  696. // Kill daemon and restart
  697. if err := s.d.cmd.Process.Kill(); err != nil {
  698. c.Fatal(err)
  699. }
  700. s.d.Restart()
  701. // Restart container
  702. _, err := s.d.Cmd("start", cName)
  703. c.Assert(err, checker.IsNil)
  704. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  705. }
  706. func (s *DockerNetworkSuite) TestDockerNetworkRunNetByID(c *check.C) {
  707. out, _ := dockerCmd(c, "network", "create", "one")
  708. dockerCmd(c, "run", "-d", "--net", strings.TrimSpace(out), "busybox", "top")
  709. }
  710. func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c *check.C) {
  711. testRequires(c, DaemonIsLinux, NotUserNamespace)
  712. s.d.StartWithBusybox()
  713. // Run a few containers on host network
  714. for i := 0; i < 10; i++ {
  715. cName := fmt.Sprintf("hostc-%d", i)
  716. out, err := s.d.Cmd("run", "-d", "--name", cName, "--net=host", "--restart=always", "busybox", "top")
  717. c.Assert(err, checker.IsNil, check.Commentf(out))
  718. }
  719. // Kill daemon ungracefully and restart
  720. if err := s.d.cmd.Process.Kill(); err != nil {
  721. c.Fatal(err)
  722. }
  723. s.d.Restart()
  724. // make sure all the containers are up and running
  725. for i := 0; i < 10; i++ {
  726. cName := fmt.Sprintf("hostc-%d", i)
  727. runningOut, err := s.d.Cmd("inspect", "--format='{{.State.Running}}'", cName)
  728. c.Assert(err, checker.IsNil)
  729. c.Assert(strings.TrimSpace(runningOut), checker.Equals, "true")
  730. }
  731. }
  732. func (s *DockerNetworkSuite) TestDockerNetworkConnectToHostFromOtherNetwork(c *check.C) {
  733. dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
  734. c.Assert(waitRun("container1"), check.IsNil)
  735. dockerCmd(c, "network", "disconnect", "bridge", "container1")
  736. out, _, err := dockerCmdWithError("network", "connect", "host", "container1")
  737. c.Assert(err, checker.NotNil, check.Commentf(out))
  738. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  739. }
  740. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromHost(c *check.C) {
  741. dockerCmd(c, "run", "-d", "--name", "container1", "--net=host", "busybox", "top")
  742. c.Assert(waitRun("container1"), check.IsNil)
  743. out, _, err := dockerCmdWithError("network", "disconnect", "host", "container1")
  744. c.Assert(err, checker.NotNil, check.Commentf("Should err out disconnect from host"))
  745. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  746. }
  747. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithPortMapping(c *check.C) {
  748. dockerCmd(c, "network", "create", "test1")
  749. dockerCmd(c, "run", "-d", "--name", "c1", "-p", "5000:5000", "busybox", "top")
  750. c.Assert(waitRun("c1"), check.IsNil)
  751. dockerCmd(c, "network", "connect", "test1", "c1")
  752. }
  753. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithMac(c *check.C) {
  754. macAddress := "02:42:ac:11:00:02"
  755. dockerCmd(c, "network", "create", "mynetwork")
  756. dockerCmd(c, "run", "--name=test", "-d", "--mac-address", macAddress, "busybox", "top")
  757. c.Assert(waitRun("test"), check.IsNil)
  758. mac1, err := inspectField("test", "NetworkSettings.Networks.bridge.MacAddress")
  759. c.Assert(err, checker.IsNil)
  760. c.Assert(strings.TrimSpace(mac1), checker.Equals, macAddress)
  761. dockerCmd(c, "network", "connect", "mynetwork", "test")
  762. mac2, err := inspectField("test", "NetworkSettings.Networks.mynetwork.MacAddress")
  763. c.Assert(err, checker.IsNil)
  764. c.Assert(strings.TrimSpace(mac2), checker.Not(checker.Equals), strings.TrimSpace(mac1))
  765. }
  766. func (s *DockerNetworkSuite) TestDockerNetworkInspectCreatedContainer(c *check.C) {
  767. dockerCmd(c, "create", "--name", "test", "busybox")
  768. networks, err := inspectField("test", "NetworkSettings.Networks")
  769. c.Assert(err, checker.IsNil)
  770. c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should return 'bridge' network"))
  771. }
  772. func (s *DockerNetworkSuite) TestDockerNetworkRestartWithMulipleNetworks(c *check.C) {
  773. dockerCmd(c, "network", "create", "test")
  774. dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
  775. c.Assert(waitRun("foo"), checker.IsNil)
  776. dockerCmd(c, "network", "connect", "test", "foo")
  777. dockerCmd(c, "restart", "foo")
  778. networks, err := inspectField("foo", "NetworkSettings.Networks")
  779. c.Assert(err, checker.IsNil)
  780. c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should contain 'bridge' network"))
  781. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' netwokr"))
  782. }
  783. func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIP(c *check.C) {
  784. // create two networks
  785. dockerCmd(c, "network", "create", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "n0")
  786. assertNwIsAvailable(c, "n0")
  787. 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")
  788. assertNwIsAvailable(c, "n1")
  789. // run a container on first network specifying the ip addresses
  790. dockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  791. c.Assert(waitRun("c0"), check.IsNil)
  792. verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  793. // connect the container to the second network specifying the preferred ip addresses
  794. dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n1", "c0")
  795. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  796. // Stop and restart the container
  797. dockerCmd(c, "stop", "c0")
  798. dockerCmd(c, "start", "c0")
  799. // verify preferred addresses are applied
  800. verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  801. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  802. // Still it should fail to connect to the default network with a specified IP (whatever ip)
  803. out, _, err := dockerCmdWithError("network", "connect", "--ip", "172.21.55.44", "bridge", "c0")
  804. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  805. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
  806. }
  807. func (s *DockerNetworkSuite) TestDockerNetworkUnsupportedPreferredIP(c *check.C) {
  808. // preferred IP is not supported on predefined networks
  809. for _, mode := range []string{"none", "host", "bridge"} {
  810. checkUnsupportedNetworkAndIP(c, mode)
  811. }
  812. // preferred IP is not supported on networks with no user defined subnets
  813. dockerCmd(c, "network", "create", "n0")
  814. assertNwIsAvailable(c, "n0")
  815. out, _, err := dockerCmdWithError("run", "-d", "--ip", "172.28.99.88", "--net", "n0", "busybox", "top")
  816. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  817. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
  818. out, _, err = dockerCmdWithError("run", "-d", "--ip6", "2001:db8:1234::9988", "--net", "n0", "busybox", "top")
  819. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  820. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
  821. dockerCmd(c, "network", "rm", "n0")
  822. assertNwNotAvailable(c, "n0")
  823. }
  824. func checkUnsupportedNetworkAndIP(c *check.C, nwMode string) {
  825. out, _, err := dockerCmdWithError("run", "-d", "--net", nwMode, "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  826. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  827. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
  828. }
  829. func verifyIPAddresses(c *check.C, cName, nwname, ipv4, ipv6 string) {
  830. out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", nwname), cName)
  831. c.Assert(strings.TrimSpace(out), check.Equals, ipv4)
  832. out, _ = dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.GlobalIPv6Address }}'", nwname), cName)
  833. c.Assert(strings.TrimSpace(out), check.Equals, ipv6)
  834. }