docker_cli_network_unix_test.go 24 KB

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