docker_cli_network_unix_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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 *DockerSuite) TestDockerInspectNetworkWithContainerName(c *check.C) {
  255. dockerCmd(c, "network", "create", "brNetForInspect")
  256. assertNwIsAvailable(c, "brNetForInspect")
  257. defer func() {
  258. dockerCmd(c, "network", "rm", "brNetForInspect")
  259. assertNwNotAvailable(c, "brNetForInspect")
  260. }()
  261. out, _ := dockerCmd(c, "run", "-d", "--name", "testNetInspect1", "--net", "brNetForInspect", "busybox", "top")
  262. c.Assert(waitRun("testNetInspect1"), check.IsNil)
  263. containerID := strings.TrimSpace(out)
  264. defer func() {
  265. // we don't stop container by name, because we'll rename it later
  266. dockerCmd(c, "stop", containerID)
  267. }()
  268. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  269. networkResources := []types.NetworkResource{}
  270. err := json.Unmarshal([]byte(out), &networkResources)
  271. c.Assert(err, check.IsNil)
  272. c.Assert(networkResources, checker.HasLen, 1)
  273. container, ok := networkResources[0].Containers[containerID]
  274. c.Assert(ok, checker.True)
  275. c.Assert(container.Name, checker.Equals, "testNetInspect1")
  276. // rename container and check docker inspect output update
  277. newName := "HappyNewName"
  278. dockerCmd(c, "rename", "testNetInspect1", newName)
  279. // check whether network inspect works properly
  280. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  281. newNetRes := []types.NetworkResource{}
  282. err = json.Unmarshal([]byte(out), &newNetRes)
  283. c.Assert(err, check.IsNil)
  284. c.Assert(newNetRes, checker.HasLen, 1)
  285. container1, ok := newNetRes[0].Containers[containerID]
  286. c.Assert(ok, checker.True)
  287. c.Assert(container1.Name, checker.Equals, newName)
  288. }
  289. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) {
  290. dockerCmd(c, "network", "create", "test")
  291. assertNwIsAvailable(c, "test")
  292. nr := getNwResource(c, "test")
  293. c.Assert(nr.Name, checker.Equals, "test")
  294. c.Assert(len(nr.Containers), checker.Equals, 0)
  295. // run a container
  296. out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  297. c.Assert(waitRun("test"), check.IsNil)
  298. containerID := strings.TrimSpace(out)
  299. // connect the container to the test network
  300. dockerCmd(c, "network", "connect", "test", containerID)
  301. // inspect the network to make sure container is connected
  302. nr = getNetworkResource(c, nr.ID)
  303. c.Assert(len(nr.Containers), checker.Equals, 1)
  304. c.Assert(nr.Containers[containerID], check.NotNil)
  305. // check if container IP matches network inspect
  306. ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address)
  307. c.Assert(err, check.IsNil)
  308. containerIP := findContainerIP(c, "test", "test")
  309. c.Assert(ip.String(), checker.Equals, containerIP)
  310. // disconnect container from the network
  311. dockerCmd(c, "network", "disconnect", "test", containerID)
  312. nr = getNwResource(c, "test")
  313. c.Assert(nr.Name, checker.Equals, "test")
  314. c.Assert(len(nr.Containers), checker.Equals, 0)
  315. // check if network connect fails for inactive containers
  316. dockerCmd(c, "stop", containerID)
  317. _, _, err = dockerCmdWithError("network", "connect", "test", containerID)
  318. c.Assert(err, check.NotNil)
  319. dockerCmd(c, "network", "rm", "test")
  320. assertNwNotAvailable(c, "test")
  321. }
  322. func (s *DockerNetworkSuite) TestDockerNetworkIpamMultipleNetworks(c *check.C) {
  323. // test0 bridge network
  324. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
  325. assertNwIsAvailable(c, "test1")
  326. // test2 bridge network does not overlap
  327. dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
  328. assertNwIsAvailable(c, "test2")
  329. // for networks w/o ipam specified, docker will choose proper non-overlapping subnets
  330. dockerCmd(c, "network", "create", "test3")
  331. assertNwIsAvailable(c, "test3")
  332. dockerCmd(c, "network", "create", "test4")
  333. assertNwIsAvailable(c, "test4")
  334. dockerCmd(c, "network", "create", "test5")
  335. assertNwIsAvailable(c, "test5")
  336. // test network with multiple subnets
  337. // bridge network doesnt support multiple subnets. hence, use a dummy driver that supports
  338. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6")
  339. assertNwIsAvailable(c, "test6")
  340. // test network with multiple subnets with valid ipam combinations
  341. // also check same subnet across networks when the driver supports it.
  342. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
  343. "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16",
  344. "--gateway=192.168.0.100", "--gateway=192.170.0.100",
  345. "--ip-range=192.168.1.0/24",
  346. "--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6",
  347. "--aux-address", "a=192.170.1.5", "--aux-address", "b=192.170.1.6",
  348. "test7")
  349. assertNwIsAvailable(c, "test7")
  350. // cleanup
  351. for i := 1; i < 8; i++ {
  352. dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
  353. }
  354. }
  355. func (s *DockerNetworkSuite) TestDockerNetworkCustomIpam(c *check.C) {
  356. // Create a bridge network using custom ipam driver
  357. dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "br0")
  358. assertNwIsAvailable(c, "br0")
  359. // Verify expected network ipam fields are there
  360. nr := getNetworkResource(c, "br0")
  361. c.Assert(nr.Driver, checker.Equals, "bridge")
  362. c.Assert(nr.IPAM.Driver, checker.Equals, dummyIpamDriver)
  363. // remove network and exercise remote ipam driver
  364. dockerCmd(c, "network", "rm", "br0")
  365. assertNwNotAvailable(c, "br0")
  366. }
  367. func (s *DockerNetworkSuite) TestDockerNetworkInspect(c *check.C) {
  368. // if unspecified, network gateway will be selected from inside preferred pool
  369. 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")
  370. assertNwIsAvailable(c, "br0")
  371. nr := getNetworkResource(c, "br0")
  372. c.Assert(nr.Driver, checker.Equals, "bridge")
  373. c.Assert(nr.Scope, checker.Equals, "local")
  374. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  375. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  376. c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16")
  377. c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24")
  378. c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254")
  379. dockerCmd(c, "network", "rm", "br0")
  380. }
  381. func (s *DockerNetworkSuite) TestDockerNetworkIpamInvalidCombinations(c *check.C) {
  382. // network with ip-range out of subnet range
  383. _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
  384. c.Assert(err, check.NotNil)
  385. // network with multiple gateways for a single subnet
  386. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
  387. c.Assert(err, check.NotNil)
  388. // Multiple overlaping subnets in the same network must fail
  389. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
  390. c.Assert(err, check.NotNil)
  391. // overlapping subnets across networks must fail
  392. // create a valid test0 network
  393. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
  394. assertNwIsAvailable(c, "test0")
  395. // create an overlapping test1 network
  396. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
  397. c.Assert(err, check.NotNil)
  398. dockerCmd(c, "network", "rm", "test0")
  399. }
  400. func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) {
  401. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
  402. assertNwIsAvailable(c, "testopt")
  403. gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
  404. c.Assert(gopts, checker.NotNil)
  405. opts, ok := gopts.(map[string]interface{})
  406. c.Assert(ok, checker.Equals, true)
  407. c.Assert(opts["opt1"], checker.Equals, "drv1")
  408. c.Assert(opts["opt2"], checker.Equals, "drv2")
  409. dockerCmd(c, "network", "rm", "testopt")
  410. }
  411. func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *check.C) {
  412. testRequires(c, ExecSupport)
  413. // On default bridge network built-in service discovery should not happen
  414. hostsFile := "/etc/hosts"
  415. bridgeName := "external-bridge"
  416. bridgeIP := "192.169.255.254/24"
  417. out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
  418. c.Assert(err, check.IsNil, check.Commentf(out))
  419. defer deleteInterface(c, bridgeName)
  420. err = s.d.StartWithBusybox("--bridge", bridgeName)
  421. c.Assert(err, check.IsNil)
  422. defer s.d.Restart()
  423. // run two containers and store first container's etc/hosts content
  424. out, err = s.d.Cmd("run", "-d", "busybox", "top")
  425. c.Assert(err, check.IsNil)
  426. cid1 := strings.TrimSpace(out)
  427. defer s.d.Cmd("stop", cid1)
  428. hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  429. c.Assert(err, checker.IsNil)
  430. out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top")
  431. c.Assert(err, check.IsNil)
  432. cid2 := strings.TrimSpace(out)
  433. // verify first container's etc/hosts file has not changed after spawning the second named container
  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 change on second container creation", hostsFile))
  438. // stop container 2 and verify first container's etc/hosts has not changed
  439. _, err = s.d.Cmd("stop", cid2)
  440. c.Assert(err, check.IsNil)
  441. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  442. c.Assert(err, checker.IsNil)
  443. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  444. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  445. // but discovery is on when connecting to non default bridge network
  446. network := "anotherbridge"
  447. out, err = s.d.Cmd("network", "create", network)
  448. c.Assert(err, check.IsNil, check.Commentf(out))
  449. defer s.d.Cmd("network", "rm", network)
  450. out, err = s.d.Cmd("network", "connect", network, cid1)
  451. c.Assert(err, check.IsNil, check.Commentf(out))
  452. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  453. c.Assert(err, checker.IsNil)
  454. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  455. check.Commentf("Unexpected %s change on second network connection", hostsFile))
  456. cName := "container3"
  457. out, err = s.d.Cmd("run", "-d", "--net", network, "--name", cName, "busybox", "top")
  458. c.Assert(err, check.IsNil, check.Commentf(out))
  459. cid3 := strings.TrimSpace(out)
  460. defer s.d.Cmd("stop", cid3)
  461. // container1 etc/hosts file should contain an entry for the third container
  462. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  463. c.Assert(err, checker.IsNil)
  464. c.Assert(string(hostsPost), checker.Contains, cName,
  465. check.Commentf("Container 1 %s file does not contain entries for named container %q: %s", hostsFile, cName, string(hostsPost)))
  466. // on container3 disconnect, first container's etc/hosts should go back to original form
  467. out, err = s.d.Cmd("network", "disconnect", network, cid3)
  468. c.Assert(err, check.IsNil, check.Commentf(out))
  469. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  470. c.Assert(err, checker.IsNil)
  471. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  472. check.Commentf("Unexpected %s content after disconnecting from second network", hostsFile))
  473. }
  474. func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
  475. testRequires(c, ExecSupport)
  476. hostsFile := "/etc/hosts"
  477. cstmBridgeNw := "custom-bridge-nw"
  478. cstmBridgeNw1 := "custom-bridge-nw1"
  479. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw)
  480. assertNwIsAvailable(c, cstmBridgeNw)
  481. // run two anonymous containers and store their etc/hosts content
  482. out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  483. cid1 := strings.TrimSpace(out)
  484. hosts1, err := readContainerFileWithExec(cid1, hostsFile)
  485. c.Assert(err, checker.IsNil)
  486. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  487. cid2 := strings.TrimSpace(out)
  488. hosts2, err := readContainerFileWithExec(cid2, hostsFile)
  489. c.Assert(err, checker.IsNil)
  490. // verify first container etc/hosts file has not changed
  491. hosts1post, err := readContainerFileWithExec(cid1, hostsFile)
  492. c.Assert(err, checker.IsNil)
  493. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  494. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  495. // Connect the 2nd container to a new network and verify the
  496. // first container /etc/hosts file still hasn't changed.
  497. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1)
  498. assertNwIsAvailable(c, cstmBridgeNw1)
  499. dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2)
  500. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  501. c.Assert(err, checker.IsNil)
  502. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  503. check.Commentf("Unexpected %s change on container connect", hostsFile))
  504. // start a named container
  505. cName := "AnyName"
  506. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top")
  507. cid3 := strings.TrimSpace(out)
  508. // verify etc/hosts file for first two containers contains the named container entry
  509. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  510. c.Assert(err, checker.IsNil)
  511. c.Assert(string(hosts1post), checker.Contains, cName,
  512. check.Commentf("Container 1 %s file does not contain entries for named container %q: %s", hostsFile, cName, string(hosts1post)))
  513. hosts2post, err := readContainerFileWithExec(cid2, hostsFile)
  514. c.Assert(err, checker.IsNil)
  515. c.Assert(string(hosts2post), checker.Contains, cName,
  516. check.Commentf("Container 2 %s file does not contain entries for named container %q: %s", hostsFile, cName, string(hosts2post)))
  517. // Stop named container and verify first two containers' etc/hosts entries are back to original
  518. dockerCmd(c, "stop", cid3)
  519. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  520. c.Assert(err, checker.IsNil)
  521. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  522. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  523. hosts2post, err = readContainerFileWithExec(cid2, hostsFile)
  524. c.Assert(err, checker.IsNil)
  525. c.Assert(string(hosts2), checker.Equals, string(hosts2post),
  526. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  527. }
  528. func (s *DockerNetworkSuite) TestDockerNetworkLinkOndefaultNetworkOnly(c *check.C) {
  529. // Link feature must work only on default network, and not across networks
  530. cnt1 := "container1"
  531. cnt2 := "container2"
  532. network := "anotherbridge"
  533. // Run first container on default network
  534. dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top")
  535. // Create another network and run the second container on it
  536. dockerCmd(c, "network", "create", network)
  537. assertNwIsAvailable(c, network)
  538. dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top")
  539. // Try launching a container on default network, linking to the first container. Must succeed
  540. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top")
  541. // Try launching a container on default network, linking to the second container. Must fail
  542. _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  543. c.Assert(err, checker.NotNil)
  544. // Connect second container to default network. Now a container on default network can link to it
  545. dockerCmd(c, "network", "connect", "bridge", cnt2)
  546. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  547. }
  548. func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) {
  549. // Verify exposed ports are present in ps output when running a container on
  550. // a network managed by a driver which does not provide the default gateway
  551. // for the container
  552. nwn := "ov"
  553. ctn := "bb"
  554. port1 := 80
  555. port2 := 443
  556. expose1 := fmt.Sprintf("--expose=%d", port1)
  557. expose2 := fmt.Sprintf("--expose=%d", port2)
  558. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  559. assertNwIsAvailable(c, nwn)
  560. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top")
  561. // Check docker ps o/p for last created container reports the unpublished ports
  562. unpPort1 := fmt.Sprintf("%d/tcp", port1)
  563. unpPort2 := fmt.Sprintf("%d/tcp", port2)
  564. out, _ := dockerCmd(c, "ps", "-n=1")
  565. // Missing unpublished ports in docker ps output
  566. c.Assert(out, checker.Contains, unpPort1)
  567. // Missing unpublished ports in docker ps output
  568. c.Assert(out, checker.Contains, unpPort2)
  569. }
  570. func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) {
  571. // Verify endpoint MAC address is correctly populated in container's network settings
  572. nwn := "ov"
  573. ctn := "bb"
  574. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  575. assertNwIsAvailable(c, nwn)
  576. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top")
  577. mac, err := inspectField(ctn, "NetworkSettings.Networks."+nwn+".MacAddress")
  578. c.Assert(err, checker.IsNil)
  579. c.Assert(mac, checker.Equals, "a0:b1:c2:d3:e4:f5")
  580. }
  581. func (s *DockerSuite) TestInspectApiMultipleNetworks(c *check.C) {
  582. dockerCmd(c, "network", "create", "mybridge1")
  583. dockerCmd(c, "network", "create", "mybridge2")
  584. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  585. id := strings.TrimSpace(out)
  586. c.Assert(waitRun(id), check.IsNil)
  587. dockerCmd(c, "network", "connect", "mybridge1", id)
  588. dockerCmd(c, "network", "connect", "mybridge2", id)
  589. body := getInspectBody(c, "v1.20", id)
  590. var inspect120 v1p20.ContainerJSON
  591. err := json.Unmarshal(body, &inspect120)
  592. c.Assert(err, checker.IsNil)
  593. versionedIP := inspect120.NetworkSettings.IPAddress
  594. body = getInspectBody(c, "v1.21", id)
  595. var inspect121 types.ContainerJSON
  596. err = json.Unmarshal(body, &inspect121)
  597. c.Assert(err, checker.IsNil)
  598. c.Assert(inspect121.NetworkSettings.Networks, checker.HasLen, 3)
  599. bridge := inspect121.NetworkSettings.Networks["bridge"]
  600. c.Assert(bridge.IPAddress, checker.Equals, versionedIP)
  601. c.Assert(bridge.IPAddress, checker.Equals, inspect121.NetworkSettings.IPAddress)
  602. }
  603. func connectContainerToNetworks(c *check.C, d *Daemon, cName string, nws []string) {
  604. // Run a container on the default network
  605. out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
  606. c.Assert(err, checker.IsNil, check.Commentf(out))
  607. // Attach the container to other three networks
  608. for _, nw := range nws {
  609. out, err = d.Cmd("network", "create", nw)
  610. c.Assert(err, checker.IsNil, check.Commentf(out))
  611. out, err = d.Cmd("network", "connect", nw, cName)
  612. c.Assert(err, checker.IsNil, check.Commentf(out))
  613. }
  614. }
  615. func verifyContainerIsConnectedToNetworks(c *check.C, d *Daemon, cName string, nws []string) {
  616. // Verify container is connected to all three networks
  617. for _, nw := range nws {
  618. out, err := d.Cmd("inspect", "-f", fmt.Sprintf("{{.NetworkSettings.Networks.%s}}", nw), cName)
  619. c.Assert(err, checker.IsNil, check.Commentf(out))
  620. c.Assert(out, checker.Not(checker.Equals), "<no value>\n")
  621. }
  622. }
  623. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRestart(c *check.C) {
  624. cName := "bb"
  625. nwList := []string{"nw1", "nw2", "nw3"}
  626. s.d.StartWithBusybox()
  627. connectContainerToNetworks(c, s.d, cName, nwList)
  628. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  629. // Reload daemon
  630. s.d.Restart()
  631. _, err := s.d.Cmd("start", cName)
  632. c.Assert(err, checker.IsNil)
  633. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  634. }
  635. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksUngracefulDaemonRestart(c *check.C) {
  636. cName := "cc"
  637. nwList := []string{"nw1", "nw2", "nw3"}
  638. s.d.StartWithBusybox()
  639. connectContainerToNetworks(c, s.d, cName, nwList)
  640. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  641. // Kill daemon and restart
  642. if err := s.d.cmd.Process.Kill(); err != nil {
  643. c.Fatal(err)
  644. }
  645. s.d.Restart()
  646. // Restart container
  647. _, err := s.d.Cmd("start", cName)
  648. c.Assert(err, checker.IsNil)
  649. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  650. }
  651. func (s *DockerNetworkSuite) TestDockerNetworkRunNetByID(c *check.C) {
  652. out, _ := dockerCmd(c, "network", "create", "one")
  653. dockerCmd(c, "run", "-d", "--net", strings.TrimSpace(out), "busybox", "top")
  654. }
  655. func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c *check.C) {
  656. testRequires(c, DaemonIsLinux, NotUserNamespace)
  657. s.d.StartWithBusybox()
  658. // Run a few containers on host network
  659. for i := 0; i < 10; i++ {
  660. cName := fmt.Sprintf("hostc-%d", i)
  661. out, err := s.d.Cmd("run", "-d", "--name", cName, "--net=host", "--restart=always", "busybox", "top")
  662. c.Assert(err, checker.IsNil, check.Commentf(out))
  663. }
  664. // Kill daemon ungracefully and restart
  665. if err := s.d.cmd.Process.Kill(); err != nil {
  666. c.Fatal(err)
  667. }
  668. s.d.Restart()
  669. // make sure all the containers are up and running
  670. for i := 0; i < 10; i++ {
  671. cName := fmt.Sprintf("hostc-%d", i)
  672. runningOut, err := s.d.Cmd("inspect", "--format='{{.State.Running}}'", cName)
  673. c.Assert(err, checker.IsNil)
  674. c.Assert(strings.TrimSpace(runningOut), checker.Equals, "true")
  675. }
  676. }
  677. func (s *DockerNetworkSuite) TestDockerNetworkConnectToHostFromOtherNetwork(c *check.C) {
  678. dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
  679. c.Assert(waitRun("container1"), check.IsNil)
  680. dockerCmd(c, "network", "disconnect", "bridge", "container1")
  681. out, _, err := dockerCmdWithError("network", "connect", "host", "container1")
  682. c.Assert(err, checker.NotNil, check.Commentf(out))
  683. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  684. }
  685. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromHost(c *check.C) {
  686. dockerCmd(c, "run", "-d", "--name", "container1", "--net=host", "busybox", "top")
  687. c.Assert(waitRun("container1"), check.IsNil)
  688. out, _, err := dockerCmdWithError("network", "disconnect", "host", "container1")
  689. c.Assert(err, checker.NotNil, check.Commentf("Should err out disconnect from host"))
  690. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  691. }
  692. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithPortMapping(c *check.C) {
  693. dockerCmd(c, "network", "create", "test1")
  694. dockerCmd(c, "run", "-d", "--name", "c1", "-p", "5000:5000", "busybox", "top")
  695. c.Assert(waitRun("c1"), check.IsNil)
  696. dockerCmd(c, "network", "connect", "test1", "c1")
  697. }
  698. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithMac(c *check.C) {
  699. macAddress := "02:42:ac:11:00:02"
  700. dockerCmd(c, "network", "create", "mynetwork")
  701. dockerCmd(c, "run", "--name=test", "-d", "--mac-address", macAddress, "busybox", "top")
  702. c.Assert(waitRun("test"), check.IsNil)
  703. mac1, err := inspectField("test", "NetworkSettings.Networks.bridge.MacAddress")
  704. c.Assert(err, checker.IsNil)
  705. c.Assert(strings.TrimSpace(mac1), checker.Equals, macAddress)
  706. dockerCmd(c, "network", "connect", "mynetwork", "test")
  707. mac2, err := inspectField("test", "NetworkSettings.Networks.mynetwork.MacAddress")
  708. c.Assert(err, checker.IsNil)
  709. c.Assert(strings.TrimSpace(mac2), checker.Not(checker.Equals), strings.TrimSpace(mac1))
  710. }