docker_cli_network_unix_test.go 40 KB

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