docker_cli_network_unix_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // +build !windows
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "net/http/httptest"
  10. "os"
  11. "strings"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/pkg/integration/checker"
  14. "github.com/docker/libnetwork/driverapi"
  15. remoteapi "github.com/docker/libnetwork/drivers/remote/api"
  16. "github.com/docker/libnetwork/ipamapi"
  17. remoteipam "github.com/docker/libnetwork/ipams/remote/api"
  18. "github.com/docker/libnetwork/netlabel"
  19. "github.com/go-check/check"
  20. )
  21. const dummyNetworkDriver = "dummy-network-driver"
  22. const dummyIpamDriver = "dummy-ipam-driver"
  23. var remoteDriverNetworkRequest remoteapi.CreateNetworkRequest
  24. func init() {
  25. check.Suite(&DockerNetworkSuite{
  26. ds: &DockerSuite{},
  27. })
  28. }
  29. type DockerNetworkSuite struct {
  30. server *httptest.Server
  31. ds *DockerSuite
  32. d *Daemon
  33. }
  34. func (s *DockerNetworkSuite) SetUpTest(c *check.C) {
  35. s.d = NewDaemon(c)
  36. }
  37. func (s *DockerNetworkSuite) TearDownTest(c *check.C) {
  38. s.d.Stop()
  39. s.ds.TearDownTest(c)
  40. }
  41. func (s *DockerNetworkSuite) SetUpSuite(c *check.C) {
  42. mux := http.NewServeMux()
  43. s.server = httptest.NewServer(mux)
  44. c.Assert(s.server, check.NotNil, check.Commentf("Failed to start a HTTP Server"))
  45. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  46. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  47. fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType)
  48. })
  49. // Network driver implementation
  50. mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  51. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  52. fmt.Fprintf(w, `{"Scope":"local"}`)
  53. })
  54. mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  55. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  56. if err != nil {
  57. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  58. return
  59. }
  60. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  61. fmt.Fprintf(w, "null")
  62. })
  63. mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  64. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  65. fmt.Fprintf(w, "null")
  66. })
  67. // Ipam Driver implementation
  68. var (
  69. poolRequest remoteipam.RequestPoolRequest
  70. poolReleaseReq remoteipam.ReleasePoolRequest
  71. addressRequest remoteipam.RequestAddressRequest
  72. addressReleaseReq remoteipam.ReleaseAddressRequest
  73. lAS = "localAS"
  74. gAS = "globalAS"
  75. pool = "172.28.0.0/16"
  76. poolID = lAS + "/" + pool
  77. gw = "172.28.255.254/16"
  78. )
  79. mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  80. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  81. fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`)
  82. })
  83. mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  84. err := json.NewDecoder(r.Body).Decode(&poolRequest)
  85. if err != nil {
  86. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  87. return
  88. }
  89. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  90. if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS {
  91. fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`)
  92. } else if poolRequest.Pool != "" && poolRequest.Pool != pool {
  93. fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`)
  94. } else {
  95. fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`)
  96. }
  97. })
  98. mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  99. err := json.NewDecoder(r.Body).Decode(&addressRequest)
  100. if err != nil {
  101. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  102. return
  103. }
  104. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  105. // make sure libnetwork is now querying on the expected pool id
  106. if addressRequest.PoolID != poolID {
  107. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  108. } else if addressRequest.Address != "" {
  109. fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`)
  110. } else {
  111. fmt.Fprintf(w, `{"Address":"`+gw+`"}`)
  112. }
  113. })
  114. mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  115. err := json.NewDecoder(r.Body).Decode(&addressReleaseReq)
  116. if err != nil {
  117. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  118. return
  119. }
  120. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  121. // make sure libnetwork is now asking to release the expected address fro mthe expected poolid
  122. if addressRequest.PoolID != poolID {
  123. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  124. } else if addressReleaseReq.Address != gw {
  125. fmt.Fprintf(w, `{"Error":"unknown address"}`)
  126. } else {
  127. fmt.Fprintf(w, "null")
  128. }
  129. })
  130. mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  131. err := json.NewDecoder(r.Body).Decode(&poolReleaseReq)
  132. if err != nil {
  133. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  134. return
  135. }
  136. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  137. // make sure libnetwork is now asking to release the expected poolid
  138. if addressRequest.PoolID != poolID {
  139. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  140. } else {
  141. fmt.Fprintf(w, "null")
  142. }
  143. })
  144. err := os.MkdirAll("/etc/docker/plugins", 0755)
  145. c.Assert(err, checker.IsNil)
  146. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", dummyNetworkDriver)
  147. err = ioutil.WriteFile(fileName, []byte(s.server.URL), 0644)
  148. c.Assert(err, checker.IsNil)
  149. ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", dummyIpamDriver)
  150. err = ioutil.WriteFile(ipamFileName, []byte(s.server.URL), 0644)
  151. c.Assert(err, checker.IsNil)
  152. }
  153. func (s *DockerNetworkSuite) TearDownSuite(c *check.C) {
  154. if s.server == nil {
  155. return
  156. }
  157. s.server.Close()
  158. err := os.RemoveAll("/etc/docker/plugins")
  159. c.Assert(err, checker.IsNil)
  160. }
  161. func assertNwIsAvailable(c *check.C, name string) {
  162. if !isNwPresent(c, name) {
  163. c.Fatalf("Network %s not found in network ls o/p", name)
  164. }
  165. }
  166. func assertNwNotAvailable(c *check.C, name string) {
  167. if isNwPresent(c, name) {
  168. c.Fatalf("Found network %s in network ls o/p", name)
  169. }
  170. }
  171. func isNwPresent(c *check.C, name string) bool {
  172. out, _ := dockerCmd(c, "network", "ls")
  173. lines := strings.Split(out, "\n")
  174. for i := 1; i < len(lines)-1; i++ {
  175. if strings.Contains(lines[i], name) {
  176. return true
  177. }
  178. }
  179. return false
  180. }
  181. func getNwResource(c *check.C, name string) *types.NetworkResource {
  182. out, _ := dockerCmd(c, "network", "inspect", name)
  183. nr := []types.NetworkResource{}
  184. err := json.Unmarshal([]byte(out), &nr)
  185. c.Assert(err, check.IsNil)
  186. return &nr[0]
  187. }
  188. func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) {
  189. defaults := []string{"bridge", "host", "none"}
  190. for _, nn := range defaults {
  191. assertNwIsAvailable(c, nn)
  192. }
  193. }
  194. func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *check.C) {
  195. dockerCmd(c, "network", "create", "test")
  196. assertNwIsAvailable(c, "test")
  197. dockerCmd(c, "network", "rm", "test")
  198. assertNwNotAvailable(c, "test")
  199. }
  200. func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *check.C) {
  201. out, _, err := dockerCmdWithError("network", "rm", "test")
  202. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  203. }
  204. func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) {
  205. out, _ := dockerCmd(c, "network", "inspect", "host", "none")
  206. networkResources := []types.NetworkResource{}
  207. err := json.Unmarshal([]byte(out), &networkResources)
  208. c.Assert(err, check.IsNil)
  209. c.Assert(networkResources, checker.HasLen, 2)
  210. // Should print an error, return an exitCode 1 *but* should print the host network
  211. out, exitCode, err := dockerCmdWithError("network", "inspect", "host", "nonexistent")
  212. c.Assert(err, checker.NotNil)
  213. c.Assert(exitCode, checker.Equals, 1)
  214. c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
  215. networkResources = []types.NetworkResource{}
  216. inspectOut := strings.SplitN(out, "\n", 2)[1]
  217. err = json.Unmarshal([]byte(inspectOut), &networkResources)
  218. c.Assert(networkResources, checker.HasLen, 1)
  219. // Should print an error and return an exitCode, nothing else
  220. out, exitCode, err = dockerCmdWithError("network", "inspect", "nonexistent")
  221. c.Assert(err, checker.NotNil)
  222. c.Assert(exitCode, checker.Equals, 1)
  223. c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
  224. }
  225. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) {
  226. dockerCmd(c, "network", "create", "test")
  227. assertNwIsAvailable(c, "test")
  228. nr := getNwResource(c, "test")
  229. c.Assert(nr.Name, checker.Equals, "test")
  230. c.Assert(len(nr.Containers), checker.Equals, 0)
  231. // run a container
  232. out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  233. c.Assert(waitRun("test"), check.IsNil)
  234. containerID := strings.TrimSpace(out)
  235. // connect the container to the test network
  236. dockerCmd(c, "network", "connect", "test", containerID)
  237. // inspect the network to make sure container is connected
  238. nr = getNetworkResource(c, nr.ID)
  239. c.Assert(len(nr.Containers), checker.Equals, 1)
  240. c.Assert(nr.Containers[containerID], check.NotNil)
  241. // check if container IP matches network inspect
  242. ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address)
  243. c.Assert(err, check.IsNil)
  244. containerIP := findContainerIP(c, "test", "test")
  245. c.Assert(ip.String(), checker.Equals, containerIP)
  246. // disconnect container from the network
  247. dockerCmd(c, "network", "disconnect", "test", containerID)
  248. nr = getNwResource(c, "test")
  249. c.Assert(nr.Name, checker.Equals, "test")
  250. c.Assert(len(nr.Containers), checker.Equals, 0)
  251. // check if network connect fails for inactive containers
  252. dockerCmd(c, "stop", containerID)
  253. _, _, err = dockerCmdWithError("network", "connect", "test", containerID)
  254. c.Assert(err, check.NotNil)
  255. dockerCmd(c, "network", "rm", "test")
  256. assertNwNotAvailable(c, "test")
  257. }
  258. func (s *DockerNetworkSuite) TestDockerNetworkIpamMultipleNetworks(c *check.C) {
  259. // test0 bridge network
  260. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
  261. assertNwIsAvailable(c, "test1")
  262. // test2 bridge network does not overlap
  263. dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
  264. assertNwIsAvailable(c, "test2")
  265. // for networks w/o ipam specified, docker will choose proper non-overlapping subnets
  266. dockerCmd(c, "network", "create", "test3")
  267. assertNwIsAvailable(c, "test3")
  268. dockerCmd(c, "network", "create", "test4")
  269. assertNwIsAvailable(c, "test4")
  270. dockerCmd(c, "network", "create", "test5")
  271. assertNwIsAvailable(c, "test5")
  272. // test network with multiple subnets
  273. // bridge network doesnt support multiple subnets. hence, use a dummy driver that supports
  274. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6")
  275. assertNwIsAvailable(c, "test6")
  276. // test network with multiple subnets with valid ipam combinations
  277. // also check same subnet across networks when the driver supports it.
  278. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
  279. "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16",
  280. "--gateway=192.168.0.100", "--gateway=192.170.0.100",
  281. "--ip-range=192.168.1.0/24",
  282. "--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6",
  283. "--aux-address", "a=192.170.1.5", "--aux-address", "b=192.170.1.6",
  284. "test7")
  285. assertNwIsAvailable(c, "test7")
  286. // cleanup
  287. for i := 1; i < 8; i++ {
  288. dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
  289. }
  290. }
  291. func (s *DockerNetworkSuite) TestDockerNetworkCustomIpam(c *check.C) {
  292. // Create a bridge network using custom ipam driver
  293. dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "br0")
  294. assertNwIsAvailable(c, "br0")
  295. // Verify expected network ipam fields are there
  296. nr := getNetworkResource(c, "br0")
  297. c.Assert(nr.Driver, checker.Equals, "bridge")
  298. c.Assert(nr.IPAM.Driver, checker.Equals, dummyIpamDriver)
  299. // remove network and exercise remote ipam driver
  300. dockerCmd(c, "network", "rm", "br0")
  301. assertNwNotAvailable(c, "br0")
  302. }
  303. func (s *DockerNetworkSuite) TestDockerNetworkInspect(c *check.C) {
  304. // if unspecified, network gateway will be selected from inside preferred pool
  305. 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")
  306. assertNwIsAvailable(c, "br0")
  307. nr := getNetworkResource(c, "br0")
  308. c.Assert(nr.Driver, checker.Equals, "bridge")
  309. c.Assert(nr.Scope, checker.Equals, "local")
  310. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  311. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  312. c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16")
  313. c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24")
  314. c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254")
  315. dockerCmd(c, "network", "rm", "br0")
  316. }
  317. func (s *DockerNetworkSuite) TestDockerNetworkIpamInvalidCombinations(c *check.C) {
  318. // network with ip-range out of subnet range
  319. _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
  320. c.Assert(err, check.NotNil)
  321. // network with multiple gateways for a single subnet
  322. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
  323. c.Assert(err, check.NotNil)
  324. // Multiple overlaping subnets in the same network must fail
  325. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
  326. c.Assert(err, check.NotNil)
  327. // overlapping subnets across networks must fail
  328. // create a valid test0 network
  329. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
  330. assertNwIsAvailable(c, "test0")
  331. // create an overlapping test1 network
  332. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
  333. c.Assert(err, check.NotNil)
  334. dockerCmd(c, "network", "rm", "test0")
  335. }
  336. func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) {
  337. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
  338. assertNwIsAvailable(c, "testopt")
  339. gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
  340. c.Assert(gopts, checker.NotNil)
  341. opts, ok := gopts.(map[string]interface{})
  342. c.Assert(ok, checker.Equals, true)
  343. c.Assert(opts["opt1"], checker.Equals, "drv1")
  344. c.Assert(opts["opt2"], checker.Equals, "drv2")
  345. dockerCmd(c, "network", "rm", "testopt")
  346. }
  347. func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *check.C) {
  348. // On default bridge network built-in service discovery should not happen
  349. hostsFile := "/etc/hosts"
  350. bridgeName := "external-bridge"
  351. bridgeIP := "192.169.255.254/24"
  352. out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
  353. c.Assert(err, check.IsNil, check.Commentf(out))
  354. defer deleteInterface(c, bridgeName)
  355. err = s.d.StartWithBusybox("--bridge", bridgeName)
  356. c.Assert(err, check.IsNil)
  357. defer s.d.Restart()
  358. // run two containers and store first container's etc/hosts content
  359. out, err = s.d.Cmd("run", "-d", "busybox", "top")
  360. c.Assert(err, check.IsNil)
  361. cid1 := strings.TrimSpace(out)
  362. defer s.d.Cmd("stop", cid1)
  363. hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  364. c.Assert(err, checker.IsNil)
  365. out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top")
  366. c.Assert(err, check.IsNil)
  367. cid2 := strings.TrimSpace(out)
  368. // verify first container's etc/hosts file has not changed after spawning the second named container
  369. hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  370. c.Assert(err, checker.IsNil)
  371. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  372. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  373. // stop container 2 and verify first container's etc/hosts has not changed
  374. _, err = s.d.Cmd("stop", cid2)
  375. c.Assert(err, check.IsNil)
  376. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  377. c.Assert(err, checker.IsNil)
  378. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  379. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  380. // but discovery is on when connecting to non default bridge network
  381. network := "anotherbridge"
  382. out, err = s.d.Cmd("network", "create", network)
  383. c.Assert(err, check.IsNil, check.Commentf(out))
  384. defer s.d.Cmd("network", "rm", network)
  385. out, err = s.d.Cmd("network", "connect", network, cid1)
  386. c.Assert(err, check.IsNil, check.Commentf(out))
  387. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  388. c.Assert(err, checker.IsNil)
  389. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  390. check.Commentf("Unexpected %s change on second network connection", hostsFile))
  391. cName := "container3"
  392. out, err = s.d.Cmd("run", "-d", "--net", network, "--name", cName, "busybox", "top")
  393. c.Assert(err, check.IsNil, check.Commentf(out))
  394. cid3 := strings.TrimSpace(out)
  395. defer s.d.Cmd("stop", cid3)
  396. // container1 etc/hosts file should contain an entry for the third container
  397. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  398. c.Assert(err, checker.IsNil)
  399. c.Assert(string(hostsPost), checker.Contains, cName,
  400. check.Commentf("Container 1 %s file does not contain entries for named container %q: %s", hostsFile, cName, string(hostsPost)))
  401. // on container3 disconnect, first container's etc/hosts should go back to original form
  402. out, err = s.d.Cmd("network", "disconnect", network, cid3)
  403. c.Assert(err, check.IsNil, check.Commentf(out))
  404. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  405. c.Assert(err, checker.IsNil)
  406. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  407. check.Commentf("Unexpected %s content after disconnecting from second network", hostsFile))
  408. }
  409. func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
  410. hostsFile := "/etc/hosts"
  411. cstmBridgeNw := "custom-bridge-nw"
  412. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw)
  413. assertNwIsAvailable(c, cstmBridgeNw)
  414. // run two anonymous containers and store their etc/hosts content
  415. out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  416. cid1 := strings.TrimSpace(out)
  417. hosts1, err := readContainerFileWithExec(cid1, hostsFile)
  418. c.Assert(err, checker.IsNil)
  419. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  420. cid2 := strings.TrimSpace(out)
  421. hosts2, err := readContainerFileWithExec(cid2, hostsFile)
  422. c.Assert(err, checker.IsNil)
  423. // verify first container etc/hosts file has not changed
  424. hosts1post, err := readContainerFileWithExec(cid1, hostsFile)
  425. c.Assert(err, checker.IsNil)
  426. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  427. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  428. // start a named container
  429. cName := "AnyName"
  430. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top")
  431. cid3 := strings.TrimSpace(out)
  432. // verify etc/hosts file for first two containers contains the named container entry
  433. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  434. c.Assert(err, checker.IsNil)
  435. c.Assert(string(hosts1post), checker.Contains, cName,
  436. check.Commentf("Container 1 %s file does not contain entries for named container %q: %s", hostsFile, cName, string(hosts1post)))
  437. hosts2post, err := readContainerFileWithExec(cid2, hostsFile)
  438. c.Assert(err, checker.IsNil)
  439. c.Assert(string(hosts2post), checker.Contains, cName,
  440. check.Commentf("Container 2 %s file does not contain entries for named container %q: %s", hostsFile, cName, string(hosts2post)))
  441. // Stop named container and verify first two containers' etc/hosts entries are back to original
  442. dockerCmd(c, "stop", cid3)
  443. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  444. c.Assert(err, checker.IsNil)
  445. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  446. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  447. hosts2post, err = readContainerFileWithExec(cid2, hostsFile)
  448. c.Assert(err, checker.IsNil)
  449. c.Assert(string(hosts2), checker.Equals, string(hosts2post),
  450. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  451. }
  452. func (s *DockerNetworkSuite) TestDockerNetworkLinkOndefaultNetworkOnly(c *check.C) {
  453. // Link feature must work only on default network, and not across networks
  454. cnt1 := "container1"
  455. cnt2 := "container2"
  456. network := "anotherbridge"
  457. // Run first container on default network
  458. dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top")
  459. // Create another network and run the second container on it
  460. dockerCmd(c, "network", "create", network)
  461. assertNwIsAvailable(c, network)
  462. dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top")
  463. // Try launching a container on default network, linking to the first container. Must succeed
  464. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top")
  465. // Try launching a container on default network, linking to the second container. Must fail
  466. _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  467. c.Assert(err, checker.NotNil)
  468. // Connect second container to default network. Now a container on default network can link to it
  469. dockerCmd(c, "network", "connect", "bridge", cnt2)
  470. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  471. }