docker_cli_network_unix_test.go 52 KB

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