docker_cli_network_unix_test.go 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860
  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. "path/filepath"
  12. "strings"
  13. "time"
  14. "github.com/docker/docker/api/types"
  15. "github.com/docker/docker/api/types/versions/v1p20"
  16. "github.com/docker/docker/integration-cli/checker"
  17. "github.com/docker/docker/integration-cli/cli"
  18. "github.com/docker/docker/integration-cli/daemon"
  19. "github.com/docker/docker/pkg/stringid"
  20. "github.com/docker/docker/runconfig"
  21. "github.com/docker/libnetwork/driverapi"
  22. remoteapi "github.com/docker/libnetwork/drivers/remote/api"
  23. "github.com/docker/libnetwork/ipamapi"
  24. remoteipam "github.com/docker/libnetwork/ipams/remote/api"
  25. "github.com/docker/libnetwork/netlabel"
  26. "github.com/go-check/check"
  27. "github.com/gotestyourself/gotestyourself/icmd"
  28. "github.com/vishvananda/netlink"
  29. "golang.org/x/sys/unix"
  30. )
  31. const dummyNetworkDriver = "dummy-network-driver"
  32. const dummyIPAMDriver = "dummy-ipam-driver"
  33. var remoteDriverNetworkRequest remoteapi.CreateNetworkRequest
  34. func init() {
  35. check.Suite(&DockerNetworkSuite{
  36. ds: &DockerSuite{},
  37. })
  38. }
  39. type DockerNetworkSuite struct {
  40. server *httptest.Server
  41. ds *DockerSuite
  42. d *daemon.Daemon
  43. }
  44. func (s *DockerNetworkSuite) SetUpTest(c *check.C) {
  45. s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
  46. Experimental: testEnv.ExperimentalDaemon(),
  47. })
  48. }
  49. func (s *DockerNetworkSuite) TearDownTest(c *check.C) {
  50. if s.d != nil {
  51. s.d.Stop(c)
  52. s.ds.TearDownTest(c)
  53. }
  54. }
  55. func (s *DockerNetworkSuite) SetUpSuite(c *check.C) {
  56. mux := http.NewServeMux()
  57. s.server = httptest.NewServer(mux)
  58. c.Assert(s.server, check.NotNil, check.Commentf("Failed to start an HTTP Server"))
  59. setupRemoteNetworkDrivers(c, mux, s.server.URL, dummyNetworkDriver, dummyIPAMDriver)
  60. }
  61. func setupRemoteNetworkDrivers(c *check.C, mux *http.ServeMux, url, netDrv, ipamDrv string) {
  62. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  63. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  64. fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType)
  65. })
  66. // Network driver implementation
  67. mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  68. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  69. fmt.Fprintf(w, `{"Scope":"local"}`)
  70. })
  71. mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  72. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  73. if err != nil {
  74. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  75. return
  76. }
  77. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  78. fmt.Fprintf(w, "null")
  79. })
  80. mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  81. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  82. fmt.Fprintf(w, "null")
  83. })
  84. mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  85. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  86. fmt.Fprintf(w, `{"Interface":{"MacAddress":"a0:b1:c2:d3:e4:f5"}}`)
  87. })
  88. mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  89. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  90. veth := &netlink.Veth{
  91. LinkAttrs: netlink.LinkAttrs{Name: "randomIfName", TxQLen: 0}, PeerName: "cnt0"}
  92. if err := netlink.LinkAdd(veth); err != nil {
  93. fmt.Fprintf(w, `{"Error":"failed to add veth pair: `+err.Error()+`"}`)
  94. } else {
  95. fmt.Fprintf(w, `{"InterfaceName":{ "SrcName":"cnt0", "DstPrefix":"veth"}}`)
  96. }
  97. })
  98. mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  99. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  100. fmt.Fprintf(w, "null")
  101. })
  102. mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  103. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  104. if link, err := netlink.LinkByName("cnt0"); err == nil {
  105. netlink.LinkDel(link)
  106. }
  107. fmt.Fprintf(w, "null")
  108. })
  109. // IPAM Driver implementation
  110. var (
  111. poolRequest remoteipam.RequestPoolRequest
  112. poolReleaseReq remoteipam.ReleasePoolRequest
  113. addressRequest remoteipam.RequestAddressRequest
  114. addressReleaseReq remoteipam.ReleaseAddressRequest
  115. lAS = "localAS"
  116. gAS = "globalAS"
  117. pool = "172.28.0.0/16"
  118. poolID = lAS + "/" + pool
  119. gw = "172.28.255.254/16"
  120. )
  121. mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  122. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  123. fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`)
  124. })
  125. mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  126. err := json.NewDecoder(r.Body).Decode(&poolRequest)
  127. if err != nil {
  128. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  129. return
  130. }
  131. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  132. if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS {
  133. fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`)
  134. } else if poolRequest.Pool != "" && poolRequest.Pool != pool {
  135. fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`)
  136. } else {
  137. fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`)
  138. }
  139. })
  140. mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  141. err := json.NewDecoder(r.Body).Decode(&addressRequest)
  142. if err != nil {
  143. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  144. return
  145. }
  146. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  147. // make sure libnetwork is now querying on the expected pool id
  148. if addressRequest.PoolID != poolID {
  149. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  150. } else if addressRequest.Address != "" {
  151. fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`)
  152. } else {
  153. fmt.Fprintf(w, `{"Address":"`+gw+`"}`)
  154. }
  155. })
  156. mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  157. err := json.NewDecoder(r.Body).Decode(&addressReleaseReq)
  158. if err != nil {
  159. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  160. return
  161. }
  162. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  163. // make sure libnetwork is now asking to release the expected address from the expected poolid
  164. if addressRequest.PoolID != poolID {
  165. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  166. } else if addressReleaseReq.Address != gw {
  167. fmt.Fprintf(w, `{"Error":"unknown address"}`)
  168. } else {
  169. fmt.Fprintf(w, "null")
  170. }
  171. })
  172. mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  173. err := json.NewDecoder(r.Body).Decode(&poolReleaseReq)
  174. if err != nil {
  175. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  176. return
  177. }
  178. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  179. // make sure libnetwork is now asking to release the expected poolid
  180. if addressRequest.PoolID != poolID {
  181. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  182. } else {
  183. fmt.Fprintf(w, "null")
  184. }
  185. })
  186. err := os.MkdirAll("/etc/docker/plugins", 0755)
  187. c.Assert(err, checker.IsNil)
  188. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", netDrv)
  189. err = ioutil.WriteFile(fileName, []byte(url), 0644)
  190. c.Assert(err, checker.IsNil)
  191. ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", ipamDrv)
  192. err = ioutil.WriteFile(ipamFileName, []byte(url), 0644)
  193. c.Assert(err, checker.IsNil)
  194. }
  195. func (s *DockerNetworkSuite) TearDownSuite(c *check.C) {
  196. if s.server == nil {
  197. return
  198. }
  199. s.server.Close()
  200. err := os.RemoveAll("/etc/docker/plugins")
  201. c.Assert(err, checker.IsNil)
  202. }
  203. func assertNwIsAvailable(c *check.C, name string) {
  204. if !isNwPresent(c, name) {
  205. c.Fatalf("Network %s not found in network ls o/p", name)
  206. }
  207. }
  208. func assertNwNotAvailable(c *check.C, name string) {
  209. if isNwPresent(c, name) {
  210. c.Fatalf("Found network %s in network ls o/p", name)
  211. }
  212. }
  213. func isNwPresent(c *check.C, name string) bool {
  214. out, _ := dockerCmd(c, "network", "ls")
  215. lines := strings.Split(out, "\n")
  216. for i := 1; i < len(lines)-1; i++ {
  217. netFields := strings.Fields(lines[i])
  218. if netFields[1] == name {
  219. return true
  220. }
  221. }
  222. return false
  223. }
  224. // assertNwList checks network list retrieved with ls command
  225. // equals to expected network list
  226. // note: out should be `network ls [option]` result
  227. func assertNwList(c *check.C, out string, expectNws []string) {
  228. lines := strings.Split(out, "\n")
  229. var nwList []string
  230. for _, line := range lines[1 : len(lines)-1] {
  231. netFields := strings.Fields(line)
  232. // wrap all network name in nwList
  233. nwList = append(nwList, netFields[1])
  234. }
  235. // network ls should contains all expected networks
  236. c.Assert(nwList, checker.DeepEquals, expectNws)
  237. }
  238. func getNwResource(c *check.C, name string) *types.NetworkResource {
  239. out, _ := dockerCmd(c, "network", "inspect", name)
  240. nr := []types.NetworkResource{}
  241. err := json.Unmarshal([]byte(out), &nr)
  242. c.Assert(err, check.IsNil)
  243. return &nr[0]
  244. }
  245. func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) {
  246. defaults := []string{"bridge", "host", "none"}
  247. for _, nn := range defaults {
  248. assertNwIsAvailable(c, nn)
  249. }
  250. }
  251. func (s *DockerSuite) TestNetworkLsFormat(c *check.C) {
  252. // E2E: Test assumes only default networks.
  253. testRequires(c, DaemonIsLinux, NotE2E)
  254. out, _ := dockerCmd(c, "network", "ls", "--format", "{{.Name}}")
  255. lines := strings.Split(strings.TrimSpace(string(out)), "\n")
  256. expected := []string{"bridge", "host", "none"}
  257. var names []string
  258. names = append(names, lines...)
  259. c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names))
  260. }
  261. func (s *DockerSuite) TestNetworkLsFormatDefaultFormat(c *check.C) {
  262. // E2E: Test assumes only default networks.
  263. testRequires(c, DaemonIsLinux, NotE2E)
  264. config := `{
  265. "networksFormat": "{{ .Name }} default"
  266. }`
  267. d, err := ioutil.TempDir("", "integration-cli-")
  268. c.Assert(err, checker.IsNil)
  269. defer os.RemoveAll(d)
  270. err = ioutil.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0644)
  271. c.Assert(err, checker.IsNil)
  272. out, _ := dockerCmd(c, "--config", d, "network", "ls")
  273. lines := strings.Split(strings.TrimSpace(string(out)), "\n")
  274. expected := []string{"bridge default", "host default", "none default"}
  275. var names []string
  276. names = append(names, lines...)
  277. c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names))
  278. }
  279. func (s *DockerNetworkSuite) TestDockerNetworkCreatePredefined(c *check.C) {
  280. predefined := []string{"bridge", "host", "none", "default"}
  281. for _, net := range predefined {
  282. // predefined networks can't be created again
  283. out, _, err := dockerCmdWithError("network", "create", net)
  284. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  285. }
  286. }
  287. func (s *DockerNetworkSuite) TestDockerNetworkCreateHostBind(c *check.C) {
  288. 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")
  289. assertNwIsAvailable(c, "testbind")
  290. out := runSleepingContainer(c, "--net=testbind", "-p", "5000:5000")
  291. id := strings.TrimSpace(out)
  292. c.Assert(waitRun(id), checker.IsNil)
  293. out, _ = dockerCmd(c, "ps")
  294. c.Assert(out, checker.Contains, "192.168.10.1:5000->5000/tcp")
  295. }
  296. func (s *DockerNetworkSuite) TestDockerNetworkRmPredefined(c *check.C) {
  297. predefined := []string{"bridge", "host", "none", "default"}
  298. for _, net := range predefined {
  299. // predefined networks can't be removed
  300. out, _, err := dockerCmdWithError("network", "rm", net)
  301. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  302. }
  303. }
  304. func (s *DockerNetworkSuite) TestDockerNetworkLsFilter(c *check.C) {
  305. testNet := "testnet1"
  306. testLabel := "foo"
  307. testValue := "bar"
  308. out, _ := dockerCmd(c, "network", "create", "dev")
  309. defer func() {
  310. dockerCmd(c, "network", "rm", "dev")
  311. dockerCmd(c, "network", "rm", testNet)
  312. }()
  313. networkID := strings.TrimSpace(out)
  314. // filter with partial ID
  315. // only show 'dev' network
  316. out, _ = dockerCmd(c, "network", "ls", "-f", "id="+networkID[0:5])
  317. assertNwList(c, out, []string{"dev"})
  318. out, _ = dockerCmd(c, "network", "ls", "-f", "name=dge")
  319. assertNwList(c, out, []string{"bridge"})
  320. // only show built-in network (bridge, none, host)
  321. out, _ = dockerCmd(c, "network", "ls", "-f", "type=builtin")
  322. assertNwList(c, out, []string{"bridge", "host", "none"})
  323. // only show custom networks (dev)
  324. out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom")
  325. assertNwList(c, out, []string{"dev"})
  326. // show all networks with filter
  327. // it should be equivalent of ls without option
  328. out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom", "-f", "type=builtin")
  329. assertNwList(c, out, []string{"bridge", "dev", "host", "none"})
  330. out, _ = dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet)
  331. assertNwIsAvailable(c, testNet)
  332. out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel)
  333. assertNwList(c, out, []string{testNet})
  334. out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel+"="+testValue)
  335. assertNwList(c, out, []string{testNet})
  336. out, _ = dockerCmd(c, "network", "ls", "-f", "label=nonexistent")
  337. outArr := strings.Split(strings.TrimSpace(out), "\n")
  338. c.Assert(len(outArr), check.Equals, 1, check.Commentf("%s\n", out))
  339. out, _ = dockerCmd(c, "network", "ls", "-f", "driver=null")
  340. assertNwList(c, out, []string{"none"})
  341. out, _ = dockerCmd(c, "network", "ls", "-f", "driver=host")
  342. assertNwList(c, out, []string{"host"})
  343. out, _ = dockerCmd(c, "network", "ls", "-f", "driver=bridge")
  344. assertNwList(c, out, []string{"bridge", "dev", testNet})
  345. }
  346. func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *check.C) {
  347. dockerCmd(c, "network", "create", "test")
  348. assertNwIsAvailable(c, "test")
  349. dockerCmd(c, "network", "rm", "test")
  350. assertNwNotAvailable(c, "test")
  351. }
  352. func (s *DockerNetworkSuite) TestDockerNetworkCreateLabel(c *check.C) {
  353. testNet := "testnetcreatelabel"
  354. testLabel := "foo"
  355. testValue := "bar"
  356. dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet)
  357. assertNwIsAvailable(c, testNet)
  358. out, _, err := dockerCmdWithError("network", "inspect", "--format={{ .Labels."+testLabel+" }}", testNet)
  359. c.Assert(err, check.IsNil)
  360. c.Assert(strings.TrimSpace(out), check.Equals, testValue)
  361. dockerCmd(c, "network", "rm", testNet)
  362. assertNwNotAvailable(c, testNet)
  363. }
  364. func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *check.C) {
  365. out, _, err := dockerCmdWithError("network", "rm", "test")
  366. c.Assert(err, checker.NotNil, check.Commentf("%v", out))
  367. }
  368. func (s *DockerSuite) TestDockerNetworkDeleteMultiple(c *check.C) {
  369. dockerCmd(c, "network", "create", "testDelMulti0")
  370. assertNwIsAvailable(c, "testDelMulti0")
  371. dockerCmd(c, "network", "create", "testDelMulti1")
  372. assertNwIsAvailable(c, "testDelMulti1")
  373. dockerCmd(c, "network", "create", "testDelMulti2")
  374. assertNwIsAvailable(c, "testDelMulti2")
  375. out, _ := dockerCmd(c, "run", "-d", "--net", "testDelMulti2", "busybox", "top")
  376. containerID := strings.TrimSpace(out)
  377. waitRun(containerID)
  378. // delete three networks at the same time, since testDelMulti2
  379. // contains active container, its deletion should fail.
  380. out, _, err := dockerCmdWithError("network", "rm", "testDelMulti0", "testDelMulti1", "testDelMulti2")
  381. // err should not be nil due to deleting testDelMulti2 failed.
  382. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  383. // testDelMulti2 should fail due to network has active endpoints
  384. c.Assert(out, checker.Contains, "has active endpoints")
  385. assertNwNotAvailable(c, "testDelMulti0")
  386. assertNwNotAvailable(c, "testDelMulti1")
  387. // testDelMulti2 can't be deleted, so it should exist
  388. assertNwIsAvailable(c, "testDelMulti2")
  389. }
  390. func (s *DockerSuite) TestDockerNetworkInspect(c *check.C) {
  391. out, _ := dockerCmd(c, "network", "inspect", "host")
  392. networkResources := []types.NetworkResource{}
  393. err := json.Unmarshal([]byte(out), &networkResources)
  394. c.Assert(err, check.IsNil)
  395. c.Assert(networkResources, checker.HasLen, 1)
  396. out, _ = dockerCmd(c, "network", "inspect", "--format={{ .Name }}", "host")
  397. c.Assert(strings.TrimSpace(out), check.Equals, "host")
  398. }
  399. func (s *DockerSuite) TestDockerNetworkInspectWithID(c *check.C) {
  400. out, _ := dockerCmd(c, "network", "create", "test2")
  401. networkID := strings.TrimSpace(out)
  402. assertNwIsAvailable(c, "test2")
  403. out, _ = dockerCmd(c, "network", "inspect", "--format={{ .Id }}", "test2")
  404. c.Assert(strings.TrimSpace(out), check.Equals, networkID)
  405. out, _ = dockerCmd(c, "network", "inspect", "--format={{ .ID }}", "test2")
  406. c.Assert(strings.TrimSpace(out), check.Equals, networkID)
  407. }
  408. func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) {
  409. result := dockerCmdWithResult("network", "inspect", "host", "none")
  410. result.Assert(c, icmd.Success)
  411. networkResources := []types.NetworkResource{}
  412. err := json.Unmarshal([]byte(result.Stdout()), &networkResources)
  413. c.Assert(err, check.IsNil)
  414. c.Assert(networkResources, checker.HasLen, 2)
  415. }
  416. func (s *DockerSuite) TestDockerInspectMultipleNetworksIncludingNonexistent(c *check.C) {
  417. // non-existent network was not at the beginning of the inspect list
  418. // This should print an error, return an exitCode 1 and print the host network
  419. result := dockerCmdWithResult("network", "inspect", "host", "nonexistent")
  420. result.Assert(c, icmd.Expected{
  421. ExitCode: 1,
  422. Err: "Error: No such network: nonexistent",
  423. Out: "host",
  424. })
  425. networkResources := []types.NetworkResource{}
  426. err := json.Unmarshal([]byte(result.Stdout()), &networkResources)
  427. c.Assert(err, check.IsNil)
  428. c.Assert(networkResources, checker.HasLen, 1)
  429. // Only one non-existent network to inspect
  430. // Should print an error and return an exitCode, nothing else
  431. result = dockerCmdWithResult("network", "inspect", "nonexistent")
  432. result.Assert(c, icmd.Expected{
  433. ExitCode: 1,
  434. Err: "Error: No such network: nonexistent",
  435. Out: "[]",
  436. })
  437. // non-existent network was at the beginning of the inspect list
  438. // Should not fail fast, and still print host network but print an error
  439. result = dockerCmdWithResult("network", "inspect", "nonexistent", "host")
  440. result.Assert(c, icmd.Expected{
  441. ExitCode: 1,
  442. Err: "Error: No such network: nonexistent",
  443. Out: "host",
  444. })
  445. networkResources = []types.NetworkResource{}
  446. err = json.Unmarshal([]byte(result.Stdout()), &networkResources)
  447. c.Assert(err, check.IsNil)
  448. c.Assert(networkResources, checker.HasLen, 1)
  449. }
  450. func (s *DockerSuite) TestDockerInspectNetworkWithContainerName(c *check.C) {
  451. dockerCmd(c, "network", "create", "brNetForInspect")
  452. assertNwIsAvailable(c, "brNetForInspect")
  453. defer func() {
  454. dockerCmd(c, "network", "rm", "brNetForInspect")
  455. assertNwNotAvailable(c, "brNetForInspect")
  456. }()
  457. out, _ := dockerCmd(c, "run", "-d", "--name", "testNetInspect1", "--net", "brNetForInspect", "busybox", "top")
  458. c.Assert(waitRun("testNetInspect1"), check.IsNil)
  459. containerID := strings.TrimSpace(out)
  460. defer func() {
  461. // we don't stop container by name, because we'll rename it later
  462. dockerCmd(c, "stop", containerID)
  463. }()
  464. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  465. networkResources := []types.NetworkResource{}
  466. err := json.Unmarshal([]byte(out), &networkResources)
  467. c.Assert(err, check.IsNil)
  468. c.Assert(networkResources, checker.HasLen, 1)
  469. container, ok := networkResources[0].Containers[containerID]
  470. c.Assert(ok, checker.True)
  471. c.Assert(container.Name, checker.Equals, "testNetInspect1")
  472. // rename container and check docker inspect output update
  473. newName := "HappyNewName"
  474. dockerCmd(c, "rename", "testNetInspect1", newName)
  475. // check whether network inspect works properly
  476. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  477. newNetRes := []types.NetworkResource{}
  478. err = json.Unmarshal([]byte(out), &newNetRes)
  479. c.Assert(err, check.IsNil)
  480. c.Assert(newNetRes, checker.HasLen, 1)
  481. container1, ok := newNetRes[0].Containers[containerID]
  482. c.Assert(ok, checker.True)
  483. c.Assert(container1.Name, checker.Equals, newName)
  484. }
  485. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) {
  486. dockerCmd(c, "network", "create", "test")
  487. assertNwIsAvailable(c, "test")
  488. nr := getNwResource(c, "test")
  489. c.Assert(nr.Name, checker.Equals, "test")
  490. c.Assert(len(nr.Containers), checker.Equals, 0)
  491. // run a container
  492. out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  493. c.Assert(waitRun("test"), check.IsNil)
  494. containerID := strings.TrimSpace(out)
  495. // connect the container to the test network
  496. dockerCmd(c, "network", "connect", "test", containerID)
  497. // inspect the network to make sure container is connected
  498. nr = getNetworkResource(c, nr.ID)
  499. c.Assert(len(nr.Containers), checker.Equals, 1)
  500. c.Assert(nr.Containers[containerID], check.NotNil)
  501. // check if container IP matches network inspect
  502. ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address)
  503. c.Assert(err, check.IsNil)
  504. containerIP := findContainerIP(c, "test", "test")
  505. c.Assert(ip.String(), checker.Equals, containerIP)
  506. // disconnect container from the network
  507. dockerCmd(c, "network", "disconnect", "test", containerID)
  508. nr = getNwResource(c, "test")
  509. c.Assert(nr.Name, checker.Equals, "test")
  510. c.Assert(len(nr.Containers), checker.Equals, 0)
  511. // run another container
  512. out, _ = dockerCmd(c, "run", "-d", "--net", "test", "--name", "test2", "busybox", "top")
  513. c.Assert(waitRun("test2"), check.IsNil)
  514. containerID = strings.TrimSpace(out)
  515. nr = getNwResource(c, "test")
  516. c.Assert(nr.Name, checker.Equals, "test")
  517. c.Assert(len(nr.Containers), checker.Equals, 1)
  518. // force disconnect the container to the test network
  519. dockerCmd(c, "network", "disconnect", "-f", "test", containerID)
  520. nr = getNwResource(c, "test")
  521. c.Assert(nr.Name, checker.Equals, "test")
  522. c.Assert(len(nr.Containers), checker.Equals, 0)
  523. dockerCmd(c, "network", "rm", "test")
  524. assertNwNotAvailable(c, "test")
  525. }
  526. func (s *DockerNetworkSuite) TestDockerNetworkIPAMMultipleNetworks(c *check.C) {
  527. // test0 bridge network
  528. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
  529. assertNwIsAvailable(c, "test1")
  530. // test2 bridge network does not overlap
  531. dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
  532. assertNwIsAvailable(c, "test2")
  533. // for networks w/o ipam specified, docker will choose proper non-overlapping subnets
  534. dockerCmd(c, "network", "create", "test3")
  535. assertNwIsAvailable(c, "test3")
  536. dockerCmd(c, "network", "create", "test4")
  537. assertNwIsAvailable(c, "test4")
  538. dockerCmd(c, "network", "create", "test5")
  539. assertNwIsAvailable(c, "test5")
  540. // test network with multiple subnets
  541. // bridge network doesn't support multiple subnets. hence, use a dummy driver that supports
  542. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6")
  543. assertNwIsAvailable(c, "test6")
  544. // test network with multiple subnets with valid ipam combinations
  545. // also check same subnet across networks when the driver supports it.
  546. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
  547. "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16",
  548. "--gateway=192.168.0.100", "--gateway=192.170.0.100",
  549. "--ip-range=192.168.1.0/24",
  550. "--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6",
  551. "--aux-address", "c=192.170.1.5", "--aux-address", "d=192.170.1.6",
  552. "test7")
  553. assertNwIsAvailable(c, "test7")
  554. // cleanup
  555. for i := 1; i < 8; i++ {
  556. dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
  557. }
  558. }
  559. func (s *DockerNetworkSuite) TestDockerNetworkCustomIPAM(c *check.C) {
  560. // Create a bridge network using custom ipam driver
  561. dockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "br0")
  562. assertNwIsAvailable(c, "br0")
  563. // Verify expected network ipam fields are there
  564. nr := getNetworkResource(c, "br0")
  565. c.Assert(nr.Driver, checker.Equals, "bridge")
  566. c.Assert(nr.IPAM.Driver, checker.Equals, dummyIPAMDriver)
  567. // remove network and exercise remote ipam driver
  568. dockerCmd(c, "network", "rm", "br0")
  569. assertNwNotAvailable(c, "br0")
  570. }
  571. func (s *DockerNetworkSuite) TestDockerNetworkIPAMOptions(c *check.C) {
  572. // Create a bridge network using custom ipam driver and options
  573. dockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "--ipam-opt", "opt1=drv1", "--ipam-opt", "opt2=drv2", "br0")
  574. assertNwIsAvailable(c, "br0")
  575. // Verify expected network ipam options
  576. nr := getNetworkResource(c, "br0")
  577. opts := nr.IPAM.Options
  578. c.Assert(opts["opt1"], checker.Equals, "drv1")
  579. c.Assert(opts["opt2"], checker.Equals, "drv2")
  580. }
  581. func (s *DockerNetworkSuite) TestDockerNetworkNullIPAMDriver(c *check.C) {
  582. // Create a network with null ipam driver
  583. _, _, err := dockerCmdWithError("network", "create", "-d", dummyNetworkDriver, "--ipam-driver", "null", "test000")
  584. c.Assert(err, check.IsNil)
  585. assertNwIsAvailable(c, "test000")
  586. // Verify the inspect data contains the default subnet provided by the null
  587. // ipam driver and no gateway, as the null ipam driver does not provide one
  588. nr := getNetworkResource(c, "test000")
  589. c.Assert(nr.IPAM.Driver, checker.Equals, "null")
  590. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  591. c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "0.0.0.0/0")
  592. c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "")
  593. }
  594. func (s *DockerNetworkSuite) TestDockerNetworkInspectDefault(c *check.C) {
  595. nr := getNetworkResource(c, "none")
  596. c.Assert(nr.Driver, checker.Equals, "null")
  597. c.Assert(nr.Scope, checker.Equals, "local")
  598. c.Assert(nr.Internal, checker.Equals, false)
  599. c.Assert(nr.EnableIPv6, checker.Equals, false)
  600. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  601. c.Assert(len(nr.IPAM.Config), checker.Equals, 0)
  602. nr = getNetworkResource(c, "host")
  603. c.Assert(nr.Driver, checker.Equals, "host")
  604. c.Assert(nr.Scope, checker.Equals, "local")
  605. c.Assert(nr.Internal, checker.Equals, false)
  606. c.Assert(nr.EnableIPv6, checker.Equals, false)
  607. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  608. c.Assert(len(nr.IPAM.Config), checker.Equals, 0)
  609. nr = getNetworkResource(c, "bridge")
  610. c.Assert(nr.Driver, checker.Equals, "bridge")
  611. c.Assert(nr.Scope, checker.Equals, "local")
  612. c.Assert(nr.Internal, checker.Equals, false)
  613. c.Assert(nr.EnableIPv6, checker.Equals, false)
  614. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  615. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  616. c.Assert(nr.IPAM.Config[0].Subnet, checker.NotNil)
  617. c.Assert(nr.IPAM.Config[0].Gateway, checker.NotNil)
  618. }
  619. func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomUnspecified(c *check.C) {
  620. // if unspecified, network subnet will be selected from inside preferred pool
  621. dockerCmd(c, "network", "create", "test01")
  622. assertNwIsAvailable(c, "test01")
  623. nr := getNetworkResource(c, "test01")
  624. c.Assert(nr.Driver, checker.Equals, "bridge")
  625. c.Assert(nr.Scope, checker.Equals, "local")
  626. c.Assert(nr.Internal, checker.Equals, false)
  627. c.Assert(nr.EnableIPv6, checker.Equals, false)
  628. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  629. c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
  630. c.Assert(nr.IPAM.Config[0].Subnet, checker.NotNil)
  631. c.Assert(nr.IPAM.Config[0].Gateway, checker.NotNil)
  632. dockerCmd(c, "network", "rm", "test01")
  633. assertNwNotAvailable(c, "test01")
  634. }
  635. func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomSpecified(c *check.C) {
  636. dockerCmd(c, "network", "create", "--driver=bridge", "--ipv6", "--subnet=fd80:24e2:f998:72d6::/64", "--subnet=172.28.0.0/16", "--ip-range=172.28.5.0/24", "--gateway=172.28.5.254", "br0")
  637. assertNwIsAvailable(c, "br0")
  638. nr := getNetworkResource(c, "br0")
  639. c.Assert(nr.Driver, checker.Equals, "bridge")
  640. c.Assert(nr.Scope, checker.Equals, "local")
  641. c.Assert(nr.Internal, checker.Equals, false)
  642. c.Assert(nr.EnableIPv6, checker.Equals, true)
  643. c.Assert(nr.IPAM.Driver, checker.Equals, "default")
  644. c.Assert(len(nr.IPAM.Config), checker.Equals, 2)
  645. c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16")
  646. c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24")
  647. c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254")
  648. c.Assert(nr.Internal, checker.False)
  649. dockerCmd(c, "network", "rm", "br0")
  650. assertNwNotAvailable(c, "test01")
  651. }
  652. func (s *DockerNetworkSuite) TestDockerNetworkIPAMInvalidCombinations(c *check.C) {
  653. // network with ip-range out of subnet range
  654. _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
  655. c.Assert(err, check.NotNil)
  656. // network with multiple gateways for a single subnet
  657. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
  658. c.Assert(err, check.NotNil)
  659. // Multiple overlapping subnets in the same network must fail
  660. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
  661. c.Assert(err, check.NotNil)
  662. // overlapping subnets across networks must fail
  663. // create a valid test0 network
  664. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
  665. assertNwIsAvailable(c, "test0")
  666. // create an overlapping test1 network
  667. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
  668. c.Assert(err, check.NotNil)
  669. dockerCmd(c, "network", "rm", "test0")
  670. assertNwNotAvailable(c, "test0")
  671. }
  672. func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) {
  673. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
  674. assertNwIsAvailable(c, "testopt")
  675. gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
  676. c.Assert(gopts, checker.NotNil)
  677. opts, ok := gopts.(map[string]interface{})
  678. c.Assert(ok, checker.Equals, true)
  679. c.Assert(opts["opt1"], checker.Equals, "drv1")
  680. c.Assert(opts["opt2"], checker.Equals, "drv2")
  681. dockerCmd(c, "network", "rm", "testopt")
  682. assertNwNotAvailable(c, "testopt")
  683. }
  684. func (s *DockerNetworkSuite) TestDockerPluginV2NetworkDriver(c *check.C) {
  685. testRequires(c, DaemonIsLinux, IsAmd64, Network)
  686. var (
  687. npName = "tiborvass/test-docker-netplugin"
  688. npTag = "latest"
  689. npNameWithTag = npName + ":" + npTag
  690. )
  691. _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", npNameWithTag)
  692. c.Assert(err, checker.IsNil)
  693. out, _, err := dockerCmdWithError("plugin", "ls")
  694. c.Assert(err, checker.IsNil)
  695. c.Assert(out, checker.Contains, npName)
  696. c.Assert(out, checker.Contains, npTag)
  697. c.Assert(out, checker.Contains, "true")
  698. dockerCmd(c, "network", "create", "-d", npNameWithTag, "v2net")
  699. assertNwIsAvailable(c, "v2net")
  700. dockerCmd(c, "network", "rm", "v2net")
  701. assertNwNotAvailable(c, "v2net")
  702. }
  703. func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *check.C) {
  704. testRequires(c, ExecSupport)
  705. // On default bridge network built-in service discovery should not happen
  706. hostsFile := "/etc/hosts"
  707. bridgeName := "external-bridge"
  708. bridgeIP := "192.169.255.254/24"
  709. createInterface(c, "bridge", bridgeName, bridgeIP)
  710. defer deleteInterface(c, bridgeName)
  711. s.d.StartWithBusybox(c, "--bridge", bridgeName)
  712. defer s.d.Restart(c)
  713. // run two containers and store first container's etc/hosts content
  714. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  715. c.Assert(err, check.IsNil)
  716. cid1 := strings.TrimSpace(out)
  717. defer s.d.Cmd("stop", cid1)
  718. hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  719. c.Assert(err, checker.IsNil)
  720. out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top")
  721. c.Assert(err, check.IsNil)
  722. cid2 := strings.TrimSpace(out)
  723. // verify first container's etc/hosts file has not changed after spawning the second named container
  724. hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  725. c.Assert(err, checker.IsNil)
  726. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  727. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  728. // stop container 2 and verify first container's etc/hosts has not changed
  729. _, err = s.d.Cmd("stop", cid2)
  730. c.Assert(err, check.IsNil)
  731. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  732. c.Assert(err, checker.IsNil)
  733. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  734. check.Commentf("Unexpected %s change on second container creation", hostsFile))
  735. // but discovery is on when connecting to non default bridge network
  736. network := "anotherbridge"
  737. out, err = s.d.Cmd("network", "create", network)
  738. c.Assert(err, check.IsNil, check.Commentf(out))
  739. defer s.d.Cmd("network", "rm", network)
  740. out, err = s.d.Cmd("network", "connect", network, cid1)
  741. c.Assert(err, check.IsNil, check.Commentf(out))
  742. hosts, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  743. c.Assert(err, checker.IsNil)
  744. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  745. c.Assert(err, checker.IsNil)
  746. c.Assert(string(hosts), checker.Equals, string(hostsPost),
  747. check.Commentf("Unexpected %s change on second network connection", hostsFile))
  748. }
  749. func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
  750. testRequires(c, ExecSupport, NotArm)
  751. hostsFile := "/etc/hosts"
  752. cstmBridgeNw := "custom-bridge-nw"
  753. cstmBridgeNw1 := "custom-bridge-nw1"
  754. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw)
  755. assertNwIsAvailable(c, cstmBridgeNw)
  756. // run two anonymous containers and store their etc/hosts content
  757. out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  758. cid1 := strings.TrimSpace(out)
  759. hosts1 := readContainerFileWithExec(c, cid1, hostsFile)
  760. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  761. cid2 := strings.TrimSpace(out)
  762. hosts2 := readContainerFileWithExec(c, cid2, hostsFile)
  763. // verify first container etc/hosts file has not changed
  764. hosts1post := readContainerFileWithExec(c, cid1, hostsFile)
  765. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  766. check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
  767. // Connect the 2nd container to a new network and verify the
  768. // first container /etc/hosts file still hasn't changed.
  769. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1)
  770. assertNwIsAvailable(c, cstmBridgeNw1)
  771. dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2)
  772. hosts2 = readContainerFileWithExec(c, cid2, hostsFile)
  773. hosts1post = readContainerFileWithExec(c, cid1, hostsFile)
  774. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  775. check.Commentf("Unexpected %s change on container connect", hostsFile))
  776. // start a named container
  777. cName := "AnyName"
  778. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top")
  779. cid3 := strings.TrimSpace(out)
  780. // verify that container 1 and 2 can ping the named container
  781. dockerCmd(c, "exec", cid1, "ping", "-c", "1", cName)
  782. dockerCmd(c, "exec", cid2, "ping", "-c", "1", cName)
  783. // Stop named container and verify first two containers' etc/hosts file hasn't changed
  784. dockerCmd(c, "stop", cid3)
  785. hosts1post = readContainerFileWithExec(c, cid1, hostsFile)
  786. c.Assert(string(hosts1), checker.Equals, string(hosts1post),
  787. check.Commentf("Unexpected %s change on name container creation", hostsFile))
  788. hosts2post := readContainerFileWithExec(c, cid2, hostsFile)
  789. c.Assert(string(hosts2), checker.Equals, string(hosts2post),
  790. check.Commentf("Unexpected %s change on name container creation", hostsFile))
  791. // verify that container 1 and 2 can't ping the named container now
  792. _, _, err := dockerCmdWithError("exec", cid1, "ping", "-c", "1", cName)
  793. c.Assert(err, check.NotNil)
  794. _, _, err = dockerCmdWithError("exec", cid2, "ping", "-c", "1", cName)
  795. c.Assert(err, check.NotNil)
  796. }
  797. func (s *DockerNetworkSuite) TestDockerNetworkLinkOnDefaultNetworkOnly(c *check.C) {
  798. // Legacy Link feature must work only on default network, and not across networks
  799. cnt1 := "container1"
  800. cnt2 := "container2"
  801. network := "anotherbridge"
  802. // Run first container on default network
  803. dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top")
  804. // Create another network and run the second container on it
  805. dockerCmd(c, "network", "create", network)
  806. assertNwIsAvailable(c, network)
  807. dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top")
  808. // Try launching a container on default network, linking to the first container. Must succeed
  809. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top")
  810. // Try launching a container on default network, linking to the second container. Must fail
  811. _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  812. c.Assert(err, checker.NotNil)
  813. // Connect second container to default network. Now a container on default network can link to it
  814. dockerCmd(c, "network", "connect", "bridge", cnt2)
  815. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  816. }
  817. func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) {
  818. // Verify exposed ports are present in ps output when running a container on
  819. // a network managed by a driver which does not provide the default gateway
  820. // for the container
  821. nwn := "ov"
  822. ctn := "bb"
  823. port1 := 80
  824. port2 := 443
  825. expose1 := fmt.Sprintf("--expose=%d", port1)
  826. expose2 := fmt.Sprintf("--expose=%d", port2)
  827. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  828. assertNwIsAvailable(c, nwn)
  829. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top")
  830. // Check docker ps o/p for last created container reports the unpublished ports
  831. unpPort1 := fmt.Sprintf("%d/tcp", port1)
  832. unpPort2 := fmt.Sprintf("%d/tcp", port2)
  833. out, _ := dockerCmd(c, "ps", "-n=1")
  834. // Missing unpublished ports in docker ps output
  835. c.Assert(out, checker.Contains, unpPort1)
  836. // Missing unpublished ports in docker ps output
  837. c.Assert(out, checker.Contains, unpPort2)
  838. }
  839. func (s *DockerNetworkSuite) TestDockerNetworkDriverUngracefulRestart(c *check.C) {
  840. testRequires(c, DaemonIsLinux, NotUserNamespace)
  841. dnd := "dnd"
  842. did := "did"
  843. mux := http.NewServeMux()
  844. server := httptest.NewServer(mux)
  845. setupRemoteNetworkDrivers(c, mux, server.URL, dnd, did)
  846. s.d.StartWithBusybox(c)
  847. _, err := s.d.Cmd("network", "create", "-d", dnd, "--subnet", "1.1.1.0/24", "net1")
  848. c.Assert(err, checker.IsNil)
  849. _, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "foo", "--ip", "1.1.1.10", "busybox", "sh")
  850. c.Assert(err, checker.IsNil)
  851. // Kill daemon and restart
  852. c.Assert(s.d.Kill(), checker.IsNil)
  853. server.Close()
  854. startTime := time.Now().Unix()
  855. s.d.Restart(c)
  856. lapse := time.Now().Unix() - startTime
  857. if lapse > 60 {
  858. // In normal scenarios, daemon restart takes ~1 second.
  859. // Plugin retry mechanism can delay the daemon start. systemd may not like it.
  860. // Avoid accessing plugins during daemon bootup
  861. c.Logf("daemon restart took too long : %d seconds", lapse)
  862. }
  863. // Restart the custom dummy plugin
  864. mux = http.NewServeMux()
  865. server = httptest.NewServer(mux)
  866. setupRemoteNetworkDrivers(c, mux, server.URL, dnd, did)
  867. // trying to reuse the same ip must succeed
  868. _, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "bar", "--ip", "1.1.1.10", "busybox", "sh")
  869. c.Assert(err, checker.IsNil)
  870. }
  871. func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) {
  872. // Verify endpoint MAC address is correctly populated in container's network settings
  873. nwn := "ov"
  874. ctn := "bb"
  875. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  876. assertNwIsAvailable(c, nwn)
  877. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top")
  878. mac := inspectField(c, ctn, "NetworkSettings.Networks."+nwn+".MacAddress")
  879. c.Assert(mac, checker.Equals, "a0:b1:c2:d3:e4:f5")
  880. }
  881. func (s *DockerSuite) TestInspectAPIMultipleNetworks(c *check.C) {
  882. dockerCmd(c, "network", "create", "mybridge1")
  883. dockerCmd(c, "network", "create", "mybridge2")
  884. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  885. id := strings.TrimSpace(out)
  886. c.Assert(waitRun(id), check.IsNil)
  887. dockerCmd(c, "network", "connect", "mybridge1", id)
  888. dockerCmd(c, "network", "connect", "mybridge2", id)
  889. body := getInspectBody(c, "v1.20", id)
  890. var inspect120 v1p20.ContainerJSON
  891. err := json.Unmarshal(body, &inspect120)
  892. c.Assert(err, checker.IsNil)
  893. versionedIP := inspect120.NetworkSettings.IPAddress
  894. body = getInspectBody(c, "v1.21", id)
  895. var inspect121 types.ContainerJSON
  896. err = json.Unmarshal(body, &inspect121)
  897. c.Assert(err, checker.IsNil)
  898. c.Assert(inspect121.NetworkSettings.Networks, checker.HasLen, 3)
  899. bridge := inspect121.NetworkSettings.Networks["bridge"]
  900. c.Assert(bridge.IPAddress, checker.Equals, versionedIP)
  901. c.Assert(bridge.IPAddress, checker.Equals, inspect121.NetworkSettings.IPAddress)
  902. }
  903. func connectContainerToNetworks(c *check.C, d *daemon.Daemon, cName string, nws []string) {
  904. // Run a container on the default network
  905. out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
  906. c.Assert(err, checker.IsNil, check.Commentf(out))
  907. // Attach the container to other networks
  908. for _, nw := range nws {
  909. out, err = d.Cmd("network", "create", nw)
  910. c.Assert(err, checker.IsNil, check.Commentf(out))
  911. out, err = d.Cmd("network", "connect", nw, cName)
  912. c.Assert(err, checker.IsNil, check.Commentf(out))
  913. }
  914. }
  915. func verifyContainerIsConnectedToNetworks(c *check.C, d *daemon.Daemon, cName string, nws []string) {
  916. // Verify container is connected to all the networks
  917. for _, nw := range nws {
  918. out, err := d.Cmd("inspect", "-f", fmt.Sprintf("{{.NetworkSettings.Networks.%s}}", nw), cName)
  919. c.Assert(err, checker.IsNil, check.Commentf(out))
  920. c.Assert(out, checker.Not(checker.Equals), "<no value>\n")
  921. }
  922. }
  923. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRestart(c *check.C) {
  924. cName := "bb"
  925. nwList := []string{"nw1", "nw2", "nw3"}
  926. s.d.StartWithBusybox(c)
  927. connectContainerToNetworks(c, s.d, cName, nwList)
  928. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  929. // Reload daemon
  930. s.d.Restart(c)
  931. _, err := s.d.Cmd("start", cName)
  932. c.Assert(err, checker.IsNil)
  933. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  934. }
  935. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksUngracefulDaemonRestart(c *check.C) {
  936. cName := "cc"
  937. nwList := []string{"nw1", "nw2", "nw3"}
  938. s.d.StartWithBusybox(c)
  939. connectContainerToNetworks(c, s.d, cName, nwList)
  940. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  941. // Kill daemon and restart
  942. c.Assert(s.d.Kill(), checker.IsNil)
  943. s.d.Restart(c)
  944. // Restart container
  945. _, err := s.d.Cmd("start", cName)
  946. c.Assert(err, checker.IsNil)
  947. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  948. }
  949. func (s *DockerNetworkSuite) TestDockerNetworkRunNetByID(c *check.C) {
  950. out, _ := dockerCmd(c, "network", "create", "one")
  951. containerOut, _, err := dockerCmdWithError("run", "-d", "--net", strings.TrimSpace(out), "busybox", "top")
  952. c.Assert(err, checker.IsNil, check.Commentf(containerOut))
  953. }
  954. func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c *check.C) {
  955. testRequires(c, DaemonIsLinux, NotUserNamespace)
  956. s.d.StartWithBusybox(c)
  957. // Run a few containers on host network
  958. for i := 0; i < 10; i++ {
  959. cName := fmt.Sprintf("hostc-%d", i)
  960. out, err := s.d.Cmd("run", "-d", "--name", cName, "--net=host", "--restart=always", "busybox", "top")
  961. c.Assert(err, checker.IsNil, check.Commentf(out))
  962. // verify container has finished starting before killing daemon
  963. err = s.d.WaitRun(cName)
  964. c.Assert(err, checker.IsNil)
  965. }
  966. // Kill daemon ungracefully and restart
  967. c.Assert(s.d.Kill(), checker.IsNil)
  968. s.d.Restart(c)
  969. // make sure all the containers are up and running
  970. for i := 0; i < 10; i++ {
  971. err := s.d.WaitRun(fmt.Sprintf("hostc-%d", i))
  972. c.Assert(err, checker.IsNil)
  973. }
  974. }
  975. func (s *DockerNetworkSuite) TestDockerNetworkConnectToHostFromOtherNetwork(c *check.C) {
  976. dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
  977. c.Assert(waitRun("container1"), check.IsNil)
  978. dockerCmd(c, "network", "disconnect", "bridge", "container1")
  979. out, _, err := dockerCmdWithError("network", "connect", "host", "container1")
  980. c.Assert(err, checker.NotNil, check.Commentf(out))
  981. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  982. }
  983. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromHost(c *check.C) {
  984. dockerCmd(c, "run", "-d", "--name", "container1", "--net=host", "busybox", "top")
  985. c.Assert(waitRun("container1"), check.IsNil)
  986. out, _, err := dockerCmdWithError("network", "disconnect", "host", "container1")
  987. c.Assert(err, checker.NotNil, check.Commentf("Should err out disconnect from host"))
  988. c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
  989. }
  990. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithPortMapping(c *check.C) {
  991. testRequires(c, NotArm)
  992. dockerCmd(c, "network", "create", "test1")
  993. dockerCmd(c, "run", "-d", "--name", "c1", "-p", "5000:5000", "busybox", "top")
  994. c.Assert(waitRun("c1"), check.IsNil)
  995. dockerCmd(c, "network", "connect", "test1", "c1")
  996. }
  997. func verifyPortMap(c *check.C, container, port, originalMapping string, mustBeEqual bool) {
  998. chk := checker.Equals
  999. if !mustBeEqual {
  1000. chk = checker.Not(checker.Equals)
  1001. }
  1002. currentMapping, _ := dockerCmd(c, "port", container, port)
  1003. c.Assert(currentMapping, chk, originalMapping)
  1004. }
  1005. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectWithPortMapping(c *check.C) {
  1006. // Connect and disconnect a container with explicit and non-explicit
  1007. // host port mapping to/from networks which do cause and do not cause
  1008. // the container default gateway to change, and verify docker port cmd
  1009. // returns congruent information
  1010. testRequires(c, NotArm)
  1011. cnt := "c1"
  1012. dockerCmd(c, "network", "create", "aaa")
  1013. dockerCmd(c, "network", "create", "ccc")
  1014. dockerCmd(c, "run", "-d", "--name", cnt, "-p", "9000:90", "-p", "70", "busybox", "top")
  1015. c.Assert(waitRun(cnt), check.IsNil)
  1016. curPortMap, _ := dockerCmd(c, "port", cnt, "70")
  1017. curExplPortMap, _ := dockerCmd(c, "port", cnt, "90")
  1018. // Connect to a network which causes the container's default gw switch
  1019. dockerCmd(c, "network", "connect", "aaa", cnt)
  1020. verifyPortMap(c, cnt, "70", curPortMap, false)
  1021. verifyPortMap(c, cnt, "90", curExplPortMap, true)
  1022. // Read current mapping
  1023. curPortMap, _ = dockerCmd(c, "port", cnt, "70")
  1024. // Disconnect from a network which causes the container's default gw switch
  1025. dockerCmd(c, "network", "disconnect", "aaa", cnt)
  1026. verifyPortMap(c, cnt, "70", curPortMap, false)
  1027. verifyPortMap(c, cnt, "90", curExplPortMap, true)
  1028. // Read current mapping
  1029. curPortMap, _ = dockerCmd(c, "port", cnt, "70")
  1030. // Connect to a network which does not cause the container's default gw switch
  1031. dockerCmd(c, "network", "connect", "ccc", cnt)
  1032. verifyPortMap(c, cnt, "70", curPortMap, true)
  1033. verifyPortMap(c, cnt, "90", curExplPortMap, true)
  1034. }
  1035. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithMac(c *check.C) {
  1036. macAddress := "02:42:ac:11:00:02"
  1037. dockerCmd(c, "network", "create", "mynetwork")
  1038. dockerCmd(c, "run", "--name=test", "-d", "--mac-address", macAddress, "busybox", "top")
  1039. c.Assert(waitRun("test"), check.IsNil)
  1040. mac1 := inspectField(c, "test", "NetworkSettings.Networks.bridge.MacAddress")
  1041. c.Assert(strings.TrimSpace(mac1), checker.Equals, macAddress)
  1042. dockerCmd(c, "network", "connect", "mynetwork", "test")
  1043. mac2 := inspectField(c, "test", "NetworkSettings.Networks.mynetwork.MacAddress")
  1044. c.Assert(strings.TrimSpace(mac2), checker.Not(checker.Equals), strings.TrimSpace(mac1))
  1045. }
  1046. func (s *DockerNetworkSuite) TestDockerNetworkInspectCreatedContainer(c *check.C) {
  1047. dockerCmd(c, "create", "--name", "test", "busybox")
  1048. networks := inspectField(c, "test", "NetworkSettings.Networks")
  1049. c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should return 'bridge' network"))
  1050. }
  1051. func (s *DockerNetworkSuite) TestDockerNetworkRestartWithMultipleNetworks(c *check.C) {
  1052. dockerCmd(c, "network", "create", "test")
  1053. dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
  1054. c.Assert(waitRun("foo"), checker.IsNil)
  1055. dockerCmd(c, "network", "connect", "test", "foo")
  1056. dockerCmd(c, "restart", "foo")
  1057. networks := inspectField(c, "foo", "NetworkSettings.Networks")
  1058. c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should contain 'bridge' network"))
  1059. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  1060. }
  1061. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectToStoppedContainer(c *check.C) {
  1062. dockerCmd(c, "network", "create", "test")
  1063. dockerCmd(c, "create", "--name=foo", "busybox", "top")
  1064. dockerCmd(c, "network", "connect", "test", "foo")
  1065. networks := inspectField(c, "foo", "NetworkSettings.Networks")
  1066. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  1067. // Restart docker daemon to test the config has persisted to disk
  1068. s.d.Restart(c)
  1069. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  1070. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  1071. // start the container and test if we can ping it from another container in the same network
  1072. dockerCmd(c, "start", "foo")
  1073. c.Assert(waitRun("foo"), checker.IsNil)
  1074. ip := inspectField(c, "foo", "NetworkSettings.Networks.test.IPAddress")
  1075. ip = strings.TrimSpace(ip)
  1076. dockerCmd(c, "run", "--net=test", "busybox", "sh", "-c", fmt.Sprintf("ping -c 1 %s", ip))
  1077. dockerCmd(c, "stop", "foo")
  1078. // Test disconnect
  1079. dockerCmd(c, "network", "disconnect", "test", "foo")
  1080. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  1081. c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
  1082. // Restart docker daemon to test the config has persisted to disk
  1083. s.d.Restart(c)
  1084. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  1085. c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
  1086. }
  1087. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectContainerNonexistingNetwork(c *check.C) {
  1088. dockerCmd(c, "network", "create", "test")
  1089. dockerCmd(c, "run", "--net=test", "-d", "--name=foo", "busybox", "top")
  1090. networks := inspectField(c, "foo", "NetworkSettings.Networks")
  1091. c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
  1092. // Stop container and remove network
  1093. dockerCmd(c, "stop", "foo")
  1094. dockerCmd(c, "network", "rm", "test")
  1095. // Test disconnecting stopped container from nonexisting network
  1096. dockerCmd(c, "network", "disconnect", "-f", "test", "foo")
  1097. networks = inspectField(c, "foo", "NetworkSettings.Networks")
  1098. c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
  1099. }
  1100. func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIP(c *check.C) {
  1101. // create two networks
  1102. dockerCmd(c, "network", "create", "--ipv6", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "n0")
  1103. assertNwIsAvailable(c, "n0")
  1104. dockerCmd(c, "network", "create", "--ipv6", "--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")
  1105. assertNwIsAvailable(c, "n1")
  1106. // run a container on first network specifying the ip addresses
  1107. dockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  1108. c.Assert(waitRun("c0"), check.IsNil)
  1109. verifyIPAddressConfig(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  1110. verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  1111. // connect the container to the second network specifying an ip addresses
  1112. dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n1", "c0")
  1113. verifyIPAddressConfig(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  1114. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  1115. // Stop and restart the container
  1116. dockerCmd(c, "stop", "c0")
  1117. dockerCmd(c, "start", "c0")
  1118. // verify requested addresses are applied and configs are still there
  1119. verifyIPAddressConfig(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  1120. verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
  1121. verifyIPAddressConfig(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  1122. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  1123. // Still it should fail to connect to the default network with a specified IP (whatever ip)
  1124. out, _, err := dockerCmdWithError("network", "connect", "--ip", "172.21.55.44", "bridge", "c0")
  1125. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1126. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
  1127. }
  1128. func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIPStoppedContainer(c *check.C) {
  1129. // create a container
  1130. dockerCmd(c, "create", "--name", "c0", "busybox", "top")
  1131. // create a network
  1132. dockerCmd(c, "network", "create", "--ipv6", "--subnet=172.30.0.0/16", "--subnet=2001:db8:abcd::/64", "n0")
  1133. assertNwIsAvailable(c, "n0")
  1134. // connect the container to the network specifying an ip addresses
  1135. dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n0", "c0")
  1136. verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  1137. // start the container, verify config has not changed and ip addresses are assigned
  1138. dockerCmd(c, "start", "c0")
  1139. c.Assert(waitRun("c0"), check.IsNil)
  1140. verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  1141. verifyIPAddresses(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  1142. // stop the container and check ip config has not changed
  1143. dockerCmd(c, "stop", "c0")
  1144. verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
  1145. }
  1146. func (s *DockerNetworkSuite) TestDockerNetworkUnsupportedRequiredIP(c *check.C) {
  1147. // requested IP is not supported on predefined networks
  1148. for _, mode := range []string{"none", "host", "bridge", "default"} {
  1149. checkUnsupportedNetworkAndIP(c, mode)
  1150. }
  1151. // requested IP is not supported on networks with no user defined subnets
  1152. dockerCmd(c, "network", "create", "n0")
  1153. assertNwIsAvailable(c, "n0")
  1154. out, _, err := dockerCmdWithError("run", "-d", "--ip", "172.28.99.88", "--net", "n0", "busybox", "top")
  1155. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1156. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
  1157. out, _, err = dockerCmdWithError("run", "-d", "--ip6", "2001:db8:1234::9988", "--net", "n0", "busybox", "top")
  1158. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1159. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
  1160. dockerCmd(c, "network", "rm", "n0")
  1161. assertNwNotAvailable(c, "n0")
  1162. }
  1163. func checkUnsupportedNetworkAndIP(c *check.C, nwMode string) {
  1164. out, _, err := dockerCmdWithError("run", "-d", "--net", nwMode, "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  1165. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1166. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
  1167. }
  1168. func verifyIPAddressConfig(c *check.C, cName, nwname, ipv4, ipv6 string) {
  1169. if ipv4 != "" {
  1170. out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAMConfig.IPv4Address", nwname))
  1171. c.Assert(strings.TrimSpace(out), check.Equals, ipv4)
  1172. }
  1173. if ipv6 != "" {
  1174. out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAMConfig.IPv6Address", nwname))
  1175. c.Assert(strings.TrimSpace(out), check.Equals, ipv6)
  1176. }
  1177. }
  1178. func verifyIPAddresses(c *check.C, cName, nwname, ipv4, ipv6 string) {
  1179. out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAddress", nwname))
  1180. c.Assert(strings.TrimSpace(out), check.Equals, ipv4)
  1181. out = inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.GlobalIPv6Address", nwname))
  1182. c.Assert(strings.TrimSpace(out), check.Equals, ipv6)
  1183. }
  1184. func (s *DockerNetworkSuite) TestDockerNetworkConnectLinkLocalIP(c *check.C) {
  1185. // create one test network
  1186. dockerCmd(c, "network", "create", "--ipv6", "--subnet=2001:db8:1234::/64", "n0")
  1187. assertNwIsAvailable(c, "n0")
  1188. // run a container with incorrect link-local address
  1189. _, _, err := dockerCmdWithError("run", "--link-local-ip", "169.253.5.5", "busybox", "top")
  1190. c.Assert(err, check.NotNil)
  1191. _, _, err = dockerCmdWithError("run", "--link-local-ip", "2001:db8::89", "busybox", "top")
  1192. c.Assert(err, check.NotNil)
  1193. // run two containers with link-local ip on the test network
  1194. dockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--link-local-ip", "169.254.7.7", "--link-local-ip", "fe80::254:77", "busybox", "top")
  1195. c.Assert(waitRun("c0"), check.IsNil)
  1196. dockerCmd(c, "run", "-d", "--name", "c1", "--net=n0", "--link-local-ip", "169.254.8.8", "--link-local-ip", "fe80::254:88", "busybox", "top")
  1197. c.Assert(waitRun("c1"), check.IsNil)
  1198. // run a container on the default network and connect it to the test network specifying a link-local address
  1199. dockerCmd(c, "run", "-d", "--name", "c2", "busybox", "top")
  1200. c.Assert(waitRun("c2"), check.IsNil)
  1201. dockerCmd(c, "network", "connect", "--link-local-ip", "169.254.9.9", "n0", "c2")
  1202. // verify the three containers can ping each other via the link-local addresses
  1203. _, _, err = dockerCmdWithError("exec", "c0", "ping", "-c", "1", "169.254.8.8")
  1204. c.Assert(err, check.IsNil)
  1205. _, _, err = dockerCmdWithError("exec", "c1", "ping", "-c", "1", "169.254.9.9")
  1206. c.Assert(err, check.IsNil)
  1207. _, _, err = dockerCmdWithError("exec", "c2", "ping", "-c", "1", "169.254.7.7")
  1208. c.Assert(err, check.IsNil)
  1209. // Stop and restart the three containers
  1210. dockerCmd(c, "stop", "c0")
  1211. dockerCmd(c, "stop", "c1")
  1212. dockerCmd(c, "stop", "c2")
  1213. dockerCmd(c, "start", "c0")
  1214. dockerCmd(c, "start", "c1")
  1215. dockerCmd(c, "start", "c2")
  1216. // verify the ping again
  1217. _, _, err = dockerCmdWithError("exec", "c0", "ping", "-c", "1", "169.254.8.8")
  1218. c.Assert(err, check.IsNil)
  1219. _, _, err = dockerCmdWithError("exec", "c1", "ping", "-c", "1", "169.254.9.9")
  1220. c.Assert(err, check.IsNil)
  1221. _, _, err = dockerCmdWithError("exec", "c2", "ping", "-c", "1", "169.254.7.7")
  1222. c.Assert(err, check.IsNil)
  1223. }
  1224. func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectLink(c *check.C) {
  1225. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  1226. dockerCmd(c, "network", "create", "-d", "bridge", "foo1")
  1227. dockerCmd(c, "network", "create", "-d", "bridge", "foo2")
  1228. dockerCmd(c, "run", "-d", "--net=foo1", "--name=first", "busybox", "top")
  1229. c.Assert(waitRun("first"), check.IsNil)
  1230. // run a container in a user-defined network with a link for an existing container
  1231. // and a link for a container that doesn't exist
  1232. dockerCmd(c, "run", "-d", "--net=foo1", "--name=second", "--link=first:FirstInFoo1",
  1233. "--link=third:bar", "busybox", "top")
  1234. c.Assert(waitRun("second"), check.IsNil)
  1235. // ping to first and its alias FirstInFoo1 must succeed
  1236. _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  1237. c.Assert(err, check.IsNil)
  1238. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1")
  1239. c.Assert(err, check.IsNil)
  1240. // connect first container to foo2 network
  1241. dockerCmd(c, "network", "connect", "foo2", "first")
  1242. // connect second container to foo2 network with a different alias for first container
  1243. dockerCmd(c, "network", "connect", "--link=first:FirstInFoo2", "foo2", "second")
  1244. // ping the new alias in network foo2
  1245. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2")
  1246. c.Assert(err, check.IsNil)
  1247. // disconnect first container from foo1 network
  1248. dockerCmd(c, "network", "disconnect", "foo1", "first")
  1249. // link in foo1 network must fail
  1250. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1")
  1251. c.Assert(err, check.NotNil)
  1252. // link in foo2 network must succeed
  1253. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2")
  1254. c.Assert(err, check.IsNil)
  1255. }
  1256. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectDefault(c *check.C) {
  1257. netWorkName1 := "test1"
  1258. netWorkName2 := "test2"
  1259. containerName := "foo"
  1260. dockerCmd(c, "network", "create", netWorkName1)
  1261. dockerCmd(c, "network", "create", netWorkName2)
  1262. dockerCmd(c, "create", "--name", containerName, "busybox", "top")
  1263. dockerCmd(c, "network", "connect", netWorkName1, containerName)
  1264. dockerCmd(c, "network", "connect", netWorkName2, containerName)
  1265. dockerCmd(c, "network", "disconnect", "bridge", containerName)
  1266. dockerCmd(c, "start", containerName)
  1267. c.Assert(waitRun(containerName), checker.IsNil)
  1268. networks := inspectField(c, containerName, "NetworkSettings.Networks")
  1269. c.Assert(networks, checker.Contains, netWorkName1, check.Commentf(fmt.Sprintf("Should contain '%s' network", netWorkName1)))
  1270. c.Assert(networks, checker.Contains, netWorkName2, check.Commentf(fmt.Sprintf("Should contain '%s' network", netWorkName2)))
  1271. c.Assert(networks, checker.Not(checker.Contains), "bridge", check.Commentf("Should not contain 'bridge' network"))
  1272. }
  1273. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithAliasOnDefaultNetworks(c *check.C) {
  1274. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  1275. defaults := []string{"bridge", "host", "none"}
  1276. out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top")
  1277. containerID := strings.TrimSpace(out)
  1278. for _, net := range defaults {
  1279. res, _, err := dockerCmdWithError("network", "connect", "--alias", "alias"+net, net, containerID)
  1280. c.Assert(err, checker.NotNil)
  1281. c.Assert(res, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
  1282. }
  1283. }
  1284. func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectAlias(c *check.C) {
  1285. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  1286. dockerCmd(c, "network", "create", "-d", "bridge", "net1")
  1287. dockerCmd(c, "network", "create", "-d", "bridge", "net2")
  1288. cid, _ := dockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo", "busybox", "top")
  1289. c.Assert(waitRun("first"), check.IsNil)
  1290. dockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox", "top")
  1291. c.Assert(waitRun("second"), check.IsNil)
  1292. // ping first container and its alias
  1293. _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  1294. c.Assert(err, check.IsNil)
  1295. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
  1296. c.Assert(err, check.IsNil)
  1297. // ping first container's short-id alias
  1298. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid))
  1299. c.Assert(err, check.IsNil)
  1300. // connect first container to net2 network
  1301. dockerCmd(c, "network", "connect", "--alias=bar", "net2", "first")
  1302. // connect second container to foo2 network with a different alias for first container
  1303. dockerCmd(c, "network", "connect", "net2", "second")
  1304. // ping the new alias in network foo2
  1305. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
  1306. c.Assert(err, check.IsNil)
  1307. // disconnect first container from net1 network
  1308. dockerCmd(c, "network", "disconnect", "net1", "first")
  1309. // ping to net1 scoped alias "foo" must fail
  1310. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
  1311. c.Assert(err, check.NotNil)
  1312. // ping to net2 scoped alias "bar" must still succeed
  1313. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
  1314. c.Assert(err, check.IsNil)
  1315. // ping to net2 scoped alias short-id must still succeed
  1316. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid))
  1317. c.Assert(err, check.IsNil)
  1318. // verify the alias option is rejected when running on predefined network
  1319. out, _, err := dockerCmdWithError("run", "--rm", "--name=any", "--net-alias=any", "busybox", "top")
  1320. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1321. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
  1322. // verify the alias option is rejected when connecting to predefined network
  1323. out, _, err = dockerCmdWithError("network", "connect", "--alias=any", "bridge", "first")
  1324. c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
  1325. c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
  1326. }
  1327. func (s *DockerSuite) TestUserDefinedNetworkConnectivity(c *check.C) {
  1328. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1329. dockerCmd(c, "network", "create", "-d", "bridge", "br.net1")
  1330. dockerCmd(c, "run", "-d", "--net=br.net1", "--name=c1.net1", "busybox", "top")
  1331. c.Assert(waitRun("c1.net1"), check.IsNil)
  1332. dockerCmd(c, "run", "-d", "--net=br.net1", "--name=c2.net1", "busybox", "top")
  1333. c.Assert(waitRun("c2.net1"), check.IsNil)
  1334. // ping first container by its unqualified name
  1335. _, _, err := dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1")
  1336. c.Assert(err, check.IsNil)
  1337. // ping first container by its qualified name
  1338. _, _, err = dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1.br.net1")
  1339. c.Assert(err, check.IsNil)
  1340. // ping with first qualified name masked by an additional domain. should fail
  1341. _, _, err = dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1.br.net1.google.com")
  1342. c.Assert(err, check.NotNil)
  1343. }
  1344. func (s *DockerSuite) TestEmbeddedDNSInvalidInput(c *check.C) {
  1345. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1346. dockerCmd(c, "network", "create", "-d", "bridge", "nw1")
  1347. // Sending garbage to embedded DNS shouldn't crash the daemon
  1348. dockerCmd(c, "run", "-i", "--net=nw1", "--name=c1", "debian:jessie", "bash", "-c", "echo InvalidQuery > /dev/udp/127.0.0.11/53")
  1349. }
  1350. func (s *DockerSuite) TestDockerNetworkConnectFailsNoInspectChange(c *check.C) {
  1351. dockerCmd(c, "run", "-d", "--name=bb", "busybox", "top")
  1352. c.Assert(waitRun("bb"), check.IsNil)
  1353. ns0 := inspectField(c, "bb", "NetworkSettings.Networks.bridge")
  1354. // A failing redundant network connect should not alter current container's endpoint settings
  1355. _, _, err := dockerCmdWithError("network", "connect", "bridge", "bb")
  1356. c.Assert(err, check.NotNil)
  1357. ns1 := inspectField(c, "bb", "NetworkSettings.Networks.bridge")
  1358. c.Assert(ns1, check.Equals, ns0)
  1359. }
  1360. func (s *DockerSuite) TestDockerNetworkInternalMode(c *check.C) {
  1361. dockerCmd(c, "network", "create", "--driver=bridge", "--internal", "internal")
  1362. assertNwIsAvailable(c, "internal")
  1363. nr := getNetworkResource(c, "internal")
  1364. c.Assert(nr.Internal, checker.True)
  1365. dockerCmd(c, "run", "-d", "--net=internal", "--name=first", "busybox", "top")
  1366. c.Assert(waitRun("first"), check.IsNil)
  1367. dockerCmd(c, "run", "-d", "--net=internal", "--name=second", "busybox", "top")
  1368. c.Assert(waitRun("second"), check.IsNil)
  1369. out, _, err := dockerCmdWithError("exec", "first", "ping", "-W", "4", "-c", "1", "www.google.com")
  1370. c.Assert(err, check.NotNil)
  1371. c.Assert(out, checker.Contains, "ping: bad address")
  1372. _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
  1373. c.Assert(err, check.IsNil)
  1374. }
  1375. // Test for #21401
  1376. func (s *DockerNetworkSuite) TestDockerNetworkCreateDeleteSpecialCharacters(c *check.C) {
  1377. dockerCmd(c, "network", "create", "test@#$")
  1378. assertNwIsAvailable(c, "test@#$")
  1379. dockerCmd(c, "network", "rm", "test@#$")
  1380. assertNwNotAvailable(c, "test@#$")
  1381. dockerCmd(c, "network", "create", "kiwl$%^")
  1382. assertNwIsAvailable(c, "kiwl$%^")
  1383. dockerCmd(c, "network", "rm", "kiwl$%^")
  1384. assertNwNotAvailable(c, "kiwl$%^")
  1385. }
  1386. func (s *DockerDaemonSuite) TestDaemonRestartRestoreBridgeNetwork(t *check.C) {
  1387. testRequires(t, DaemonIsLinux)
  1388. s.d.StartWithBusybox(t, "--live-restore")
  1389. defer s.d.Stop(t)
  1390. oldCon := "old"
  1391. _, err := s.d.Cmd("run", "-d", "--name", oldCon, "-p", "80:80", "busybox", "top")
  1392. if err != nil {
  1393. t.Fatal(err)
  1394. }
  1395. oldContainerIP, err := s.d.Cmd("inspect", "-f", "{{ .NetworkSettings.Networks.bridge.IPAddress }}", oldCon)
  1396. if err != nil {
  1397. t.Fatal(err)
  1398. }
  1399. // Kill the daemon
  1400. if err := s.d.Kill(); err != nil {
  1401. t.Fatal(err)
  1402. }
  1403. // restart the daemon
  1404. s.d.Start(t, "--live-restore")
  1405. // start a new container, the new container's ip should not be the same with
  1406. // old running container.
  1407. newCon := "new"
  1408. _, err = s.d.Cmd("run", "-d", "--name", newCon, "busybox", "top")
  1409. if err != nil {
  1410. t.Fatal(err)
  1411. }
  1412. newContainerIP, err := s.d.Cmd("inspect", "-f", "{{ .NetworkSettings.Networks.bridge.IPAddress }}", newCon)
  1413. if err != nil {
  1414. t.Fatal(err)
  1415. }
  1416. if strings.Compare(strings.TrimSpace(oldContainerIP), strings.TrimSpace(newContainerIP)) == 0 {
  1417. t.Fatalf("new container ip should not equal to old running container ip")
  1418. }
  1419. // start a new container, the new container should ping old running container
  1420. _, err = s.d.Cmd("run", "-t", "busybox", "ping", "-c", "1", oldContainerIP)
  1421. if err != nil {
  1422. t.Fatal(err)
  1423. }
  1424. // start a new container, trying to publish port 80:80 should fail
  1425. out, err := s.d.Cmd("run", "-p", "80:80", "-d", "busybox", "top")
  1426. if err == nil || !strings.Contains(out, "Bind for 0.0.0.0:80 failed: port is already allocated") {
  1427. t.Fatalf("80 port is allocated to old running container, it should failed on allocating to new container")
  1428. }
  1429. // kill old running container and try to allocate again
  1430. _, err = s.d.Cmd("kill", oldCon)
  1431. if err != nil {
  1432. t.Fatal(err)
  1433. }
  1434. id, err := s.d.Cmd("run", "-p", "80:80", "-d", "busybox", "top")
  1435. if err != nil {
  1436. t.Fatal(err)
  1437. }
  1438. // Cleanup because these containers will not be shut down by daemon
  1439. out, err = s.d.Cmd("stop", newCon)
  1440. if err != nil {
  1441. t.Fatalf("err: %v %v", err, string(out))
  1442. }
  1443. _, err = s.d.Cmd("stop", strings.TrimSpace(id))
  1444. if err != nil {
  1445. t.Fatal(err)
  1446. }
  1447. }
  1448. func (s *DockerNetworkSuite) TestDockerNetworkFlagAlias(c *check.C) {
  1449. dockerCmd(c, "network", "create", "user")
  1450. output, status := dockerCmd(c, "run", "--rm", "--network=user", "--network-alias=foo", "busybox", "true")
  1451. c.Assert(status, checker.Equals, 0, check.Commentf("unexpected status code %d (%s)", status, output))
  1452. output, status, _ = dockerCmdWithError("run", "--rm", "--net=user", "--network=user", "busybox", "true")
  1453. c.Assert(status, checker.Equals, 0, check.Commentf("unexpected status code %d (%s)", status, output))
  1454. output, status, _ = dockerCmdWithError("run", "--rm", "--network=user", "--net-alias=foo", "--network-alias=bar", "busybox", "true")
  1455. c.Assert(status, checker.Equals, 0, check.Commentf("unexpected status code %d (%s)", status, output))
  1456. }
  1457. func (s *DockerNetworkSuite) TestDockerNetworkValidateIP(c *check.C) {
  1458. _, _, err := dockerCmdWithError("network", "create", "--ipv6", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "mynet")
  1459. c.Assert(err, check.IsNil)
  1460. assertNwIsAvailable(c, "mynet")
  1461. _, _, err = dockerCmdWithError("run", "-d", "--name", "mynet0", "--net=mynet", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  1462. c.Assert(err, check.IsNil)
  1463. c.Assert(waitRun("mynet0"), check.IsNil)
  1464. verifyIPAddressConfig(c, "mynet0", "mynet", "172.28.99.88", "2001:db8:1234::9988")
  1465. verifyIPAddresses(c, "mynet0", "mynet", "172.28.99.88", "2001:db8:1234::9988")
  1466. _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip", "mynet_ip", "--ip6", "2001:db8:1234::9999", "busybox", "top")
  1467. c.Assert(err.Error(), checker.Contains, "invalid IPv4 address")
  1468. _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip", "172.28.99.99", "--ip6", "mynet_ip6", "busybox", "top")
  1469. c.Assert(err.Error(), checker.Contains, "invalid IPv6 address")
  1470. // This is a case of IPv4 address to `--ip6`
  1471. _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip6", "172.28.99.99", "busybox", "top")
  1472. c.Assert(err.Error(), checker.Contains, "invalid IPv6 address")
  1473. // This is a special case of an IPv4-mapped IPv6 address
  1474. _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip6", "::ffff:172.28.99.99", "busybox", "top")
  1475. c.Assert(err.Error(), checker.Contains, "invalid IPv6 address")
  1476. }
  1477. // Test case for 26220
  1478. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromBridge(c *check.C) {
  1479. out, _ := dockerCmd(c, "network", "inspect", "--format", "{{.Id}}", "bridge")
  1480. network := strings.TrimSpace(out)
  1481. name := "test"
  1482. dockerCmd(c, "create", "--name", name, "busybox", "top")
  1483. _, _, err := dockerCmdWithError("network", "disconnect", network, name)
  1484. c.Assert(err, check.IsNil)
  1485. }
  1486. // TestConntrackFlowsLeak covers the failure scenario of ticket: https://github.com/docker/docker/issues/8795
  1487. // Validates that conntrack is correctly cleaned once a container is destroyed
  1488. func (s *DockerNetworkSuite) TestConntrackFlowsLeak(c *check.C) {
  1489. testRequires(c, IsAmd64, DaemonIsLinux, Network)
  1490. // Create a new network
  1491. cli.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")
  1492. assertNwIsAvailable(c, "testbind")
  1493. // Launch the server, this will remain listening on an exposed port and reply to any request in a ping/pong fashion
  1494. cmd := "while true; do echo hello | nc -w 1 -lu 8080; done"
  1495. cli.DockerCmd(c, "run", "-d", "--name", "server", "--net", "testbind", "-p", "8080:8080/udp", "appropriate/nc", "sh", "-c", cmd)
  1496. // Launch a container client, here the objective is to create a flow that is natted in order to expose the bug
  1497. cmd = "echo world | nc -q 1 -u 192.168.10.1 8080"
  1498. cli.DockerCmd(c, "run", "-d", "--name", "client", "--net=host", "appropriate/nc", "sh", "-c", cmd)
  1499. // Get all the flows using netlink
  1500. flows, err := netlink.ConntrackTableList(netlink.ConntrackTable, unix.AF_INET)
  1501. c.Assert(err, check.IsNil)
  1502. var flowMatch int
  1503. for _, flow := range flows {
  1504. // count only the flows that we are interested in, skipping others that can be laying around the host
  1505. if flow.Forward.Protocol == unix.IPPROTO_UDP &&
  1506. flow.Forward.DstIP.Equal(net.ParseIP("192.168.10.1")) &&
  1507. flow.Forward.DstPort == 8080 {
  1508. flowMatch++
  1509. }
  1510. }
  1511. // The client should have created only 1 flow
  1512. c.Assert(flowMatch, checker.Equals, 1)
  1513. // Now delete the server, this will trigger the conntrack cleanup
  1514. cli.DockerCmd(c, "rm", "-fv", "server")
  1515. // Fetch again all the flows and validate that there is no server flow in the conntrack laying around
  1516. flows, err = netlink.ConntrackTableList(netlink.ConntrackTable, unix.AF_INET)
  1517. c.Assert(err, check.IsNil)
  1518. flowMatch = 0
  1519. for _, flow := range flows {
  1520. if flow.Forward.Protocol == unix.IPPROTO_UDP &&
  1521. flow.Forward.DstIP.Equal(net.ParseIP("192.168.10.1")) &&
  1522. flow.Forward.DstPort == 8080 {
  1523. flowMatch++
  1524. }
  1525. }
  1526. // All the flows have to be gone
  1527. c.Assert(flowMatch, checker.Equals, 0)
  1528. }