docker_cli_network_unix_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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/pkg/integration/checker"
  14. "github.com/docker/libnetwork/driverapi"
  15. remoteapi "github.com/docker/libnetwork/drivers/remote/api"
  16. "github.com/docker/libnetwork/ipamapi"
  17. remoteipam "github.com/docker/libnetwork/ipams/remote/api"
  18. "github.com/docker/libnetwork/netlabel"
  19. "github.com/go-check/check"
  20. )
  21. const dummyNetworkDriver = "dummy-network-driver"
  22. const dummyIpamDriver = "dummy-ipam-driver"
  23. var remoteDriverNetworkRequest remoteapi.CreateNetworkRequest
  24. func init() {
  25. check.Suite(&DockerNetworkSuite{
  26. ds: &DockerSuite{},
  27. })
  28. }
  29. type DockerNetworkSuite struct {
  30. server *httptest.Server
  31. ds *DockerSuite
  32. d *Daemon
  33. }
  34. func (s *DockerNetworkSuite) SetUpTest(c *check.C) {
  35. s.d = NewDaemon(c)
  36. }
  37. func (s *DockerNetworkSuite) TearDownTest(c *check.C) {
  38. s.d.Stop()
  39. s.ds.TearDownTest(c)
  40. }
  41. func (s *DockerNetworkSuite) SetUpSuite(c *check.C) {
  42. mux := http.NewServeMux()
  43. s.server = httptest.NewServer(mux)
  44. c.Assert(s.server, check.NotNil, check.Commentf("Failed to start a HTTP Server"))
  45. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  46. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  47. fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType)
  48. })
  49. // Network driver implementation
  50. mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  51. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  52. fmt.Fprintf(w, `{"Scope":"local"}`)
  53. })
  54. mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  55. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  56. if err != nil {
  57. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  58. return
  59. }
  60. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  61. fmt.Fprintf(w, "null")
  62. })
  63. mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  64. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  65. fmt.Fprintf(w, "null")
  66. })
  67. // Ipam Driver implementation
  68. var (
  69. poolRequest remoteipam.RequestPoolRequest
  70. poolReleaseReq remoteipam.ReleasePoolRequest
  71. addressRequest remoteipam.RequestAddressRequest
  72. addressReleaseReq remoteipam.ReleaseAddressRequest
  73. lAS = "localAS"
  74. gAS = "globalAS"
  75. pool = "172.28.0.0/16"
  76. poolID = lAS + "/" + pool
  77. gw = "172.28.255.254/16"
  78. )
  79. mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  80. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  81. fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`)
  82. })
  83. mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  84. err := json.NewDecoder(r.Body).Decode(&poolRequest)
  85. if err != nil {
  86. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  87. return
  88. }
  89. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  90. if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS {
  91. fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`)
  92. } else if poolRequest.Pool != "" && poolRequest.Pool != pool {
  93. fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`)
  94. } else {
  95. fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`)
  96. }
  97. })
  98. mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  99. err := json.NewDecoder(r.Body).Decode(&addressRequest)
  100. if err != nil {
  101. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  102. return
  103. }
  104. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  105. // make sure libnetwork is now querying on the expected pool id
  106. if addressRequest.PoolID != poolID {
  107. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  108. } else if addressRequest.Address != "" {
  109. fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`)
  110. } else {
  111. fmt.Fprintf(w, `{"Address":"`+gw+`"}`)
  112. }
  113. })
  114. mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  115. err := json.NewDecoder(r.Body).Decode(&addressReleaseReq)
  116. if err != nil {
  117. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  118. return
  119. }
  120. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  121. // make sure libnetwork is now asking to release the expected address fro mthe expected poolid
  122. if addressRequest.PoolID != poolID {
  123. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  124. } else if addressReleaseReq.Address != gw {
  125. fmt.Fprintf(w, `{"Error":"unknown address"}`)
  126. } else {
  127. fmt.Fprintf(w, "null")
  128. }
  129. })
  130. mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  131. err := json.NewDecoder(r.Body).Decode(&poolReleaseReq)
  132. if err != nil {
  133. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  134. return
  135. }
  136. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  137. // make sure libnetwork is now asking to release the expected poolid
  138. if addressRequest.PoolID != poolID {
  139. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  140. } else {
  141. fmt.Fprintf(w, "null")
  142. }
  143. })
  144. err := os.MkdirAll("/etc/docker/plugins", 0755)
  145. c.Assert(err, checker.IsNil)
  146. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", dummyNetworkDriver)
  147. err = ioutil.WriteFile(fileName, []byte(s.server.URL), 0644)
  148. c.Assert(err, checker.IsNil)
  149. ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", dummyIpamDriver)
  150. err = ioutil.WriteFile(ipamFileName, []byte(s.server.URL), 0644)
  151. c.Assert(err, checker.IsNil)
  152. }
  153. func (s *DockerNetworkSuite) TearDownSuite(c *check.C) {
  154. if s.server == nil {
  155. return
  156. }
  157. s.server.Close()
  158. err := os.RemoveAll("/etc/docker/plugins")
  159. c.Assert(err, checker.IsNil)
  160. }
  161. func assertNwIsAvailable(c *check.C, name string) {
  162. if !isNwPresent(c, name) {
  163. c.Fatalf("Network %s not found in network ls o/p", name)
  164. }
  165. }
  166. func assertNwNotAvailable(c *check.C, name string) {
  167. if isNwPresent(c, name) {
  168. c.Fatalf("Found network %s in network ls o/p", name)
  169. }
  170. }
  171. func isNwPresent(c *check.C, name string) bool {
  172. out, _ := dockerCmd(c, "network", "ls")
  173. lines := strings.Split(out, "\n")
  174. for i := 1; i < len(lines)-1; i++ {
  175. if strings.Contains(lines[i], name) {
  176. return true
  177. }
  178. }
  179. return false
  180. }
  181. func getNwResource(c *check.C, name string) *types.NetworkResource {
  182. out, _ := dockerCmd(c, "network", "inspect", name)
  183. nr := []types.NetworkResource{}
  184. err := json.Unmarshal([]byte(out), &nr)
  185. c.Assert(err, check.IsNil)
  186. return &nr[0]
  187. }
  188. func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) {
  189. defaults := []string{"bridge", "host", "none"}
  190. for _, nn := range defaults {
  191. assertNwIsAvailable(c, nn)
  192. }
  193. }
  194. func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *check.C) {
  195. dockerCmd(c, "network", "create", "test")
  196. assertNwIsAvailable(c, "test")
  197. dockerCmd(c, "network", "rm", "test")
  198. assertNwNotAvailable(c, "test")
  199. }
  200. func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *check.C) {
  201. out, _, err := dockerCmdWithError("network", "rm", "test")
  202. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  203. }
  204. func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) {
  205. out, _ := dockerCmd(c, "network", "inspect", "host", "none")
  206. networkResources := []types.NetworkResource{}
  207. err := json.Unmarshal([]byte(out), &networkResources)
  208. c.Assert(err, check.IsNil)
  209. c.Assert(networkResources, checker.HasLen, 2)
  210. // Should print an error, return an exitCode 1 *but* should print the host network
  211. out, exitCode, err := dockerCmdWithError("network", "inspect", "host", "nonexistent")
  212. c.Assert(err, checker.NotNil)
  213. c.Assert(exitCode, checker.Equals, 1)
  214. c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
  215. networkResources = []types.NetworkResource{}
  216. inspectOut := strings.SplitN(out, "\n", 2)[1]
  217. err = json.Unmarshal([]byte(inspectOut), &networkResources)
  218. c.Assert(networkResources, checker.HasLen, 1)
  219. // Should print an error and return an exitCode, nothing else
  220. out, exitCode, err = dockerCmdWithError("network", "inspect", "nonexistent")
  221. c.Assert(err, checker.NotNil)
  222. c.Assert(exitCode, checker.Equals, 1)
  223. c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
  224. }
  225. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) {
  226. dockerCmd(c, "network", "create", "test")
  227. assertNwIsAvailable(c, "test")
  228. nr := getNwResource(c, "test")
  229. c.Assert(nr.Name, checker.Equals, "test")
  230. c.Assert(len(nr.Containers), checker.Equals, 0)
  231. // run a container
  232. out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  233. c.Assert(waitRun("test"), check.IsNil)
  234. containerID := strings.TrimSpace(out)
  235. // connect the container to the test network
  236. dockerCmd(c, "network", "connect", "test", containerID)
  237. // inspect the network to make sure container is connected
  238. nr = getNetworkResource(c, nr.ID)
  239. c.Assert(len(nr.Containers), checker.Equals, 1)
  240. c.Assert(nr.Containers[containerID], check.NotNil)
  241. // check if container IP matches network inspect
  242. ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address)
  243. c.Assert(err, check.IsNil)
  244. containerIP := findContainerIP(c, "test")
  245. c.Assert(ip.String(), checker.Equals, containerIP)
  246. // disconnect container from the network
  247. dockerCmd(c, "network", "disconnect", "test", containerID)
  248. nr = getNwResource(c, "test")
  249. c.Assert(nr.Name, checker.Equals, "test")
  250. c.Assert(len(nr.Containers), checker.Equals, 0)
  251. // check if network connect fails for inactive containers
  252. dockerCmd(c, "stop", containerID)
  253. _, _, err = dockerCmdWithError("network", "connect", "test", containerID)
  254. c.Assert(err, check.NotNil)
  255. dockerCmd(c, "network", "rm", "test")
  256. assertNwNotAvailable(c, "test")
  257. }
  258. func (s *DockerNetworkSuite) TestDockerNetworkIpamMultipleNetworks(c *check.C) {
  259. // test0 bridge network
  260. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
  261. assertNwIsAvailable(c, "test1")
  262. // test2 bridge network does not overlap
  263. dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
  264. assertNwIsAvailable(c, "test2")
  265. // for networks w/o ipam specified, docker will choose proper non-overlapping subnets
  266. dockerCmd(c, "network", "create", "test3")
  267. assertNwIsAvailable(c, "test3")
  268. dockerCmd(c, "network", "create", "test4")
  269. assertNwIsAvailable(c, "test4")
  270. dockerCmd(c, "network", "create", "test5")
  271. assertNwIsAvailable(c, "test5")
  272. // test network with multiple subnets
  273. // bridge network doesnt support multiple subnets. hence, use a dummy driver that supports
  274. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6")
  275. assertNwIsAvailable(c, "test6")
  276. // test network with multiple subnets with valid ipam combinations
  277. // also check same subnet across networks when the driver supports it.
  278. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
  279. "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16",
  280. "--gateway=192.168.0.100", "--gateway=192.170.0.100",
  281. "--ip-range=192.168.1.0/24",
  282. "--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6",
  283. "--aux-address", "a=192.170.1.5", "--aux-address", "b=192.170.1.6",
  284. "test7")
  285. assertNwIsAvailable(c, "test7")
  286. // cleanup
  287. for i := 1; i < 8; i++ {
  288. dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
  289. }
  290. }
  291. func (s *DockerNetworkSuite) TestDockerNetworkCustomIpam(c *check.C) {
  292. // Create a bridge network using custom ipam driver
  293. dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "br0")
  294. assertNwIsAvailable(c, "br0")
  295. // Verify expected network ipam fields are there
  296. nr := getNetworkResource(c, "br0")
  297. c.Assert(nr.Driver, checker.Equals, "bridge")
  298. c.Assert(nr.IPAM.Driver, checker.Equals, dummyIpamDriver)
  299. // remove network and exercise remote ipam driver
  300. dockerCmd(c, "network", "rm", "br0")
  301. assertNwNotAvailable(c, "br0")
  302. }
  303. func (s *DockerNetworkSuite) TestDockerNetworkInspect(c *check.C) {
  304. // if unspecified, network gateway will be selected from inside preferred pool
  305. 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")
  306. assertNwIsAvailable(c, "br0")
  307. nr := getNetworkResource(c, "br0")
  308. c.Assert(nr.Driver, checker.Equals, "bridge")
  309. c.Assert(nr.Scope, checker.Equals, "local")
  310. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  311. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  312. c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16")
  313. c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24")
  314. c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254")
  315. dockerCmd(c, "network", "rm", "br0")
  316. }
  317. func (s *DockerNetworkSuite) TestDockerNetworkIpamInvalidCombinations(c *check.C) {
  318. // network with ip-range out of subnet range
  319. _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
  320. c.Assert(err, check.NotNil)
  321. // network with multiple gateways for a single subnet
  322. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
  323. c.Assert(err, check.NotNil)
  324. // Multiple overlaping subnets in the same network must fail
  325. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
  326. c.Assert(err, check.NotNil)
  327. // overlapping subnets across networks must fail
  328. // create a valid test0 network
  329. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
  330. assertNwIsAvailable(c, "test0")
  331. // create an overlapping test1 network
  332. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
  333. c.Assert(err, check.NotNil)
  334. dockerCmd(c, "network", "rm", "test0")
  335. }
  336. func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) {
  337. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
  338. assertNwIsAvailable(c, "testopt")
  339. gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
  340. c.Assert(gopts, checker.NotNil)
  341. opts, ok := gopts.(map[string]interface{})
  342. c.Assert(ok, checker.Equals, true)
  343. c.Assert(opts["opt1"], checker.Equals, "drv1")
  344. c.Assert(opts["opt2"], checker.Equals, "drv2")
  345. dockerCmd(c, "network", "rm", "testopt")
  346. }