docker_cli_network_unix_test.go 27 KB

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