docker_cli_network_unix_test.go 31 KB

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