docker_cli_network_unix_test.go 72 KB

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