docker_cli_network_unix_test.go 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  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 retrieved 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) TestDockerNetworkCreateHostBind(c *check.C) {
  254. dockerCmd(c, "network", "create", "--subnet=192.168.10.0/24", "--gateway=192.168.10.1", "-o", "com.docker.network.bridge.host_binding_ipv4=192.168.10.1", "testbind")
  255. assertNwIsAvailable(c, "testbind")
  256. out, _ := runSleepingContainer(c, "--net=testbind", "-p", "5000:5000")
  257. id := strings.TrimSpace(out)
  258. c.Assert(waitRun(id), checker.IsNil)
  259. out, _ = dockerCmd(c, "ps")
  260. c.Assert(out, checker.Contains, "192.168.10.1:5000->5000/tcp")
  261. }
  262. func (s *DockerNetworkSuite) TestDockerNetworkRmPredefined(c *check.C) {
  263. predefined := []string{"bridge", "host", "none", "default"}
  264. for _, net := range predefined {
  265. // predefined networks can't be removed
  266. out, _, err := dockerCmdWithError("network", "rm", net)
  267. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  268. }
  269. }
  270. func (s *DockerNetworkSuite) TestDockerNetworkLsFilter(c *check.C) {
  271. out, _ := dockerCmd(c, "network", "create", "dev")
  272. defer func() {
  273. dockerCmd(c, "network", "rm", "dev")
  274. }()
  275. networkID := strings.TrimSpace(out)
  276. // filter with partial ID and partial name
  277. // only show 'bridge' and 'dev' network
  278. out, _ = dockerCmd(c, "network", "ls", "-f", "id="+networkID[0:5], "-f", "name=dge")
  279. assertNwList(c, out, []string{"dev", "bridge"})
  280. // only show built-in network (bridge, none, host)
  281. out, _ = dockerCmd(c, "network", "ls", "-f", "type=builtin")
  282. assertNwList(c, out, []string{"bridge", "none", "host"})
  283. // only show custom networks (dev)
  284. out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom")
  285. assertNwList(c, out, []string{"dev"})
  286. // show all networks with filter
  287. // it should be equivalent of ls without option
  288. out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom", "-f", "type=builtin")
  289. assertNwList(c, out, []string{"dev", "bridge", "host", "none"})
  290. }
  291. func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *check.C) {
  292. dockerCmd(c, "network", "create", "test")
  293. assertNwIsAvailable(c, "test")
  294. dockerCmd(c, "network", "rm", "test")
  295. assertNwNotAvailable(c, "test")
  296. }
  297. func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *check.C) {
  298. out, _, err := dockerCmdWithError("network", "rm", "test")
  299. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  300. }
  301. func (s *DockerSuite) TestDockerNetworkDeleteMultiple(c *check.C) {
  302. dockerCmd(c, "network", "create", "testDelMulti0")
  303. assertNwIsAvailable(c, "testDelMulti0")
  304. dockerCmd(c, "network", "create", "testDelMulti1")
  305. assertNwIsAvailable(c, "testDelMulti1")
  306. dockerCmd(c, "network", "create", "testDelMulti2")
  307. assertNwIsAvailable(c, "testDelMulti2")
  308. out, _ := dockerCmd(c, "run", "-d", "--net", "testDelMulti2", "busybox", "top")
  309. containerID := strings.TrimSpace(out)
  310. waitRun(containerID)
  311. // delete three networks at the same time, since testDelMulti2
  312. // contains active container, its deletion should fail.
  313. out, _, err := dockerCmdWithError("network", "rm", "testDelMulti0", "testDelMulti1", "testDelMulti2")
  314. // err should not be nil due to deleting testDelMulti2 failed.
  315. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  316. // testDelMulti2 should fail due to network has active endpoints
  317. c.Assert(out, checker.Contains, "has active endpoints")
  318. assertNwNotAvailable(c, "testDelMulti0")
  319. assertNwNotAvailable(c, "testDelMulti1")
  320. // testDelMulti2 can't be deleted, so it should exist
  321. assertNwIsAvailable(c, "testDelMulti2")
  322. }
  323. func (s *DockerSuite) TestDockerNetworkInspect(c *check.C) {
  324. out, _ := dockerCmd(c, "network", "inspect", "host")
  325. networkResources := []types.NetworkResource{}
  326. err := json.Unmarshal([]byte(out), &networkResources)
  327. c.Assert(err, check.IsNil)
  328. c.Assert(networkResources, checker.HasLen, 1)
  329. out, _ = dockerCmd(c, "network", "inspect", "--format='{{ .Name }}'", "host")
  330. c.Assert(strings.TrimSpace(out), check.Equals, "host")
  331. }
  332. func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) {
  333. out, _ := dockerCmd(c, "network", "inspect", "host", "none")
  334. networkResources := []types.NetworkResource{}
  335. err := json.Unmarshal([]byte(out), &networkResources)
  336. c.Assert(err, check.IsNil)
  337. c.Assert(networkResources, checker.HasLen, 2)
  338. // Should print an error, return an exitCode 1 *but* should print the host network
  339. out, exitCode, err := dockerCmdWithError("network", "inspect", "host", "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. networkResources = []types.NetworkResource{}
  344. inspectOut := strings.SplitN(out, "\nError: No such network: nonexistent\n", 2)[0]
  345. err = json.Unmarshal([]byte(inspectOut), &networkResources)
  346. c.Assert(networkResources, checker.HasLen, 1)
  347. // Should print an error and return an exitCode, nothing else
  348. out, exitCode, err = dockerCmdWithError("network", "inspect", "nonexistent")
  349. c.Assert(err, checker.NotNil)
  350. c.Assert(exitCode, checker.Equals, 1)
  351. c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
  352. }
  353. func (s *DockerSuite) TestDockerInspectNetworkWithContainerName(c *check.C) {
  354. dockerCmd(c, "network", "create", "brNetForInspect")
  355. assertNwIsAvailable(c, "brNetForInspect")
  356. defer func() {
  357. dockerCmd(c, "network", "rm", "brNetForInspect")
  358. assertNwNotAvailable(c, "brNetForInspect")
  359. }()
  360. out, _ := dockerCmd(c, "run", "-d", "--name", "testNetInspect1", "--net", "brNetForInspect", "busybox", "top")
  361. c.Assert(waitRun("testNetInspect1"), check.IsNil)
  362. containerID := strings.TrimSpace(out)
  363. defer func() {
  364. // we don't stop container by name, because we'll rename it later
  365. dockerCmd(c, "stop", containerID)
  366. }()
  367. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  368. networkResources := []types.NetworkResource{}
  369. err := json.Unmarshal([]byte(out), &networkResources)
  370. c.Assert(err, check.IsNil)
  371. c.Assert(networkResources, checker.HasLen, 1)
  372. container, ok := networkResources[0].Containers[containerID]
  373. c.Assert(ok, checker.True)
  374. c.Assert(container.Name, checker.Equals, "testNetInspect1")
  375. // rename container and check docker inspect output update
  376. newName := "HappyNewName"
  377. dockerCmd(c, "rename", "testNetInspect1", newName)
  378. // check whether network inspect works properly
  379. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  380. newNetRes := []types.NetworkResource{}
  381. err = json.Unmarshal([]byte(out), &newNetRes)
  382. c.Assert(err, check.IsNil)
  383. c.Assert(newNetRes, checker.HasLen, 1)
  384. container1, ok := newNetRes[0].Containers[containerID]
  385. c.Assert(ok, checker.True)
  386. c.Assert(container1.Name, checker.Equals, newName)
  387. }
  388. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) {
  389. dockerCmd(c, "network", "create", "test")
  390. assertNwIsAvailable(c, "test")
  391. nr := getNwResource(c, "test")
  392. c.Assert(nr.Name, checker.Equals, "test")
  393. c.Assert(len(nr.Containers), checker.Equals, 0)
  394. // run a container
  395. out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  396. c.Assert(waitRun("test"), check.IsNil)
  397. containerID := strings.TrimSpace(out)
  398. // connect the container to the test network
  399. dockerCmd(c, "network", "connect", "test", containerID)
  400. // inspect the network to make sure container is connected
  401. nr = getNetworkResource(c, nr.ID)
  402. c.Assert(len(nr.Containers), checker.Equals, 1)
  403. c.Assert(nr.Containers[containerID], check.NotNil)
  404. // check if container IP matches network inspect
  405. ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address)
  406. c.Assert(err, check.IsNil)
  407. containerIP := findContainerIP(c, "test", "test")
  408. c.Assert(ip.String(), checker.Equals, containerIP)
  409. // disconnect container from the network
  410. dockerCmd(c, "network", "disconnect", "test", containerID)
  411. nr = getNwResource(c, "test")
  412. c.Assert(nr.Name, checker.Equals, "test")
  413. c.Assert(len(nr.Containers), checker.Equals, 0)
  414. // run another container
  415. out, _ = dockerCmd(c, "run", "-d", "--net", "test", "--name", "test2", "busybox", "top")
  416. c.Assert(waitRun("test2"), check.IsNil)
  417. containerID = strings.TrimSpace(out)
  418. nr = getNwResource(c, "test")
  419. c.Assert(nr.Name, checker.Equals, "test")
  420. c.Assert(len(nr.Containers), checker.Equals, 1)
  421. // force disconnect the container to the test network
  422. dockerCmd(c, "network", "disconnect", "-f", "test", containerID)
  423. nr = getNwResource(c, "test")
  424. c.Assert(nr.Name, checker.Equals, "test")
  425. c.Assert(len(nr.Containers), checker.Equals, 0)
  426. dockerCmd(c, "network", "rm", "test")
  427. assertNwNotAvailable(c, "test")
  428. }
  429. func (s *DockerNetworkSuite) TestDockerNetworkIpamMultipleNetworks(c *check.C) {
  430. // test0 bridge network
  431. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
  432. assertNwIsAvailable(c, "test1")
  433. // test2 bridge network does not overlap
  434. dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
  435. assertNwIsAvailable(c, "test2")
  436. // for networks w/o ipam specified, docker will choose proper non-overlapping subnets
  437. dockerCmd(c, "network", "create", "test3")
  438. assertNwIsAvailable(c, "test3")
  439. dockerCmd(c, "network", "create", "test4")
  440. assertNwIsAvailable(c, "test4")
  441. dockerCmd(c, "network", "create", "test5")
  442. assertNwIsAvailable(c, "test5")
  443. // test network with multiple subnets
  444. // bridge network doesn't support multiple subnets. hence, use a dummy driver that supports
  445. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6")
  446. assertNwIsAvailable(c, "test6")
  447. // test network with multiple subnets with valid ipam combinations
  448. // also check same subnet across networks when the driver supports it.
  449. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
  450. "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16",
  451. "--gateway=192.168.0.100", "--gateway=192.170.0.100",
  452. "--ip-range=192.168.1.0/24",
  453. "--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6",
  454. "--aux-address", "a=192.170.1.5", "--aux-address", "b=192.170.1.6",
  455. "test7")
  456. assertNwIsAvailable(c, "test7")
  457. // cleanup
  458. for i := 1; i < 8; i++ {
  459. dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
  460. }
  461. }
  462. func (s *DockerNetworkSuite) TestDockerNetworkCustomIpam(c *check.C) {
  463. // Create a bridge network using custom ipam driver
  464. dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "br0")
  465. assertNwIsAvailable(c, "br0")
  466. // Verify expected network ipam fields are there
  467. nr := getNetworkResource(c, "br0")
  468. c.Assert(nr.Driver, checker.Equals, "bridge")
  469. c.Assert(nr.IPAM.Driver, checker.Equals, dummyIpamDriver)
  470. // remove network and exercise remote ipam driver
  471. dockerCmd(c, "network", "rm", "br0")
  472. assertNwNotAvailable(c, "br0")
  473. }
  474. func (s *DockerNetworkSuite) TestDockerNetworkIpamOptions(c *check.C) {
  475. // Create a bridge network using custom ipam driver and options
  476. dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "--ipam-opt", "opt1=drv1", "--ipam-opt", "opt2=drv2", "br0")
  477. assertNwIsAvailable(c, "br0")
  478. // Verify expected network ipam options
  479. nr := getNetworkResource(c, "br0")
  480. opts := nr.IPAM.Options
  481. c.Assert(opts["opt1"], checker.Equals, "drv1")
  482. c.Assert(opts["opt2"], checker.Equals, "drv2")
  483. }
  484. func (s *DockerNetworkSuite) TestDockerNetworkInspectDefault(c *check.C) {
  485. nr := getNetworkResource(c, "none")
  486. c.Assert(nr.Driver, checker.Equals, "null")
  487. c.Assert(nr.Scope, checker.Equals, "local")
  488. c.Assert(nr.Internal, checker.Equals, false)
  489. c.Assert(nr.EnableIPv6, checker.Equals, false)
  490. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  491. c.Assert(len(nr.IPAM.Config), checker.Equals, 0)
  492. nr = getNetworkResource(c, "host")
  493. c.Assert(nr.Driver, checker.Equals, "host")
  494. c.Assert(nr.Scope, checker.Equals, "local")
  495. c.Assert(nr.Internal, checker.Equals, false)
  496. c.Assert(nr.EnableIPv6, checker.Equals, false)
  497. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  498. c.Assert(len(nr.IPAM.Config), checker.Equals, 0)
  499. nr = getNetworkResource(c, "bridge")
  500. c.Assert(nr.Driver, checker.Equals, "bridge")
  501. c.Assert(nr.Scope, checker.Equals, "local")
  502. c.Assert(nr.Internal, checker.Equals, false)
  503. c.Assert(nr.EnableIPv6, checker.Equals, false)
  504. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  505. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  506. c.Assert(nr.IPAM.Config[0].Subnet, checker.NotNil)
  507. c.Assert(nr.IPAM.Config[0].Gateway, checker.NotNil)
  508. }
  509. func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomUnspecified(c *check.C) {
  510. // if unspecified, network subnet will be selected from inside preferred pool
  511. dockerCmd(c, "network", "create", "test01")
  512. assertNwIsAvailable(c, "test01")
  513. nr := getNetworkResource(c, "test01")
  514. c.Assert(nr.Driver, checker.Equals, "bridge")
  515. c.Assert(nr.Scope, checker.Equals, "local")
  516. c.Assert(nr.Internal, checker.Equals, false)
  517. c.Assert(nr.EnableIPv6, checker.Equals, false)
  518. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  519. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  520. c.Assert(nr.IPAM.Config[0].Subnet, checker.NotNil)
  521. c.Assert(nr.IPAM.Config[0].Gateway, checker.NotNil)
  522. dockerCmd(c, "network", "rm", "test01")
  523. assertNwNotAvailable(c, "test01")
  524. }
  525. func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomSpecified(c *check.C) {
  526. dockerCmd(c, "network", "create", "--driver=bridge", "--ipv6", "--subnet=172.28.0.0/16", "--ip-range=172.28.5.0/24", "--gateway=172.28.5.254", "br0")
  527. assertNwIsAvailable(c, "br0")
  528. nr := getNetworkResource(c, "br0")
  529. c.Assert(nr.Driver, checker.Equals, "bridge")
  530. c.Assert(nr.Scope, checker.Equals, "local")
  531. c.Assert(nr.Internal, checker.Equals, false)
  532. c.Assert(nr.EnableIPv6, checker.Equals, true)
  533. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  534. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  535. c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16")
  536. c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24")
  537. c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254")
  538. c.Assert(nr.Internal, checker.False)
  539. dockerCmd(c, "network", "rm", "br0")
  540. assertNwNotAvailable(c, "test01")
  541. }
  542. func (s *DockerNetworkSuite) TestDockerNetworkIpamInvalidCombinations(c *check.C) {
  543. // network with ip-range out of subnet range
  544. _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
  545. c.Assert(err, check.NotNil)
  546. // network with multiple gateways for a single subnet
  547. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
  548. c.Assert(err, check.NotNil)
  549. // Multiple overlapping subnets in the same network must fail
  550. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
  551. c.Assert(err, check.NotNil)
  552. // overlapping subnets across networks must fail
  553. // create a valid test0 network
  554. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
  555. assertNwIsAvailable(c, "test0")
  556. // create an overlapping test1 network
  557. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
  558. c.Assert(err, check.NotNil)
  559. dockerCmd(c, "network", "rm", "test0")
  560. assertNwNotAvailable(c, "test0")
  561. }
  562. func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) {
  563. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
  564. assertNwIsAvailable(c, "testopt")
  565. gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
  566. c.Assert(gopts, checker.NotNil)
  567. opts, ok := gopts.(map[string]interface{})
  568. c.Assert(ok, checker.Equals, true)
  569. c.Assert(opts["opt1"], checker.Equals, "drv1")
  570. c.Assert(opts["opt2"], checker.Equals, "drv2")
  571. dockerCmd(c, "network", "rm", "testopt")
  572. assertNwNotAvailable(c, "testopt")
  573. }
  574. func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *check.C) {
  575. testRequires(c, ExecSupport)
  576. // On default bridge network built-in service discovery should not happen
  577. hostsFile := "/etc/hosts"
  578. bridgeName := "external-bridge"
  579. bridgeIP := "192.169.255.254/24"
  580. out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
  581. c.Assert(err, check.IsNil, check.Commentf(out))
  582. defer deleteInterface(c, bridgeName)
  583. err = s.d.StartWithBusybox("--bridge", bridgeName)
  584. c.Assert(err, check.IsNil)
  585. defer s.d.Restart()
  586. // run two containers and store first container's etc/hosts content
  587. out, err = s.d.Cmd("run", "-d", "busybox", "top")
  588. c.Assert(err, check.IsNil)
  589. cid1 := strings.TrimSpace(out)
  590. defer s.d.Cmd("stop", cid1)
  591. hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  592. c.Assert(err, checker.IsNil)
  593. out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top")
  594. c.Assert(err, check.IsNil)
  595. cid2 := strings.TrimSpace(out)
  596. // verify first container's etc/hosts file has not changed after spawning the second named container
  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 container creation", hostsFile))
  601. // stop container 2 and verify first container's etc/hosts has not changed
  602. _, err = s.d.Cmd("stop", cid2)
  603. c.Assert(err, check.IsNil)
  604. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  605. c.Assert(err, checker.IsNil)
  606. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  607. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  608. // but discovery is on when connecting to non default bridge network
  609. network := "anotherbridge"
  610. out, err = s.d.Cmd("network", "create", network)
  611. c.Assert(err, check.IsNil, check.Commentf(out))
  612. defer s.d.Cmd("network", "rm", network)
  613. out, err = s.d.Cmd("network", "connect", network, cid1)
  614. c.Assert(err, check.IsNil, check.Commentf(out))
  615. hosts, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  616. c.Assert(err, checker.IsNil)
  617. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  618. c.Assert(err, checker.IsNil)
  619. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  620. check.Commentf("Unexpected %s change on second network connection", hostsFile))
  621. }
  622. func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
  623. testRequires(c, ExecSupport, NotArm)
  624. hostsFile := "/etc/hosts"
  625. cstmBridgeNw := "custom-bridge-nw"
  626. cstmBridgeNw1 := "custom-bridge-nw1"
  627. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw)
  628. assertNwIsAvailable(c, cstmBridgeNw)
  629. // run two anonymous containers and store their etc/hosts content
  630. out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  631. cid1 := strings.TrimSpace(out)
  632. hosts1, err := readContainerFileWithExec(cid1, hostsFile)
  633. c.Assert(err, checker.IsNil)
  634. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  635. cid2 := strings.TrimSpace(out)
  636. hosts2, err := readContainerFileWithExec(cid2, hostsFile)
  637. c.Assert(err, checker.IsNil)
  638. // verify first container etc/hosts file has not changed
  639. hosts1post, err := readContainerFileWithExec(cid1, hostsFile)
  640. c.Assert(err, checker.IsNil)
  641. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  642. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  643. // Connect the 2nd container to a new network and verify the
  644. // first container /etc/hosts file still hasn't changed.
  645. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1)
  646. assertNwIsAvailable(c, cstmBridgeNw1)
  647. dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2)
  648. hosts2, err = readContainerFileWithExec(cid2, hostsFile)
  649. c.Assert(err, checker.IsNil)
  650. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  651. c.Assert(err, checker.IsNil)
  652. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  653. check.Commentf("Unexpected %s change on container connect", hostsFile))
  654. // start a named container
  655. cName := "AnyName"
  656. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top")
  657. cid3 := strings.TrimSpace(out)
  658. // verify that container 1 and 2 can ping the named container
  659. dockerCmd(c, "exec", cid1, "ping", "-c", "1", cName)
  660. dockerCmd(c, "exec", cid2, "ping", "-c", "1", cName)
  661. // Stop named container and verify first two containers' etc/hosts file hasn't changed
  662. dockerCmd(c, "stop", cid3)
  663. hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
  664. c.Assert(err, checker.IsNil)
  665. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  666. check.Commentf("Unexpected %s change on name container creation", hostsFile))
  667. hosts2post, err := readContainerFileWithExec(cid2, hostsFile)
  668. c.Assert(err, checker.IsNil)
  669. c.Assert(string(hosts2), checker.Equals, string(hosts2post),
  670. check.Commentf("Unexpected %s change on name container creation", hostsFile))
  671. // verify that container 1 and 2 can't ping the named container now
  672. _, _, err = dockerCmdWithError("exec", cid1, "ping", "-c", "1", cName)
  673. c.Assert(err, check.NotNil)
  674. _, _, err = dockerCmdWithError("exec", cid2, "ping", "-c", "1", cName)
  675. c.Assert(err, check.NotNil)
  676. }
  677. func (s *DockerNetworkSuite) TestDockerNetworkLinkOndefaultNetworkOnly(c *check.C) {
  678. // Link feature must work only on default network, and not across networks
  679. cnt1 := "container1"
  680. cnt2 := "container2"
  681. network := "anotherbridge"
  682. // Run first container on default network
  683. dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top")
  684. // Create another network and run the second container on it
  685. dockerCmd(c, "network", "create", network)
  686. assertNwIsAvailable(c, network)
  687. dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top")
  688. // Try launching a container on default network, linking to the first container. Must succeed
  689. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top")
  690. // Try launching a container on default network, linking to the second container. Must fail
  691. _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  692. c.Assert(err, checker.NotNil)
  693. // Connect second container to default network. Now a container on default network can link to it
  694. dockerCmd(c, "network", "connect", "bridge", cnt2)
  695. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  696. }
  697. func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) {
  698. // Verify exposed ports are present in ps output when running a container on
  699. // a network managed by a driver which does not provide the default gateway
  700. // for the container
  701. nwn := "ov"
  702. ctn := "bb"
  703. port1 := 80
  704. port2 := 443
  705. expose1 := fmt.Sprintf("--expose=%d", port1)
  706. expose2 := fmt.Sprintf("--expose=%d", port2)
  707. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  708. assertNwIsAvailable(c, nwn)
  709. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top")
  710. // Check docker ps o/p for last created container reports the unpublished ports
  711. unpPort1 := fmt.Sprintf("%d/tcp", port1)
  712. unpPort2 := fmt.Sprintf("%d/tcp", port2)
  713. out, _ := dockerCmd(c, "ps", "-n=1")
  714. // Missing unpublished ports in docker ps output
  715. c.Assert(out, checker.Contains, unpPort1)
  716. // Missing unpublished ports in docker ps output
  717. c.Assert(out, checker.Contains, unpPort2)
  718. }
  719. func (s *DockerNetworkSuite) TestDockerNetworkDriverUngracefulRestart(c *check.C) {
  720. testRequires(c, DaemonIsLinux, NotUserNamespace)
  721. dnd := "dnd"
  722. did := "did"
  723. mux := http.NewServeMux()
  724. server := httptest.NewServer(mux)
  725. setupRemoteNetworkDrivers(c, mux, server.URL, dnd, did)
  726. s.d.StartWithBusybox()
  727. _, err := s.d.Cmd("network", "create", "-d", dnd, "--subnet", "1.1.1.0/24", "net1")
  728. c.Assert(err, checker.IsNil)
  729. _, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "foo", "--ip", "1.1.1.10", "busybox", "sh")
  730. c.Assert(err, checker.IsNil)
  731. // Kill daemon and restart
  732. if err = s.d.cmd.Process.Kill(); err != nil {
  733. c.Fatal(err)
  734. }
  735. server.Close()
  736. startTime := time.Now().Unix()
  737. if err = s.d.Restart(); err != nil {
  738. c.Fatal(err)
  739. }
  740. lapse := time.Now().Unix() - startTime
  741. if lapse > 60 {
  742. // In normal scenarios, daemon restart takes ~1 second.
  743. // Plugin retry mechanism can delay the daemon start. systemd may not like it.
  744. // Avoid accessing plugins during daemon bootup
  745. c.Logf("daemon restart took too long : %d seconds", lapse)
  746. }
  747. // Restart the custom dummy plugin
  748. mux = http.NewServeMux()
  749. server = httptest.NewServer(mux)
  750. setupRemoteNetworkDrivers(c, mux, server.URL, dnd, did)
  751. // trying to reuse the same ip must succeed
  752. _, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "bar", "--ip", "1.1.1.10", "busybox", "sh")
  753. c.Assert(err, checker.IsNil)
  754. }
  755. func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) {
  756. // Verify endpoint MAC address is correctly populated in container's network settings
  757. nwn := "ov"
  758. ctn := "bb"
  759. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  760. assertNwIsAvailable(c, nwn)
  761. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top")
  762. mac := inspectField(c, ctn, "NetworkSettings.Networks."+nwn+".MacAddress")
  763. c.Assert(mac, checker.Equals, "a0:b1:c2:d3:e4:f5")
  764. }
  765. func (s *DockerSuite) TestInspectApiMultipleNetworks(c *check.C) {
  766. dockerCmd(c, "network", "create", "mybridge1")
  767. dockerCmd(c, "network", "create", "mybridge2")
  768. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  769. id := strings.TrimSpace(out)
  770. c.Assert(waitRun(id), check.IsNil)
  771. dockerCmd(c, "network", "connect", "mybridge1", id)
  772. dockerCmd(c, "network", "connect", "mybridge2", id)
  773. body := getInspectBody(c, "v1.20", id)
  774. var inspect120 v1p20.ContainerJSON
  775. err := json.Unmarshal(body, &inspect120)
  776. c.Assert(err, checker.IsNil)
  777. versionedIP := inspect120.NetworkSettings.IPAddress
  778. body = getInspectBody(c, "v1.21", id)
  779. var inspect121 types.ContainerJSON
  780. err = json.Unmarshal(body, &inspect121)
  781. c.Assert(err, checker.IsNil)
  782. c.Assert(inspect121.NetworkSettings.Networks, checker.HasLen, 3)
  783. bridge := inspect121.NetworkSettings.Networks["bridge"]
  784. c.Assert(bridge.IPAddress, checker.Equals, versionedIP)
  785. c.Assert(bridge.IPAddress, checker.Equals, inspect121.NetworkSettings.IPAddress)
  786. }
  787. func connectContainerToNetworks(c *check.C, d *Daemon, cName string, nws []string) {
  788. // Run a container on the default network
  789. out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
  790. c.Assert(err, checker.IsNil, check.Commentf(out))
  791. // Attach the container to other networks
  792. for _, nw := range nws {
  793. out, err = d.Cmd("network", "create", nw)
  794. c.Assert(err, checker.IsNil, check.Commentf(out))
  795. out, err = d.Cmd("network", "connect", nw, cName)
  796. c.Assert(err, checker.IsNil, check.Commentf(out))
  797. }
  798. }
  799. func verifyContainerIsConnectedToNetworks(c *check.C, d *Daemon, cName string, nws []string) {
  800. // Verify container is connected to all the networks
  801. for _, nw := range nws {
  802. out, err := d.Cmd("inspect", "-f", fmt.Sprintf("{{.NetworkSettings.Networks.%s}}", nw), cName)
  803. c.Assert(err, checker.IsNil, check.Commentf(out))
  804. c.Assert(out, checker.Not(checker.Equals), "<no value>\n")
  805. }
  806. }
  807. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRestart(c *check.C) {
  808. cName := "bb"
  809. nwList := []string{"nw1", "nw2", "nw3"}
  810. s.d.StartWithBusybox()
  811. connectContainerToNetworks(c, s.d, cName, nwList)
  812. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  813. // Reload daemon
  814. s.d.Restart()
  815. _, err := s.d.Cmd("start", cName)
  816. c.Assert(err, checker.IsNil)
  817. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  818. }
  819. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksUngracefulDaemonRestart(c *check.C) {
  820. cName := "cc"
  821. nwList := []string{"nw1", "nw2", "nw3"}
  822. s.d.StartWithBusybox()
  823. connectContainerToNetworks(c, s.d, cName, nwList)
  824. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  825. // Kill daemon and restart
  826. if err := s.d.cmd.Process.Kill(); err != nil {
  827. c.Fatal(err)
  828. }
  829. s.d.Restart()
  830. // Restart container
  831. _, err := s.d.Cmd("start", cName)
  832. c.Assert(err, checker.IsNil)
  833. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  834. }
  835. func (s *DockerNetworkSuite) TestDockerNetworkRunNetByID(c *check.C) {
  836. out, _ := dockerCmd(c, "network", "create", "one")
  837. containerOut, _, err := dockerCmdWithError("run", "-d", "--net", strings.TrimSpace(out), "busybox", "top")
  838. c.Assert(err, checker.IsNil, check.Commentf(containerOut))
  839. }
  840. func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c *check.C) {
  841. testRequires(c, DaemonIsLinux, NotUserNamespace)
  842. s.d.StartWithBusybox()
  843. // Run a few containers on host network
  844. for i := 0; i < 10; i++ {
  845. cName := fmt.Sprintf("hostc-%d", i)
  846. out, err := s.d.Cmd("run", "-d", "--name", cName, "--net=host", "--restart=always", "busybox", "top")
  847. c.Assert(err, checker.IsNil, check.Commentf(out))
  848. // verfiy container has finished starting before killing daemon
  849. err = s.d.waitRun(cName)
  850. c.Assert(err, checker.IsNil)
  851. }
  852. // Kill daemon ungracefully and restart
  853. if err := s.d.cmd.Process.Kill(); err != nil {
  854. c.Fatal(err)
  855. }
  856. if err := s.d.Restart(); err != nil {
  857. c.Fatal(err)
  858. }
  859. // make sure all the containers are up and running
  860. for i := 0; i < 10; i++ {
  861. err := s.d.waitRun(fmt.Sprintf("hostc-%d", i))
  862. c.Assert(err, checker.IsNil)
  863. }
  864. }
  865. func (s *DockerNetworkSuite) TestDockerNetworkConnectToHostFromOtherNetwork(c *check.C) {
  866. dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
  867. c.Assert(waitRun("container1"), check.IsNil)
  868. dockerCmd(c, "network", "disconnect", "bridge", "container1")
  869. out, _, err := dockerCmdWithError("network", "connect", "host", "container1")
  870. c.Assert(err, checker.NotNil, check.Commentf(out))
  871. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  872. }
  873. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromHost(c *check.C) {
  874. dockerCmd(c, "run", "-d", "--name", "container1", "--net=host", "busybox", "top")
  875. c.Assert(waitRun("container1"), check.IsNil)
  876. out, _, err := dockerCmdWithError("network", "disconnect", "host", "container1")
  877. c.Assert(err, checker.NotNil, check.Commentf("Should err out disconnect from host"))
  878. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  879. }
  880. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithPortMapping(c *check.C) {
  881. testRequires(c, NotArm)
  882. dockerCmd(c, "network", "create", "test1")
  883. dockerCmd(c, "run", "-d", "--name", "c1", "-p", "5000:5000", "busybox", "top")
  884. c.Assert(waitRun("c1"), check.IsNil)
  885. dockerCmd(c, "network", "connect", "test1", "c1")
  886. }
  887. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithMac(c *check.C) {
  888. macAddress := "02:42:ac:11:00:02"
  889. dockerCmd(c, "network", "create", "mynetwork")
  890. dockerCmd(c, "run", "--name=test", "-d", "--mac-address", macAddress, "busybox", "top")
  891. c.Assert(waitRun("test"), check.IsNil)
  892. mac1 := inspectField(c, "test", "NetworkSettings.Networks.bridge.MacAddress")
  893. c.Assert(strings.TrimSpace(mac1), checker.Equals, macAddress)
  894. dockerCmd(c, "network", "connect", "mynetwork", "test")
  895. mac2 := inspectField(c, "test", "NetworkSettings.Networks.mynetwork.MacAddress")
  896. c.Assert(strings.TrimSpace(mac2), checker.Not(checker.Equals), strings.TrimSpace(mac1))
  897. }
  898. func (s *DockerNetworkSuite) TestDockerNetworkInspectCreatedContainer(c *check.C) {
  899. dockerCmd(c, "create", "--name", "test", "busybox")
  900. networks := inspectField(c, "test", "NetworkSettings.Networks")
  901. c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should return 'bridge' network"))
  902. }
  903. func (s *DockerNetworkSuite) TestDockerNetworkRestartWithMultipleNetworks(c *check.C) {
  904. dockerCmd(c, "network", "create", "test")
  905. dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
  906. c.Assert(waitRun("foo"), checker.IsNil)
  907. dockerCmd(c, "network", "connect", "test", "foo")
  908. dockerCmd(c, "restart", "foo")
  909. networks := inspectField(c, "foo", "NetworkSettings.Networks")
  910. c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should contain 'bridge' network"))
  911. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  912. }
  913. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectToStoppedContainer(c *check.C) {
  914. dockerCmd(c, "network", "create", "test")
  915. dockerCmd(c, "create", "--name=foo", "busybox", "top")
  916. dockerCmd(c, "network", "connect", "test", "foo")
  917. networks := inspectField(c, "foo", "NetworkSettings.Networks")
  918. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  919. // Restart docker daemon to test the config has persisted to disk
  920. s.d.Restart()
  921. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  922. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  923. // start the container and test if we can ping it from another container in the same network
  924. dockerCmd(c, "start", "foo")
  925. c.Assert(waitRun("foo"), checker.IsNil)
  926. ip := inspectField(c, "foo", "NetworkSettings.Networks.test.IPAddress")
  927. ip = strings.TrimSpace(ip)
  928. dockerCmd(c, "run", "--net=test", "busybox", "sh", "-c", fmt.Sprintf("ping -c 1 %s", ip))
  929. dockerCmd(c, "stop", "foo")
  930. // Test disconnect
  931. dockerCmd(c, "network", "disconnect", "test", "foo")
  932. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  933. c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
  934. // Restart docker daemon to test the config has persisted to disk
  935. s.d.Restart()
  936. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  937. c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
  938. }
  939. func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIP(c *check.C) {
  940. // create two networks
  941. dockerCmd(c, "network", "create", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "n0")
  942. assertNwIsAvailable(c, "n0")
  943. 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")
  944. assertNwIsAvailable(c, "n1")
  945. // run a container on first network specifying the ip addresses
  946. dockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  947. c.Assert(waitRun("c0"), check.IsNil)
  948. verifyIPAddressConfig(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  949. verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  950. // connect the container to the second network specifying an ip addresses
  951. dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n1", "c0")
  952. verifyIPAddressConfig(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  953. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  954. // Stop and restart the container
  955. dockerCmd(c, "stop", "c0")
  956. dockerCmd(c, "start", "c0")
  957. // verify requested addresses are applied and configs are still there
  958. verifyIPAddressConfig(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  959. verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  960. verifyIPAddressConfig(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  961. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  962. // Still it should fail to connect to the default network with a specified IP (whatever ip)
  963. out, _, err := dockerCmdWithError("network", "connect", "--ip", "172.21.55.44", "bridge", "c0")
  964. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  965. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
  966. }
  967. func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIPStoppedContainer(c *check.C) {
  968. // create a container
  969. dockerCmd(c, "create", "--name", "c0", "busybox", "top")
  970. // create a network
  971. dockerCmd(c, "network", "create", "--subnet=172.30.0.0/16", "--subnet=2001:db8:abcd::/64", "n0")
  972. assertNwIsAvailable(c, "n0")
  973. // connect the container to the network specifying an ip addresses
  974. dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n0", "c0")
  975. verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  976. // start the container, verify config has not changed and ip addresses are assigned
  977. dockerCmd(c, "start", "c0")
  978. c.Assert(waitRun("c0"), check.IsNil)
  979. verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  980. verifyIPAddresses(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  981. // stop the container and check ip config has not changed
  982. dockerCmd(c, "stop", "c0")
  983. verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  984. }
  985. func (s *DockerNetworkSuite) TestDockerNetworkUnsupportedRequiredIP(c *check.C) {
  986. // requested IP is not supported on predefined networks
  987. for _, mode := range []string{"none", "host", "bridge", "default"} {
  988. checkUnsupportedNetworkAndIP(c, mode)
  989. }
  990. // requested IP is not supported on networks with no user defined subnets
  991. dockerCmd(c, "network", "create", "n0")
  992. assertNwIsAvailable(c, "n0")
  993. out, _, err := dockerCmdWithError("run", "-d", "--ip", "172.28.99.88", "--net", "n0", "busybox", "top")
  994. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  995. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
  996. out, _, err = dockerCmdWithError("run", "-d", "--ip6", "2001:db8:1234::9988", "--net", "n0", "busybox", "top")
  997. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  998. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
  999. dockerCmd(c, "network", "rm", "n0")
  1000. assertNwNotAvailable(c, "n0")
  1001. }
  1002. func checkUnsupportedNetworkAndIP(c *check.C, nwMode string) {
  1003. out, _, err := dockerCmdWithError("run", "-d", "--net", nwMode, "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  1004. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1005. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
  1006. }
  1007. func verifyIPAddressConfig(c *check.C, cName, nwname, ipv4, ipv6 string) {
  1008. if ipv4 != "" {
  1009. out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAMConfig.IPv4Address", nwname))
  1010. c.Assert(strings.TrimSpace(out), check.Equals, ipv4)
  1011. }
  1012. if ipv6 != "" {
  1013. out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAMConfig.IPv6Address", nwname))
  1014. c.Assert(strings.TrimSpace(out), check.Equals, ipv6)
  1015. }
  1016. }
  1017. func verifyIPAddresses(c *check.C, cName, nwname, ipv4, ipv6 string) {
  1018. out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAddress", nwname))
  1019. c.Assert(strings.TrimSpace(out), check.Equals, ipv4)
  1020. out = inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.GlobalIPv6Address", nwname))
  1021. c.Assert(strings.TrimSpace(out), check.Equals, ipv6)
  1022. }
  1023. func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectLink(c *check.C) {
  1024. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  1025. dockerCmd(c, "network", "create", "-d", "bridge", "foo1")
  1026. dockerCmd(c, "network", "create", "-d", "bridge", "foo2")
  1027. dockerCmd(c, "run", "-d", "--net=foo1", "--name=first", "busybox", "top")
  1028. c.Assert(waitRun("first"), check.IsNil)
  1029. // run a container in a user-defined network with a link for an existing container
  1030. // and a link for a container that doesn't exist
  1031. dockerCmd(c, "run", "-d", "--net=foo1", "--name=second", "--link=first:FirstInFoo1",
  1032. "--link=third:bar", "busybox", "top")
  1033. c.Assert(waitRun("second"), check.IsNil)
  1034. // ping to first and its alias FirstInFoo1 must succeed
  1035. _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  1036. c.Assert(err, check.IsNil)
  1037. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1")
  1038. c.Assert(err, check.IsNil)
  1039. // connect first container to foo2 network
  1040. dockerCmd(c, "network", "connect", "foo2", "first")
  1041. // connect second container to foo2 network with a different alias for first container
  1042. dockerCmd(c, "network", "connect", "--link=first:FirstInFoo2", "foo2", "second")
  1043. // ping the new alias in network foo2
  1044. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2")
  1045. c.Assert(err, check.IsNil)
  1046. // disconnect first container from foo1 network
  1047. dockerCmd(c, "network", "disconnect", "foo1", "first")
  1048. // link in foo1 network must fail
  1049. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1")
  1050. c.Assert(err, check.NotNil)
  1051. // link in foo2 network must succeed
  1052. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2")
  1053. c.Assert(err, check.IsNil)
  1054. }
  1055. // #19100 This is a deprecated feature test, it should be removed in Docker 1.12
  1056. func (s *DockerNetworkSuite) TestDockerNetworkStartAPIWithHostconfig(c *check.C) {
  1057. netName := "test"
  1058. conName := "foo"
  1059. dockerCmd(c, "network", "create", netName)
  1060. dockerCmd(c, "create", "--name", conName, "busybox", "top")
  1061. config := map[string]interface{}{
  1062. "HostConfig": map[string]interface{}{
  1063. "NetworkMode": netName,
  1064. },
  1065. }
  1066. _, _, err := sockRequest("POST", "/containers/"+conName+"/start", config)
  1067. c.Assert(err, checker.IsNil)
  1068. c.Assert(waitRun(conName), checker.IsNil)
  1069. networks := inspectField(c, conName, "NetworkSettings.Networks")
  1070. c.Assert(networks, checker.Contains, netName, check.Commentf(fmt.Sprintf("Should contain '%s' network", netName)))
  1071. c.Assert(networks, checker.Not(checker.Contains), "bridge", check.Commentf("Should not contain 'bridge' network"))
  1072. }
  1073. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectDefault(c *check.C) {
  1074. netWorkName1 := "test1"
  1075. netWorkName2 := "test2"
  1076. containerName := "foo"
  1077. dockerCmd(c, "network", "create", netWorkName1)
  1078. dockerCmd(c, "network", "create", netWorkName2)
  1079. dockerCmd(c, "create", "--name", containerName, "busybox", "top")
  1080. dockerCmd(c, "network", "connect", netWorkName1, containerName)
  1081. dockerCmd(c, "network", "connect", netWorkName2, containerName)
  1082. dockerCmd(c, "network", "disconnect", "bridge", containerName)
  1083. dockerCmd(c, "start", containerName)
  1084. c.Assert(waitRun(containerName), checker.IsNil)
  1085. networks := inspectField(c, containerName, "NetworkSettings.Networks")
  1086. c.Assert(networks, checker.Contains, netWorkName1, check.Commentf(fmt.Sprintf("Should contain '%s' network", netWorkName1)))
  1087. c.Assert(networks, checker.Contains, netWorkName2, check.Commentf(fmt.Sprintf("Should contain '%s' network", netWorkName2)))
  1088. c.Assert(networks, checker.Not(checker.Contains), "bridge", check.Commentf("Should not contain 'bridge' network"))
  1089. }
  1090. func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectAlias(c *check.C) {
  1091. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  1092. dockerCmd(c, "network", "create", "-d", "bridge", "net1")
  1093. dockerCmd(c, "network", "create", "-d", "bridge", "net2")
  1094. dockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo", "busybox", "top")
  1095. c.Assert(waitRun("first"), check.IsNil)
  1096. dockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox", "top")
  1097. c.Assert(waitRun("second"), check.IsNil)
  1098. // ping first container and its alias
  1099. _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  1100. c.Assert(err, check.IsNil)
  1101. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
  1102. c.Assert(err, check.IsNil)
  1103. // connect first container to net2 network
  1104. dockerCmd(c, "network", "connect", "--alias=bar", "net2", "first")
  1105. // connect second container to foo2 network with a different alias for first container
  1106. dockerCmd(c, "network", "connect", "net2", "second")
  1107. // ping the new alias in network foo2
  1108. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
  1109. c.Assert(err, check.IsNil)
  1110. // disconnect first container from net1 network
  1111. dockerCmd(c, "network", "disconnect", "net1", "first")
  1112. // ping to net1 scoped alias "foo" must fail
  1113. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
  1114. c.Assert(err, check.NotNil)
  1115. // ping to net2 scoped alias "bar" must still succeed
  1116. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
  1117. c.Assert(err, check.IsNil)
  1118. // verify the alias option is rejected when running on predefined network
  1119. out, _, err := dockerCmdWithError("run", "--rm", "--name=any", "--net-alias=any", "busybox", "top")
  1120. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1121. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
  1122. // verify the alias option is rejected when connecting to predefined network
  1123. out, _, err = dockerCmdWithError("network", "connect", "--alias=any", "bridge", "first")
  1124. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1125. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
  1126. }
  1127. func (s *DockerSuite) TestUserDefinedNetworkConnectivity(c *check.C) {
  1128. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1129. dockerCmd(c, "network", "create", "-d", "bridge", "br.net1")
  1130. dockerCmd(c, "run", "-d", "--net=br.net1", "--name=c1.net1", "busybox", "top")
  1131. c.Assert(waitRun("c1.net1"), check.IsNil)
  1132. dockerCmd(c, "run", "-d", "--net=br.net1", "--name=c2.net1", "busybox", "top")
  1133. c.Assert(waitRun("c2.net1"), check.IsNil)
  1134. // ping first container by its unqualified name
  1135. _, _, err := dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1")
  1136. c.Assert(err, check.IsNil)
  1137. // ping first container by its qualified name
  1138. _, _, err = dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1.br.net1")
  1139. c.Assert(err, check.IsNil)
  1140. // ping with first qualified name masked by an additional domain. should fail
  1141. _, _, err = dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1.br.net1.google.com")
  1142. c.Assert(err, check.NotNil)
  1143. }
  1144. func (s *DockerSuite) TestEmbeddedDNSInvalidInput(c *check.C) {
  1145. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1146. dockerCmd(c, "network", "create", "-d", "bridge", "nw1")
  1147. // Sending garbge to embedded DNS shouldn't crash the daemon
  1148. dockerCmd(c, "run", "-i", "--net=nw1", "--name=c1", "debian:jessie", "bash", "-c", "echo InvalidQuery > /dev/udp/127.0.0.11/53")
  1149. }
  1150. func (s *DockerSuite) TestDockerNetworkConnectFailsNoInspectChange(c *check.C) {
  1151. dockerCmd(c, "run", "-d", "--name=bb", "busybox", "top")
  1152. c.Assert(waitRun("bb"), check.IsNil)
  1153. ns0 := inspectField(c, "bb", "NetworkSettings.Networks.bridge")
  1154. // A failing redundant network connect should not alter current container's endpoint settings
  1155. _, _, err := dockerCmdWithError("network", "connect", "bridge", "bb")
  1156. c.Assert(err, check.NotNil)
  1157. ns1 := inspectField(c, "bb", "NetworkSettings.Networks.bridge")
  1158. c.Assert(ns1, check.Equals, ns0)
  1159. }
  1160. func (s *DockerNetworkSuite) TestDockerNetworkInternalMode(c *check.C) {
  1161. dockerCmd(c, "network", "create", "--driver=bridge", "--internal", "internal")
  1162. assertNwIsAvailable(c, "internal")
  1163. nr := getNetworkResource(c, "internal")
  1164. c.Assert(nr.Internal, checker.True)
  1165. dockerCmd(c, "run", "-d", "--net=internal", "--name=first", "busybox", "top")
  1166. c.Assert(waitRun("first"), check.IsNil)
  1167. dockerCmd(c, "run", "-d", "--net=internal", "--name=second", "busybox", "top")
  1168. c.Assert(waitRun("second"), check.IsNil)
  1169. _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "www.google.com")
  1170. c.Assert(err, check.NotNil)
  1171. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  1172. c.Assert(err, check.IsNil)
  1173. }