docker_cli_network_unix_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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. netFields := strings.Fields(lines[i])
  202. if netFields[1] == name {
  203. return true
  204. }
  205. }
  206. return false
  207. }
  208. func getNwResource(c *check.C, name string) *types.NetworkResource {
  209. out, _ := dockerCmd(c, "network", "inspect", name)
  210. nr := []types.NetworkResource{}
  211. err := json.Unmarshal([]byte(out), &nr)
  212. c.Assert(err, check.IsNil)
  213. return &nr[0]
  214. }
  215. func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) {
  216. defaults := []string{"bridge", "host", "none"}
  217. for _, nn := range defaults {
  218. assertNwIsAvailable(c, nn)
  219. }
  220. }
  221. func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *check.C) {
  222. dockerCmd(c, "network", "create", "test")
  223. assertNwIsAvailable(c, "test")
  224. dockerCmd(c, "network", "rm", "test")
  225. assertNwNotAvailable(c, "test")
  226. }
  227. func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *check.C) {
  228. out, _, err := dockerCmdWithError("network", "rm", "test")
  229. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  230. }
  231. func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) {
  232. out, _ := dockerCmd(c, "network", "inspect", "host", "none")
  233. networkResources := []types.NetworkResource{}
  234. err := json.Unmarshal([]byte(out), &networkResources)
  235. c.Assert(err, check.IsNil)
  236. c.Assert(networkResources, checker.HasLen, 2)
  237. // Should print an error, return an exitCode 1 *but* should print the host network
  238. out, exitCode, err := dockerCmdWithError("network", "inspect", "host", "nonexistent")
  239. c.Assert(err, checker.NotNil)
  240. c.Assert(exitCode, checker.Equals, 1)
  241. c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
  242. networkResources = []types.NetworkResource{}
  243. inspectOut := strings.SplitN(out, "\n", 2)[1]
  244. err = json.Unmarshal([]byte(inspectOut), &networkResources)
  245. c.Assert(networkResources, checker.HasLen, 1)
  246. // Should print an error and return an exitCode, nothing else
  247. out, exitCode, err = dockerCmdWithError("network", "inspect", "nonexistent")
  248. c.Assert(err, checker.NotNil)
  249. c.Assert(exitCode, checker.Equals, 1)
  250. c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
  251. }
  252. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) {
  253. dockerCmd(c, "network", "create", "test")
  254. assertNwIsAvailable(c, "test")
  255. nr := getNwResource(c, "test")
  256. c.Assert(nr.Name, checker.Equals, "test")
  257. c.Assert(len(nr.Containers), checker.Equals, 0)
  258. // run a container
  259. out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  260. c.Assert(waitRun("test"), check.IsNil)
  261. containerID := strings.TrimSpace(out)
  262. // connect the container to the test network
  263. dockerCmd(c, "network", "connect", "test", containerID)
  264. // inspect the network to make sure container is connected
  265. nr = getNetworkResource(c, nr.ID)
  266. c.Assert(len(nr.Containers), checker.Equals, 1)
  267. c.Assert(nr.Containers[containerID], check.NotNil)
  268. // check if container IP matches network inspect
  269. ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address)
  270. c.Assert(err, check.IsNil)
  271. containerIP := findContainerIP(c, "test", "test")
  272. c.Assert(ip.String(), checker.Equals, containerIP)
  273. // disconnect container from the network
  274. dockerCmd(c, "network", "disconnect", "test", containerID)
  275. nr = getNwResource(c, "test")
  276. c.Assert(nr.Name, checker.Equals, "test")
  277. c.Assert(len(nr.Containers), checker.Equals, 0)
  278. // check if network connect fails for inactive containers
  279. dockerCmd(c, "stop", containerID)
  280. _, _, err = dockerCmdWithError("network", "connect", "test", containerID)
  281. c.Assert(err, check.NotNil)
  282. dockerCmd(c, "network", "rm", "test")
  283. assertNwNotAvailable(c, "test")
  284. }
  285. func (s *DockerNetworkSuite) TestDockerNetworkIpamMultipleNetworks(c *check.C) {
  286. // test0 bridge network
  287. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
  288. assertNwIsAvailable(c, "test1")
  289. // test2 bridge network does not overlap
  290. dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
  291. assertNwIsAvailable(c, "test2")
  292. // for networks w/o ipam specified, docker will choose proper non-overlapping subnets
  293. dockerCmd(c, "network", "create", "test3")
  294. assertNwIsAvailable(c, "test3")
  295. dockerCmd(c, "network", "create", "test4")
  296. assertNwIsAvailable(c, "test4")
  297. dockerCmd(c, "network", "create", "test5")
  298. assertNwIsAvailable(c, "test5")
  299. // test network with multiple subnets
  300. // bridge network doesnt support multiple subnets. hence, use a dummy driver that supports
  301. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6")
  302. assertNwIsAvailable(c, "test6")
  303. // test network with multiple subnets with valid ipam combinations
  304. // also check same subnet across networks when the driver supports it.
  305. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
  306. "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16",
  307. "--gateway=192.168.0.100", "--gateway=192.170.0.100",
  308. "--ip-range=192.168.1.0/24",
  309. "--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6",
  310. "--aux-address", "a=192.170.1.5", "--aux-address", "b=192.170.1.6",
  311. "test7")
  312. assertNwIsAvailable(c, "test7")
  313. // cleanup
  314. for i := 1; i < 8; i++ {
  315. dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
  316. }
  317. }
  318. func (s *DockerNetworkSuite) TestDockerNetworkCustomIpam(c *check.C) {
  319. // Create a bridge network using custom ipam driver
  320. dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "br0")
  321. assertNwIsAvailable(c, "br0")
  322. // Verify expected network ipam fields are there
  323. nr := getNetworkResource(c, "br0")
  324. c.Assert(nr.Driver, checker.Equals, "bridge")
  325. c.Assert(nr.IPAM.Driver, checker.Equals, dummyIpamDriver)
  326. // remove network and exercise remote ipam driver
  327. dockerCmd(c, "network", "rm", "br0")
  328. assertNwNotAvailable(c, "br0")
  329. }
  330. func (s *DockerNetworkSuite) TestDockerNetworkInspect(c *check.C) {
  331. // if unspecified, network gateway will be selected from inside preferred pool
  332. 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")
  333. assertNwIsAvailable(c, "br0")
  334. nr := getNetworkResource(c, "br0")
  335. c.Assert(nr.Driver, checker.Equals, "bridge")
  336. c.Assert(nr.Scope, checker.Equals, "local")
  337. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  338. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  339. c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16")
  340. c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24")
  341. c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254")
  342. dockerCmd(c, "network", "rm", "br0")
  343. }
  344. func (s *DockerNetworkSuite) TestDockerNetworkIpamInvalidCombinations(c *check.C) {
  345. // network with ip-range out of subnet range
  346. _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
  347. c.Assert(err, check.NotNil)
  348. // network with multiple gateways for a single subnet
  349. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
  350. c.Assert(err, check.NotNil)
  351. // Multiple overlaping subnets in the same network must fail
  352. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
  353. c.Assert(err, check.NotNil)
  354. // overlapping subnets across networks must fail
  355. // create a valid test0 network
  356. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
  357. assertNwIsAvailable(c, "test0")
  358. // create an overlapping test1 network
  359. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
  360. c.Assert(err, check.NotNil)
  361. dockerCmd(c, "network", "rm", "test0")
  362. }
  363. func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) {
  364. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
  365. assertNwIsAvailable(c, "testopt")
  366. gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
  367. c.Assert(gopts, checker.NotNil)
  368. opts, ok := gopts.(map[string]interface{})
  369. c.Assert(ok, checker.Equals, true)
  370. c.Assert(opts["opt1"], checker.Equals, "drv1")
  371. c.Assert(opts["opt2"], checker.Equals, "drv2")
  372. dockerCmd(c, "network", "rm", "testopt")
  373. }
  374. func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *check.C) {
  375. testRequires(c, ExecSupport)
  376. // On default bridge network built-in service discovery should not happen
  377. hostsFile := "/etc/hosts"
  378. bridgeName := "external-bridge"
  379. bridgeIP := "192.169.255.254/24"
  380. out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
  381. c.Assert(err, check.IsNil, check.Commentf(out))
  382. defer deleteInterface(c, bridgeName)
  383. err = s.d.StartWithBusybox("--bridge", bridgeName)
  384. c.Assert(err, check.IsNil)
  385. defer s.d.Restart()
  386. // run two containers and store first container's etc/hosts content
  387. out, err = s.d.Cmd("run", "-d", "busybox", "top")
  388. c.Assert(err, check.IsNil)
  389. cid1 := strings.TrimSpace(out)
  390. defer s.d.Cmd("stop", cid1)
  391. hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  392. c.Assert(err, checker.IsNil)
  393. out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top")
  394. c.Assert(err, check.IsNil)
  395. cid2 := strings.TrimSpace(out)
  396. // verify first container's etc/hosts file has not changed after spawning the second named container
  397. hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  398. c.Assert(err, checker.IsNil)
  399. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  400. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  401. // stop container 2 and verify first container's etc/hosts has not changed
  402. _, err = s.d.Cmd("stop", cid2)
  403. c.Assert(err, check.IsNil)
  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 change on second container creation", hostsFile))
  408. // but discovery is on when connecting to non default bridge network
  409. network := "anotherbridge"
  410. out, err = s.d.Cmd("network", "create", network)
  411. c.Assert(err, check.IsNil, check.Commentf(out))
  412. defer s.d.Cmd("network", "rm", network)
  413. out, err = s.d.Cmd("network", "connect", network, cid1)
  414. c.Assert(err, check.IsNil, check.Commentf(out))
  415. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  416. c.Assert(err, checker.IsNil)
  417. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  418. check.Commentf("Unexpected %s change on second network connection", hostsFile))
  419. cName := "container3"
  420. out, err = s.d.Cmd("run", "-d", "--net", network, "--name", cName, "busybox", "top")
  421. c.Assert(err, check.IsNil, check.Commentf(out))
  422. cid3 := strings.TrimSpace(out)
  423. defer s.d.Cmd("stop", cid3)
  424. // container1 etc/hosts file should contain an entry for the third container
  425. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  426. c.Assert(err, checker.IsNil)
  427. c.Assert(string(hostsPost), checker.Contains, cName,
  428. check.Commentf("Container 1 %s file does not contain entries for named container %q: %s", hostsFile, cName, string(hostsPost)))
  429. // on container3 disconnect, first container's etc/hosts should go back to original form
  430. out, err = s.d.Cmd("network", "disconnect", network, cid3)
  431. c.Assert(err, check.IsNil, check.Commentf(out))
  432. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  433. c.Assert(err, checker.IsNil)
  434. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  435. check.Commentf("Unexpected %s content after disconnecting from second network", hostsFile))
  436. }
  437. func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
  438. testRequires(c, ExecSupport)
  439. hostsFile := "/etc/hosts"
  440. cstmBridgeNw := "custom-bridge-nw"
  441. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw)
  442. assertNwIsAvailable(c, cstmBridgeNw)
  443. // run two anonymous containers and store their etc/hosts content
  444. out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  445. cid1 := strings.TrimSpace(out)
  446. hosts1, err := readContainerFileWithExec(cid1, hostsFile)
  447. c.Assert(err, checker.IsNil)
  448. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  449. cid2 := strings.TrimSpace(out)
  450. hosts2, err := readContainerFileWithExec(cid2, hostsFile)
  451. c.Assert(err, checker.IsNil)
  452. // verify first container etc/hosts file has not changed
  453. hosts1post, err := readContainerFileWithExec(cid1, hostsFile)
  454. c.Assert(err, checker.IsNil)
  455. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  456. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  457. // start a named container
  458. cName := "AnyName"
  459. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top")
  460. cid3 := strings.TrimSpace(out)
  461. // verify etc/hosts file for first two containers contains the named container entry
  462. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  463. c.Assert(err, checker.IsNil)
  464. c.Assert(string(hosts1post), checker.Contains, cName,
  465. check.Commentf("Container 1 %s file does not contain entries for named container %q: %s", hostsFile, cName, string(hosts1post)))
  466. hosts2post, err := readContainerFileWithExec(cid2, hostsFile)
  467. c.Assert(err, checker.IsNil)
  468. c.Assert(string(hosts2post), checker.Contains, cName,
  469. check.Commentf("Container 2 %s file does not contain entries for named container %q: %s", hostsFile, cName, string(hosts2post)))
  470. // Stop named container and verify first two containers' etc/hosts entries are back to original
  471. dockerCmd(c, "stop", cid3)
  472. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  473. c.Assert(err, checker.IsNil)
  474. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  475. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  476. hosts2post, err = readContainerFileWithExec(cid2, hostsFile)
  477. c.Assert(err, checker.IsNil)
  478. c.Assert(string(hosts2), checker.Equals, string(hosts2post),
  479. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  480. }
  481. func (s *DockerNetworkSuite) TestDockerNetworkLinkOndefaultNetworkOnly(c *check.C) {
  482. // Link feature must work only on default network, and not across networks
  483. cnt1 := "container1"
  484. cnt2 := "container2"
  485. network := "anotherbridge"
  486. // Run first container on default network
  487. dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top")
  488. // Create another network and run the second container on it
  489. dockerCmd(c, "network", "create", network)
  490. assertNwIsAvailable(c, network)
  491. dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top")
  492. // Try launching a container on default network, linking to the first container. Must succeed
  493. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top")
  494. // Try launching a container on default network, linking to the second container. Must fail
  495. _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  496. c.Assert(err, checker.NotNil)
  497. // Connect second container to default network. Now a container on default network can link to it
  498. dockerCmd(c, "network", "connect", "bridge", cnt2)
  499. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  500. }
  501. func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) {
  502. // Verify exposed ports are present in ps output when running a container on
  503. // a network managed by a driver which does not provide the default gateway
  504. // for the container
  505. nwn := "ov"
  506. ctn := "bb"
  507. port1 := 80
  508. port2 := 443
  509. expose1 := fmt.Sprintf("--expose=%d", port1)
  510. expose2 := fmt.Sprintf("--expose=%d", port2)
  511. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  512. assertNwIsAvailable(c, nwn)
  513. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top")
  514. // Check docker ps o/p for last created container reports the unpublished ports
  515. unpPort1 := fmt.Sprintf("%d/tcp", port1)
  516. unpPort2 := fmt.Sprintf("%d/tcp", port2)
  517. out, _ := dockerCmd(c, "ps", "-n=1")
  518. // Missing unpublished ports in docker ps output
  519. c.Assert(out, checker.Contains, unpPort1)
  520. // Missing unpublished ports in docker ps output
  521. c.Assert(out, checker.Contains, unpPort2)
  522. }
  523. func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) {
  524. // Verify endpoint MAC address is correctly populated in container's network settings
  525. nwn := "ov"
  526. ctn := "bb"
  527. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  528. assertNwIsAvailable(c, nwn)
  529. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top")
  530. mac, err := inspectField(ctn, "NetworkSettings.Networks."+nwn+".MacAddress")
  531. c.Assert(err, checker.IsNil)
  532. c.Assert(mac, checker.Equals, "a0:b1:c2:d3:e4:f5")
  533. }