docker_cli_network_unix_test.go 71 KB

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