docker_cli_network_unix_test.go 70 KB

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