docker_cli_network_unix_test.go 45 KB

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