docker_cli_network_unix_test.go 71 KB

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