docker_cli_network_unix_test.go 41 KB

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