docker_cli_network_unix_test.go 34 KB

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