docker_cli_network_unix_test.go 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801
  1. // +build !windows
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "net/http/httptest"
  10. "os"
  11. "strings"
  12. "testing"
  13. "time"
  14. "github.com/docker/docker/api/types"
  15. "github.com/docker/docker/api/types/versions/v1p20"
  16. "github.com/docker/docker/integration-cli/cli"
  17. "github.com/docker/docker/integration-cli/daemon"
  18. testdaemon "github.com/docker/docker/internal/test/daemon"
  19. "github.com/docker/docker/pkg/stringid"
  20. "github.com/docker/docker/runconfig"
  21. "github.com/docker/libnetwork/driverapi"
  22. remoteapi "github.com/docker/libnetwork/drivers/remote/api"
  23. "github.com/docker/libnetwork/ipamapi"
  24. remoteipam "github.com/docker/libnetwork/ipams/remote/api"
  25. "github.com/docker/libnetwork/netlabel"
  26. "github.com/vishvananda/netlink"
  27. "golang.org/x/sys/unix"
  28. "gotest.tools/assert"
  29. "gotest.tools/icmd"
  30. )
  31. const dummyNetworkDriver = "dummy-network-driver"
  32. const dummyIPAMDriver = "dummy-ipam-driver"
  33. var remoteDriverNetworkRequest remoteapi.CreateNetworkRequest
  34. func init() {
  35. /*check.Suite(&DockerNetworkSuite{ds: &DockerSuite{}})*/
  36. }
  37. type DockerNetworkSuite struct {
  38. server *httptest.Server
  39. ds *DockerSuite
  40. d *daemon.Daemon
  41. }
  42. func (s *DockerNetworkSuite) SetUpTest(c *testing.T) {
  43. s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
  44. }
  45. func (s *DockerNetworkSuite) TearDownTest(c *testing.T) {
  46. if s.d != nil {
  47. s.d.Stop(c)
  48. s.ds.TearDownTest(c)
  49. }
  50. }
  51. func (s *DockerNetworkSuite) SetUpSuite(c *testing.T) {
  52. mux := http.NewServeMux()
  53. s.server = httptest.NewServer(mux)
  54. assert.Assert(c, s.server != nil, "Failed to start an HTTP Server")
  55. setupRemoteNetworkDrivers(c, mux, s.server.URL, dummyNetworkDriver, dummyIPAMDriver)
  56. }
  57. func setupRemoteNetworkDrivers(c *testing.T, mux *http.ServeMux, url, netDrv, ipamDrv string) {
  58. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  59. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  60. fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType)
  61. })
  62. // Network driver implementation
  63. mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  64. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  65. fmt.Fprintf(w, `{"Scope":"local"}`)
  66. })
  67. mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  68. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  69. if err != nil {
  70. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  71. return
  72. }
  73. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  74. fmt.Fprintf(w, "null")
  75. })
  76. mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  77. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  78. fmt.Fprintf(w, "null")
  79. })
  80. mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  81. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  82. fmt.Fprintf(w, `{"Interface":{"MacAddress":"a0:b1:c2:d3:e4:f5"}}`)
  83. })
  84. mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  85. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  86. veth := &netlink.Veth{
  87. LinkAttrs: netlink.LinkAttrs{Name: "randomIfName", TxQLen: 0}, PeerName: "cnt0"}
  88. if err := netlink.LinkAdd(veth); err != nil {
  89. fmt.Fprintf(w, `{"Error":"failed to add veth pair: `+err.Error()+`"}`)
  90. } else {
  91. fmt.Fprintf(w, `{"InterfaceName":{ "SrcName":"cnt0", "DstPrefix":"veth"}}`)
  92. }
  93. })
  94. mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  95. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  96. fmt.Fprintf(w, "null")
  97. })
  98. mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  99. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  100. if link, err := netlink.LinkByName("cnt0"); err == nil {
  101. netlink.LinkDel(link)
  102. }
  103. fmt.Fprintf(w, "null")
  104. })
  105. // IPAM Driver implementation
  106. var (
  107. poolRequest remoteipam.RequestPoolRequest
  108. poolReleaseReq remoteipam.ReleasePoolRequest
  109. addressRequest remoteipam.RequestAddressRequest
  110. addressReleaseReq remoteipam.ReleaseAddressRequest
  111. lAS = "localAS"
  112. gAS = "globalAS"
  113. pool = "172.28.0.0/16"
  114. poolID = lAS + "/" + pool
  115. gw = "172.28.255.254/16"
  116. )
  117. mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  118. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  119. fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`)
  120. })
  121. mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  122. err := json.NewDecoder(r.Body).Decode(&poolRequest)
  123. if err != nil {
  124. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  125. return
  126. }
  127. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  128. if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS {
  129. fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`)
  130. } else if poolRequest.Pool != "" && poolRequest.Pool != pool {
  131. fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`)
  132. } else {
  133. fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`)
  134. }
  135. })
  136. mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  137. err := json.NewDecoder(r.Body).Decode(&addressRequest)
  138. if err != nil {
  139. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  140. return
  141. }
  142. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  143. // make sure libnetwork is now querying on the expected pool id
  144. if addressRequest.PoolID != poolID {
  145. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  146. } else if addressRequest.Address != "" {
  147. fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`)
  148. } else {
  149. fmt.Fprintf(w, `{"Address":"`+gw+`"}`)
  150. }
  151. })
  152. mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  153. err := json.NewDecoder(r.Body).Decode(&addressReleaseReq)
  154. if err != nil {
  155. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  156. return
  157. }
  158. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  159. // make sure libnetwork is now asking to release the expected address from the expected poolid
  160. if addressRequest.PoolID != poolID {
  161. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  162. } else if addressReleaseReq.Address != gw {
  163. fmt.Fprintf(w, `{"Error":"unknown address"}`)
  164. } else {
  165. fmt.Fprintf(w, "null")
  166. }
  167. })
  168. mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  169. err := json.NewDecoder(r.Body).Decode(&poolReleaseReq)
  170. if err != nil {
  171. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  172. return
  173. }
  174. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  175. // make sure libnetwork is now asking to release the expected poolid
  176. if addressRequest.PoolID != poolID {
  177. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  178. } else {
  179. fmt.Fprintf(w, "null")
  180. }
  181. })
  182. err := os.MkdirAll("/etc/docker/plugins", 0755)
  183. assert.NilError(c, err)
  184. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", netDrv)
  185. err = ioutil.WriteFile(fileName, []byte(url), 0644)
  186. assert.NilError(c, err)
  187. ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", ipamDrv)
  188. err = ioutil.WriteFile(ipamFileName, []byte(url), 0644)
  189. assert.NilError(c, err)
  190. }
  191. func (s *DockerNetworkSuite) TearDownSuite(c *testing.T) {
  192. if s.server == nil {
  193. return
  194. }
  195. s.server.Close()
  196. err := os.RemoveAll("/etc/docker/plugins")
  197. assert.NilError(c, err)
  198. }
  199. func assertNwIsAvailable(c *testing.T, name string) {
  200. if !isNwPresent(c, name) {
  201. c.Fatalf("Network %s not found in network ls o/p", name)
  202. }
  203. }
  204. func assertNwNotAvailable(c *testing.T, name string) {
  205. if isNwPresent(c, name) {
  206. c.Fatalf("Found network %s in network ls o/p", name)
  207. }
  208. }
  209. func isNwPresent(c *testing.T, name string) bool {
  210. out, _ := dockerCmd(c, "network", "ls")
  211. lines := strings.Split(out, "\n")
  212. for i := 1; i < len(lines)-1; i++ {
  213. netFields := strings.Fields(lines[i])
  214. if netFields[1] == name {
  215. return true
  216. }
  217. }
  218. return false
  219. }
  220. // assertNwList checks network list retrieved with ls command
  221. // equals to expected network list
  222. // note: out should be `network ls [option]` result
  223. func assertNwList(c *testing.T, out string, expectNws []string) {
  224. lines := strings.Split(out, "\n")
  225. var nwList []string
  226. for _, line := range lines[1 : len(lines)-1] {
  227. netFields := strings.Fields(line)
  228. // wrap all network name in nwList
  229. nwList = append(nwList, netFields[1])
  230. }
  231. // network ls should contains all expected networks
  232. assert.DeepEqual(c, nwList, expectNws)
  233. }
  234. func getNwResource(c *testing.T, name string) *types.NetworkResource {
  235. out, _ := dockerCmd(c, "network", "inspect", name)
  236. var nr []types.NetworkResource
  237. err := json.Unmarshal([]byte(out), &nr)
  238. assert.NilError(c, err)
  239. return &nr[0]
  240. }
  241. func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *testing.T) {
  242. defaults := []string{"bridge", "host", "none"}
  243. for _, nn := range defaults {
  244. assertNwIsAvailable(c, nn)
  245. }
  246. }
  247. func (s *DockerNetworkSuite) TestDockerNetworkCreatePredefined(c *testing.T) {
  248. predefined := []string{"bridge", "host", "none", "default"}
  249. for _, net := range predefined {
  250. // predefined networks can't be created again
  251. out, _, err := dockerCmdWithError("network", "create", net)
  252. assert.ErrorContains(c, err, "", out)
  253. }
  254. }
  255. func (s *DockerNetworkSuite) TestDockerNetworkCreateHostBind(c *testing.T) {
  256. 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")
  257. assertNwIsAvailable(c, "testbind")
  258. out := runSleepingContainer(c, "--net=testbind", "-p", "5000:5000")
  259. id := strings.TrimSpace(out)
  260. assert.NilError(c, waitRun(id))
  261. out, _ = dockerCmd(c, "ps")
  262. assert.Assert(c, strings.Contains(out, "192.168.10.1:5000->5000/tcp"))
  263. }
  264. func (s *DockerNetworkSuite) TestDockerNetworkRmPredefined(c *testing.T) {
  265. predefined := []string{"bridge", "host", "none", "default"}
  266. for _, net := range predefined {
  267. // predefined networks can't be removed
  268. out, _, err := dockerCmdWithError("network", "rm", net)
  269. assert.ErrorContains(c, err, "", out)
  270. }
  271. }
  272. func (s *DockerNetworkSuite) TestDockerNetworkLsFilter(c *testing.T) {
  273. testRequires(c, OnlyDefaultNetworks)
  274. testNet := "testnet1"
  275. testLabel := "foo"
  276. testValue := "bar"
  277. out, _ := dockerCmd(c, "network", "create", "dev")
  278. defer func() {
  279. dockerCmd(c, "network", "rm", "dev")
  280. dockerCmd(c, "network", "rm", testNet)
  281. }()
  282. networkID := strings.TrimSpace(out)
  283. // filter with partial ID
  284. // only show 'dev' network
  285. out, _ = dockerCmd(c, "network", "ls", "-f", "id="+networkID[0:5])
  286. assertNwList(c, out, []string{"dev"})
  287. out, _ = dockerCmd(c, "network", "ls", "-f", "name=dge")
  288. assertNwList(c, out, []string{"bridge"})
  289. // only show built-in network (bridge, none, host)
  290. out, _ = dockerCmd(c, "network", "ls", "-f", "type=builtin")
  291. assertNwList(c, out, []string{"bridge", "host", "none"})
  292. // only show custom networks (dev)
  293. out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom")
  294. assertNwList(c, out, []string{"dev"})
  295. // show all networks with filter
  296. // it should be equivalent of ls without option
  297. out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom", "-f", "type=builtin")
  298. assertNwList(c, out, []string{"bridge", "dev", "host", "none"})
  299. dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet)
  300. assertNwIsAvailable(c, testNet)
  301. out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel)
  302. assertNwList(c, out, []string{testNet})
  303. out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel+"="+testValue)
  304. assertNwList(c, out, []string{testNet})
  305. out, _ = dockerCmd(c, "network", "ls", "-f", "label=nonexistent")
  306. outArr := strings.Split(strings.TrimSpace(out), "\n")
  307. assert.Equal(c, len(outArr), 1, fmt.Sprintf("%s\n", out))
  308. out, _ = dockerCmd(c, "network", "ls", "-f", "driver=null")
  309. assertNwList(c, out, []string{"none"})
  310. out, _ = dockerCmd(c, "network", "ls", "-f", "driver=host")
  311. assertNwList(c, out, []string{"host"})
  312. out, _ = dockerCmd(c, "network", "ls", "-f", "driver=bridge")
  313. assertNwList(c, out, []string{"bridge", "dev", testNet})
  314. }
  315. func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *testing.T) {
  316. dockerCmd(c, "network", "create", "test")
  317. assertNwIsAvailable(c, "test")
  318. dockerCmd(c, "network", "rm", "test")
  319. assertNwNotAvailable(c, "test")
  320. }
  321. func (s *DockerNetworkSuite) TestDockerNetworkCreateLabel(c *testing.T) {
  322. testNet := "testnetcreatelabel"
  323. testLabel := "foo"
  324. testValue := "bar"
  325. dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet)
  326. assertNwIsAvailable(c, testNet)
  327. out, _, err := dockerCmdWithError("network", "inspect", "--format={{ .Labels."+testLabel+" }}", testNet)
  328. assert.NilError(c, err)
  329. assert.Equal(c, strings.TrimSpace(out), testValue)
  330. dockerCmd(c, "network", "rm", testNet)
  331. assertNwNotAvailable(c, testNet)
  332. }
  333. func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *testing.T) {
  334. out, _, err := dockerCmdWithError("network", "rm", "test")
  335. assert.ErrorContains(c, err, "", out)
  336. }
  337. func (s *DockerSuite) TestDockerNetworkDeleteMultiple(c *testing.T) {
  338. dockerCmd(c, "network", "create", "testDelMulti0")
  339. assertNwIsAvailable(c, "testDelMulti0")
  340. dockerCmd(c, "network", "create", "testDelMulti1")
  341. assertNwIsAvailable(c, "testDelMulti1")
  342. dockerCmd(c, "network", "create", "testDelMulti2")
  343. assertNwIsAvailable(c, "testDelMulti2")
  344. out, _ := dockerCmd(c, "run", "-d", "--net", "testDelMulti2", "busybox", "top")
  345. containerID := strings.TrimSpace(out)
  346. waitRun(containerID)
  347. // delete three networks at the same time, since testDelMulti2
  348. // contains active container, its deletion should fail.
  349. out, _, err := dockerCmdWithError("network", "rm", "testDelMulti0", "testDelMulti1", "testDelMulti2")
  350. // err should not be nil due to deleting testDelMulti2 failed.
  351. assert.Assert(c, err != nil, fmt.Sprintf("out: %s", out))
  352. // testDelMulti2 should fail due to network has active endpoints
  353. assert.Assert(c, strings.Contains(out, "has active endpoints"))
  354. assertNwNotAvailable(c, "testDelMulti0")
  355. assertNwNotAvailable(c, "testDelMulti1")
  356. // testDelMulti2 can't be deleted, so it should exist
  357. assertNwIsAvailable(c, "testDelMulti2")
  358. }
  359. func (s *DockerSuite) TestDockerNetworkInspect(c *testing.T) {
  360. out, _ := dockerCmd(c, "network", "inspect", "host")
  361. var networkResources []types.NetworkResource
  362. err := json.Unmarshal([]byte(out), &networkResources)
  363. assert.NilError(c, err)
  364. assert.Equal(c, len(networkResources), 1)
  365. out, _ = dockerCmd(c, "network", "inspect", "--format={{ .Name }}", "host")
  366. assert.Equal(c, strings.TrimSpace(out), "host")
  367. }
  368. func (s *DockerSuite) TestDockerNetworkInspectWithID(c *testing.T) {
  369. out, _ := dockerCmd(c, "network", "create", "test2")
  370. networkID := strings.TrimSpace(out)
  371. assertNwIsAvailable(c, "test2")
  372. out, _ = dockerCmd(c, "network", "inspect", "--format={{ .Id }}", "test2")
  373. assert.Equal(c, strings.TrimSpace(out), networkID)
  374. out, _ = dockerCmd(c, "network", "inspect", "--format={{ .ID }}", "test2")
  375. assert.Equal(c, strings.TrimSpace(out), networkID)
  376. }
  377. func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *testing.T) {
  378. result := dockerCmdWithResult("network", "inspect", "host", "none")
  379. result.Assert(c, icmd.Success)
  380. var networkResources []types.NetworkResource
  381. err := json.Unmarshal([]byte(result.Stdout()), &networkResources)
  382. assert.NilError(c, err)
  383. assert.Equal(c, len(networkResources), 2)
  384. }
  385. func (s *DockerSuite) TestDockerInspectMultipleNetworksIncludingNonexistent(c *testing.T) {
  386. // non-existent network was not at the beginning of the inspect list
  387. // This should print an error, return an exitCode 1 and print the host network
  388. result := dockerCmdWithResult("network", "inspect", "host", "nonexistent")
  389. result.Assert(c, icmd.Expected{
  390. ExitCode: 1,
  391. Err: "Error: No such network: nonexistent",
  392. Out: "host",
  393. })
  394. var networkResources []types.NetworkResource
  395. err := json.Unmarshal([]byte(result.Stdout()), &networkResources)
  396. assert.NilError(c, err)
  397. assert.Equal(c, len(networkResources), 1)
  398. // Only one non-existent network to inspect
  399. // Should print an error and return an exitCode, nothing else
  400. result = dockerCmdWithResult("network", "inspect", "nonexistent")
  401. result.Assert(c, icmd.Expected{
  402. ExitCode: 1,
  403. Err: "Error: No such network: nonexistent",
  404. Out: "[]",
  405. })
  406. // non-existent network was at the beginning of the inspect list
  407. // Should not fail fast, and still print host network but print an error
  408. result = dockerCmdWithResult("network", "inspect", "nonexistent", "host")
  409. result.Assert(c, icmd.Expected{
  410. ExitCode: 1,
  411. Err: "Error: No such network: nonexistent",
  412. Out: "host",
  413. })
  414. networkResources = []types.NetworkResource{}
  415. err = json.Unmarshal([]byte(result.Stdout()), &networkResources)
  416. assert.NilError(c, err)
  417. assert.Equal(c, len(networkResources), 1)
  418. }
  419. func (s *DockerSuite) TestDockerInspectNetworkWithContainerName(c *testing.T) {
  420. dockerCmd(c, "network", "create", "brNetForInspect")
  421. assertNwIsAvailable(c, "brNetForInspect")
  422. defer func() {
  423. dockerCmd(c, "network", "rm", "brNetForInspect")
  424. assertNwNotAvailable(c, "brNetForInspect")
  425. }()
  426. out, _ := dockerCmd(c, "run", "-d", "--name", "testNetInspect1", "--net", "brNetForInspect", "busybox", "top")
  427. assert.Assert(c, waitRun("testNetInspect1") == nil)
  428. containerID := strings.TrimSpace(out)
  429. defer func() {
  430. // we don't stop container by name, because we'll rename it later
  431. dockerCmd(c, "stop", containerID)
  432. }()
  433. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  434. var networkResources []types.NetworkResource
  435. err := json.Unmarshal([]byte(out), &networkResources)
  436. assert.NilError(c, err)
  437. assert.Equal(c, len(networkResources), 1)
  438. container, ok := networkResources[0].Containers[containerID]
  439. assert.Assert(c, ok)
  440. assert.Equal(c, container.Name, "testNetInspect1")
  441. // rename container and check docker inspect output update
  442. newName := "HappyNewName"
  443. dockerCmd(c, "rename", "testNetInspect1", newName)
  444. // check whether network inspect works properly
  445. out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
  446. var newNetRes []types.NetworkResource
  447. err = json.Unmarshal([]byte(out), &newNetRes)
  448. assert.NilError(c, err)
  449. assert.Equal(c, len(newNetRes), 1)
  450. container1, ok := newNetRes[0].Containers[containerID]
  451. assert.Assert(c, ok)
  452. assert.Equal(c, container1.Name, newName)
  453. }
  454. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *testing.T) {
  455. dockerCmd(c, "network", "create", "test")
  456. assertNwIsAvailable(c, "test")
  457. nr := getNwResource(c, "test")
  458. assert.Equal(c, nr.Name, "test")
  459. assert.Equal(c, len(nr.Containers), 0)
  460. // run a container
  461. out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  462. assert.Assert(c, waitRun("test") == nil)
  463. containerID := strings.TrimSpace(out)
  464. // connect the container to the test network
  465. dockerCmd(c, "network", "connect", "test", containerID)
  466. // inspect the network to make sure container is connected
  467. nr = getNetworkResource(c, nr.ID)
  468. assert.Equal(c, len(nr.Containers), 1)
  469. // check if container IP matches network inspect
  470. ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address)
  471. assert.NilError(c, err)
  472. containerIP := findContainerIP(c, "test", "test")
  473. assert.Equal(c, ip.String(), containerIP)
  474. // disconnect container from the network
  475. dockerCmd(c, "network", "disconnect", "test", containerID)
  476. nr = getNwResource(c, "test")
  477. assert.Equal(c, nr.Name, "test")
  478. assert.Equal(c, len(nr.Containers), 0)
  479. // run another container
  480. out, _ = dockerCmd(c, "run", "-d", "--net", "test", "--name", "test2", "busybox", "top")
  481. assert.Assert(c, waitRun("test2") == nil)
  482. containerID = strings.TrimSpace(out)
  483. nr = getNwResource(c, "test")
  484. assert.Equal(c, nr.Name, "test")
  485. assert.Equal(c, len(nr.Containers), 1)
  486. // force disconnect the container to the test network
  487. dockerCmd(c, "network", "disconnect", "-f", "test", containerID)
  488. nr = getNwResource(c, "test")
  489. assert.Equal(c, nr.Name, "test")
  490. assert.Equal(c, len(nr.Containers), 0)
  491. dockerCmd(c, "network", "rm", "test")
  492. assertNwNotAvailable(c, "test")
  493. }
  494. func (s *DockerNetworkSuite) TestDockerNetworkIPAMMultipleNetworks(c *testing.T) {
  495. testRequires(c, testEnv.IsLocalDaemon)
  496. // test0 bridge network
  497. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
  498. assertNwIsAvailable(c, "test1")
  499. // test2 bridge network does not overlap
  500. dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
  501. assertNwIsAvailable(c, "test2")
  502. // for networks w/o ipam specified, docker will choose proper non-overlapping subnets
  503. dockerCmd(c, "network", "create", "test3")
  504. assertNwIsAvailable(c, "test3")
  505. dockerCmd(c, "network", "create", "test4")
  506. assertNwIsAvailable(c, "test4")
  507. dockerCmd(c, "network", "create", "test5")
  508. assertNwIsAvailable(c, "test5")
  509. // test network with multiple subnets
  510. // bridge network doesn't support multiple subnets. hence, use a dummy driver that supports
  511. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.170.0.0/16", "--subnet=192.171.0.0/16", "test6")
  512. assertNwIsAvailable(c, "test6")
  513. // test network with multiple subnets with valid ipam combinations
  514. // also check same subnet across networks when the driver supports it.
  515. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
  516. "--subnet=192.172.0.0/16", "--subnet=192.173.0.0/16",
  517. "--gateway=192.172.0.100", "--gateway=192.173.0.100",
  518. "--ip-range=192.172.1.0/24",
  519. "--aux-address", "a=192.172.1.5", "--aux-address", "b=192.172.1.6",
  520. "--aux-address", "c=192.173.1.5", "--aux-address", "d=192.173.1.6",
  521. "test7")
  522. assertNwIsAvailable(c, "test7")
  523. // cleanup
  524. for i := 1; i < 8; i++ {
  525. dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
  526. }
  527. }
  528. func (s *DockerNetworkSuite) TestDockerNetworkCustomIPAM(c *testing.T) {
  529. testRequires(c, testEnv.IsLocalDaemon)
  530. // Create a bridge network using custom ipam driver
  531. dockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "br0")
  532. assertNwIsAvailable(c, "br0")
  533. // Verify expected network ipam fields are there
  534. nr := getNetworkResource(c, "br0")
  535. assert.Equal(c, nr.Driver, "bridge")
  536. assert.Equal(c, nr.IPAM.Driver, dummyIPAMDriver)
  537. // remove network and exercise remote ipam driver
  538. dockerCmd(c, "network", "rm", "br0")
  539. assertNwNotAvailable(c, "br0")
  540. }
  541. func (s *DockerNetworkSuite) TestDockerNetworkIPAMOptions(c *testing.T) {
  542. testRequires(c, testEnv.IsLocalDaemon)
  543. // Create a bridge network using custom ipam driver and options
  544. dockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "--ipam-opt", "opt1=drv1", "--ipam-opt", "opt2=drv2", "br0")
  545. assertNwIsAvailable(c, "br0")
  546. // Verify expected network ipam options
  547. nr := getNetworkResource(c, "br0")
  548. opts := nr.IPAM.Options
  549. assert.Equal(c, opts["opt1"], "drv1")
  550. assert.Equal(c, opts["opt2"], "drv2")
  551. }
  552. func (s *DockerNetworkSuite) TestDockerNetworkNullIPAMDriver(c *testing.T) {
  553. testRequires(c, testEnv.IsLocalDaemon)
  554. // Create a network with null ipam driver
  555. _, _, err := dockerCmdWithError("network", "create", "-d", dummyNetworkDriver, "--ipam-driver", "null", "test000")
  556. assert.NilError(c, err)
  557. assertNwIsAvailable(c, "test000")
  558. // Verify the inspect data contains the default subnet provided by the null
  559. // ipam driver and no gateway, as the null ipam driver does not provide one
  560. nr := getNetworkResource(c, "test000")
  561. assert.Equal(c, nr.IPAM.Driver, "null")
  562. assert.Equal(c, len(nr.IPAM.Config), 1)
  563. assert.Equal(c, nr.IPAM.Config[0].Subnet, "0.0.0.0/0")
  564. assert.Equal(c, nr.IPAM.Config[0].Gateway, "")
  565. }
  566. func (s *DockerNetworkSuite) TestDockerNetworkInspectDefault(c *testing.T) {
  567. nr := getNetworkResource(c, "none")
  568. assert.Equal(c, nr.Driver, "null")
  569. assert.Equal(c, nr.Scope, "local")
  570. assert.Equal(c, nr.Internal, false)
  571. assert.Equal(c, nr.EnableIPv6, false)
  572. assert.Equal(c, nr.IPAM.Driver, "default")
  573. assert.Equal(c, len(nr.IPAM.Config), 0)
  574. nr = getNetworkResource(c, "host")
  575. assert.Equal(c, nr.Driver, "host")
  576. assert.Equal(c, nr.Scope, "local")
  577. assert.Equal(c, nr.Internal, false)
  578. assert.Equal(c, nr.EnableIPv6, false)
  579. assert.Equal(c, nr.IPAM.Driver, "default")
  580. assert.Equal(c, len(nr.IPAM.Config), 0)
  581. nr = getNetworkResource(c, "bridge")
  582. assert.Equal(c, nr.Driver, "bridge")
  583. assert.Equal(c, nr.Scope, "local")
  584. assert.Equal(c, nr.Internal, false)
  585. assert.Equal(c, nr.EnableIPv6, false)
  586. assert.Equal(c, nr.IPAM.Driver, "default")
  587. assert.Equal(c, len(nr.IPAM.Config), 1)
  588. }
  589. func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomUnspecified(c *testing.T) {
  590. // if unspecified, network subnet will be selected from inside preferred pool
  591. dockerCmd(c, "network", "create", "test01")
  592. assertNwIsAvailable(c, "test01")
  593. nr := getNetworkResource(c, "test01")
  594. assert.Equal(c, nr.Driver, "bridge")
  595. assert.Equal(c, nr.Scope, "local")
  596. assert.Equal(c, nr.Internal, false)
  597. assert.Equal(c, nr.EnableIPv6, false)
  598. assert.Equal(c, nr.IPAM.Driver, "default")
  599. assert.Equal(c, len(nr.IPAM.Config), 1)
  600. dockerCmd(c, "network", "rm", "test01")
  601. assertNwNotAvailable(c, "test01")
  602. }
  603. func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomSpecified(c *testing.T) {
  604. 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")
  605. assertNwIsAvailable(c, "br0")
  606. nr := getNetworkResource(c, "br0")
  607. assert.Equal(c, nr.Driver, "bridge")
  608. assert.Equal(c, nr.Scope, "local")
  609. assert.Equal(c, nr.Internal, false)
  610. assert.Equal(c, nr.EnableIPv6, true)
  611. assert.Equal(c, nr.IPAM.Driver, "default")
  612. assert.Equal(c, len(nr.IPAM.Config), 2)
  613. assert.Equal(c, nr.IPAM.Config[0].Subnet, "172.28.0.0/16")
  614. assert.Equal(c, nr.IPAM.Config[0].IPRange, "172.28.5.0/24")
  615. assert.Equal(c, nr.IPAM.Config[0].Gateway, "172.28.5.254")
  616. assert.Equal(c, nr.Internal, false)
  617. dockerCmd(c, "network", "rm", "br0")
  618. assertNwNotAvailable(c, "br0")
  619. }
  620. func (s *DockerNetworkSuite) TestDockerNetworkIPAMInvalidCombinations(c *testing.T) {
  621. // network with ip-range out of subnet range
  622. _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
  623. assert.ErrorContains(c, err, "")
  624. // network with multiple gateways for a single subnet
  625. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
  626. assert.ErrorContains(c, err, "")
  627. // Multiple overlapping subnets in the same network must fail
  628. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
  629. assert.ErrorContains(c, err, "")
  630. // overlapping subnets across networks must fail
  631. // create a valid test0 network
  632. dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
  633. assertNwIsAvailable(c, "test0")
  634. // create an overlapping test1 network
  635. _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
  636. assert.ErrorContains(c, err, "")
  637. dockerCmd(c, "network", "rm", "test0")
  638. assertNwNotAvailable(c, "test0")
  639. }
  640. func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *testing.T) {
  641. testRequires(c, testEnv.IsLocalDaemon)
  642. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
  643. assertNwIsAvailable(c, "testopt")
  644. gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
  645. assert.Assert(c, gopts != nil)
  646. opts, ok := gopts.(map[string]interface{})
  647. assert.Equal(c, ok, true)
  648. assert.Equal(c, opts["opt1"], "drv1")
  649. assert.Equal(c, opts["opt2"], "drv2")
  650. dockerCmd(c, "network", "rm", "testopt")
  651. assertNwNotAvailable(c, "testopt")
  652. }
  653. func (s *DockerNetworkSuite) TestDockerPluginV2NetworkDriver(c *testing.T) {
  654. testRequires(c, DaemonIsLinux, IsAmd64, Network)
  655. var (
  656. npName = "tiborvass/test-docker-netplugin"
  657. npTag = "latest"
  658. npNameWithTag = npName + ":" + npTag
  659. )
  660. _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", npNameWithTag)
  661. assert.NilError(c, err)
  662. out, _, err := dockerCmdWithError("plugin", "ls")
  663. assert.NilError(c, err)
  664. assert.Assert(c, strings.Contains(out, npName))
  665. assert.Assert(c, strings.Contains(out, npTag))
  666. assert.Assert(c, strings.Contains(out, "true"))
  667. dockerCmd(c, "network", "create", "-d", npNameWithTag, "v2net")
  668. assertNwIsAvailable(c, "v2net")
  669. dockerCmd(c, "network", "rm", "v2net")
  670. assertNwNotAvailable(c, "v2net")
  671. }
  672. func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *testing.T) {
  673. // On default bridge network built-in service discovery should not happen
  674. hostsFile := "/etc/hosts"
  675. bridgeName := "external-bridge"
  676. bridgeIP := "192.169.255.254/24"
  677. createInterface(c, "bridge", bridgeName, bridgeIP)
  678. defer deleteInterface(c, bridgeName)
  679. s.d.StartWithBusybox(c, "--bridge", bridgeName)
  680. defer s.d.Restart(c)
  681. // run two containers and store first container's etc/hosts content
  682. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  683. assert.NilError(c, err)
  684. cid1 := strings.TrimSpace(out)
  685. defer s.d.Cmd("stop", cid1)
  686. hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  687. assert.NilError(c, err)
  688. out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top")
  689. assert.NilError(c, err)
  690. cid2 := strings.TrimSpace(out)
  691. // verify first container's etc/hosts file has not changed after spawning the second named container
  692. hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
  693. assert.NilError(c, err)
  694. assert.Equal(c, string(hosts), string(hostsPost), fmt.Sprintf("Unexpected %s change on second container creation", hostsFile))
  695. // stop container 2 and verify first container's etc/hosts has not changed
  696. _, err = s.d.Cmd("stop", cid2)
  697. assert.NilError(c, err)
  698. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  699. assert.NilError(c, err)
  700. assert.Equal(c, string(hosts), string(hostsPost), fmt.Sprintf("Unexpected %s change on second container creation", hostsFile))
  701. // but discovery is on when connecting to non default bridge network
  702. network := "anotherbridge"
  703. out, err = s.d.Cmd("network", "create", network)
  704. assert.NilError(c, err, out)
  705. defer s.d.Cmd("network", "rm", network)
  706. out, err = s.d.Cmd("network", "connect", network, cid1)
  707. assert.NilError(c, err, out)
  708. hosts, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  709. assert.NilError(c, err)
  710. hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
  711. assert.NilError(c, err)
  712. assert.Equal(c, string(hosts), string(hostsPost), fmt.Sprintf("Unexpected %s change on second network connection", hostsFile))
  713. }
  714. func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *testing.T) {
  715. testRequires(c, NotArm)
  716. hostsFile := "/etc/hosts"
  717. cstmBridgeNw := "custom-bridge-nw"
  718. cstmBridgeNw1 := "custom-bridge-nw1"
  719. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw)
  720. assertNwIsAvailable(c, cstmBridgeNw)
  721. // run two anonymous containers and store their etc/hosts content
  722. out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  723. cid1 := strings.TrimSpace(out)
  724. hosts1 := readContainerFileWithExec(c, cid1, hostsFile)
  725. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
  726. cid2 := strings.TrimSpace(out)
  727. // verify first container etc/hosts file has not changed
  728. hosts1post := readContainerFileWithExec(c, cid1, hostsFile)
  729. assert.Equal(c, string(hosts1), string(hosts1post), fmt.Sprintf("Unexpected %s change on anonymous container creation", hostsFile))
  730. // Connect the 2nd container to a new network and verify the
  731. // first container /etc/hosts file still hasn't changed.
  732. dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1)
  733. assertNwIsAvailable(c, cstmBridgeNw1)
  734. dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2)
  735. hosts2 := readContainerFileWithExec(c, cid2, hostsFile)
  736. hosts1post = readContainerFileWithExec(c, cid1, hostsFile)
  737. assert.Equal(c, string(hosts1), string(hosts1post), fmt.Sprintf("Unexpected %s change on container connect", hostsFile))
  738. // start a named container
  739. cName := "AnyName"
  740. out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top")
  741. cid3 := strings.TrimSpace(out)
  742. // verify that container 1 and 2 can ping the named container
  743. dockerCmd(c, "exec", cid1, "ping", "-c", "1", cName)
  744. dockerCmd(c, "exec", cid2, "ping", "-c", "1", cName)
  745. // Stop named container and verify first two containers' etc/hosts file hasn't changed
  746. dockerCmd(c, "stop", cid3)
  747. hosts1post = readContainerFileWithExec(c, cid1, hostsFile)
  748. assert.Equal(c, string(hosts1), string(hosts1post), fmt.Sprintf("Unexpected %s change on name container creation", hostsFile))
  749. hosts2post := readContainerFileWithExec(c, cid2, hostsFile)
  750. assert.Equal(c, string(hosts2), string(hosts2post), fmt.Sprintf("Unexpected %s change on name container creation", hostsFile))
  751. // verify that container 1 and 2 can't ping the named container now
  752. _, _, err := dockerCmdWithError("exec", cid1, "ping", "-c", "1", cName)
  753. assert.ErrorContains(c, err, "")
  754. _, _, err = dockerCmdWithError("exec", cid2, "ping", "-c", "1", cName)
  755. assert.ErrorContains(c, err, "")
  756. }
  757. func (s *DockerNetworkSuite) TestDockerNetworkLinkOnDefaultNetworkOnly(c *testing.T) {
  758. // Legacy Link feature must work only on default network, and not across networks
  759. cnt1 := "container1"
  760. cnt2 := "container2"
  761. network := "anotherbridge"
  762. // Run first container on default network
  763. dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top")
  764. // Create another network and run the second container on it
  765. dockerCmd(c, "network", "create", network)
  766. assertNwIsAvailable(c, network)
  767. dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top")
  768. // Try launching a container on default network, linking to the first container. Must succeed
  769. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top")
  770. // Try launching a container on default network, linking to the second container. Must fail
  771. _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  772. assert.ErrorContains(c, err, "")
  773. // Connect second container to default network. Now a container on default network can link to it
  774. dockerCmd(c, "network", "connect", "bridge", cnt2)
  775. dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
  776. }
  777. func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *testing.T) {
  778. testRequires(c, testEnv.IsLocalDaemon)
  779. // Verify exposed ports are present in ps output when running a container on
  780. // a network managed by a driver which does not provide the default gateway
  781. // for the container
  782. nwn := "ov"
  783. ctn := "bb"
  784. port1 := 80
  785. port2 := 443
  786. expose1 := fmt.Sprintf("--expose=%d", port1)
  787. expose2 := fmt.Sprintf("--expose=%d", port2)
  788. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  789. assertNwIsAvailable(c, nwn)
  790. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top")
  791. // Check docker ps o/p for last created container reports the unpublished ports
  792. unpPort1 := fmt.Sprintf("%d/tcp", port1)
  793. unpPort2 := fmt.Sprintf("%d/tcp", port2)
  794. out, _ := dockerCmd(c, "ps", "-n=1")
  795. // Missing unpublished ports in docker ps output
  796. assert.Assert(c, strings.Contains(out, unpPort1))
  797. // Missing unpublished ports in docker ps output
  798. assert.Assert(c, strings.Contains(out, unpPort2))
  799. }
  800. func (s *DockerNetworkSuite) TestDockerNetworkDriverUngracefulRestart(c *testing.T) {
  801. testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon)
  802. dnd := "dnd"
  803. did := "did"
  804. mux := http.NewServeMux()
  805. server := httptest.NewServer(mux)
  806. setupRemoteNetworkDrivers(c, mux, server.URL, dnd, did)
  807. s.d.StartWithBusybox(c)
  808. _, err := s.d.Cmd("network", "create", "-d", dnd, "--subnet", "1.1.1.0/24", "net1")
  809. assert.NilError(c, err)
  810. _, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "foo", "--ip", "1.1.1.10", "busybox", "sh")
  811. assert.NilError(c, err)
  812. // Kill daemon and restart
  813. assert.Assert(c, s.d.Kill() == nil)
  814. server.Close()
  815. startTime := time.Now().Unix()
  816. s.d.Restart(c)
  817. lapse := time.Now().Unix() - startTime
  818. if lapse > 60 {
  819. // In normal scenarios, daemon restart takes ~1 second.
  820. // Plugin retry mechanism can delay the daemon start. systemd may not like it.
  821. // Avoid accessing plugins during daemon bootup
  822. c.Logf("daemon restart took too long : %d seconds", lapse)
  823. }
  824. // Restart the custom dummy plugin
  825. mux = http.NewServeMux()
  826. server = httptest.NewServer(mux)
  827. setupRemoteNetworkDrivers(c, mux, server.URL, dnd, did)
  828. // trying to reuse the same ip must succeed
  829. _, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "bar", "--ip", "1.1.1.10", "busybox", "sh")
  830. assert.NilError(c, err)
  831. }
  832. func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *testing.T) {
  833. testRequires(c, testEnv.IsLocalDaemon)
  834. // Verify endpoint MAC address is correctly populated in container's network settings
  835. nwn := "ov"
  836. ctn := "bb"
  837. dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
  838. assertNwIsAvailable(c, nwn)
  839. dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top")
  840. mac := inspectField(c, ctn, "NetworkSettings.Networks."+nwn+".MacAddress")
  841. assert.Equal(c, mac, "a0:b1:c2:d3:e4:f5")
  842. }
  843. func (s *DockerSuite) TestInspectAPIMultipleNetworks(c *testing.T) {
  844. dockerCmd(c, "network", "create", "mybridge1")
  845. dockerCmd(c, "network", "create", "mybridge2")
  846. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  847. id := strings.TrimSpace(out)
  848. assert.NilError(c, waitRun(id))
  849. dockerCmd(c, "network", "connect", "mybridge1", id)
  850. dockerCmd(c, "network", "connect", "mybridge2", id)
  851. body := getInspectBody(c, "v1.20", id)
  852. var inspect120 v1p20.ContainerJSON
  853. err := json.Unmarshal(body, &inspect120)
  854. assert.NilError(c, err)
  855. versionedIP := inspect120.NetworkSettings.IPAddress
  856. body = getInspectBody(c, "v1.21", id)
  857. var inspect121 types.ContainerJSON
  858. err = json.Unmarshal(body, &inspect121)
  859. assert.NilError(c, err)
  860. assert.Equal(c, len(inspect121.NetworkSettings.Networks), 3)
  861. bridge := inspect121.NetworkSettings.Networks["bridge"]
  862. assert.Equal(c, bridge.IPAddress, versionedIP)
  863. assert.Equal(c, bridge.IPAddress, inspect121.NetworkSettings.IPAddress)
  864. }
  865. func connectContainerToNetworks(c *testing.T, d *daemon.Daemon, cName string, nws []string) {
  866. // Run a container on the default network
  867. out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
  868. assert.NilError(c, err, out)
  869. // Attach the container to other networks
  870. for _, nw := range nws {
  871. out, err = d.Cmd("network", "create", nw)
  872. assert.NilError(c, err, out)
  873. out, err = d.Cmd("network", "connect", nw, cName)
  874. assert.NilError(c, err, out)
  875. }
  876. }
  877. func verifyContainerIsConnectedToNetworks(c *testing.T, d *daemon.Daemon, cName string, nws []string) {
  878. // Verify container is connected to all the networks
  879. for _, nw := range nws {
  880. out, err := d.Cmd("inspect", "-f", fmt.Sprintf("{{.NetworkSettings.Networks.%s}}", nw), cName)
  881. assert.NilError(c, err, out)
  882. assert.Assert(c, out != "<no value>\n")
  883. }
  884. }
  885. func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRestart(c *testing.T) {
  886. testRequires(c, testEnv.IsLocalDaemon)
  887. cName := "bb"
  888. nwList := []string{"nw1", "nw2", "nw3"}
  889. s.d.StartWithBusybox(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. cName := "cc"
  901. nwList := []string{"nw1", "nw2", "nw3"}
  902. s.d.StartWithBusybox(c)
  903. connectContainerToNetworks(c, s.d, cName, nwList)
  904. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  905. // Kill daemon and restart
  906. assert.Assert(c, s.d.Kill() == nil)
  907. s.d.Restart(c)
  908. // Restart container
  909. _, err := s.d.Cmd("start", cName)
  910. assert.NilError(c, err)
  911. verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
  912. }
  913. func (s *DockerNetworkSuite) TestDockerNetworkRunNetByID(c *testing.T) {
  914. out, _ := dockerCmd(c, "network", "create", "one")
  915. containerOut, _, err := dockerCmdWithError("run", "-d", "--net", strings.TrimSpace(out), "busybox", "top")
  916. assert.Assert(c, err == nil, containerOut)
  917. }
  918. func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c *testing.T) {
  919. testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon)
  920. s.d.StartWithBusybox(c)
  921. // Run a few containers on host network
  922. for i := 0; i < 10; i++ {
  923. cName := fmt.Sprintf("hostc-%d", i)
  924. out, err := s.d.Cmd("run", "-d", "--name", cName, "--net=host", "--restart=always", "busybox", "top")
  925. assert.NilError(c, err, out)
  926. // verify container has finished starting before killing daemon
  927. err = s.d.WaitRun(cName)
  928. assert.NilError(c, err)
  929. }
  930. // Kill daemon ungracefully and restart
  931. assert.Assert(c, s.d.Kill() == nil)
  932. s.d.Restart(c)
  933. // make sure all the containers are up and running
  934. for i := 0; i < 10; i++ {
  935. err := s.d.WaitRun(fmt.Sprintf("hostc-%d", i))
  936. assert.NilError(c, err)
  937. }
  938. }
  939. func (s *DockerNetworkSuite) TestDockerNetworkConnectToHostFromOtherNetwork(c *testing.T) {
  940. dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
  941. assert.Assert(c, waitRun("container1") == nil)
  942. dockerCmd(c, "network", "disconnect", "bridge", "container1")
  943. out, _, err := dockerCmdWithError("network", "connect", "host", "container1")
  944. assert.ErrorContains(c, err, "", out)
  945. assert.Assert(c, strings.Contains(out, runconfig.ErrConflictHostNetwork.Error()))
  946. }
  947. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromHost(c *testing.T) {
  948. dockerCmd(c, "run", "-d", "--name", "container1", "--net=host", "busybox", "top")
  949. assert.Assert(c, waitRun("container1") == nil)
  950. out, _, err := dockerCmdWithError("network", "disconnect", "host", "container1")
  951. assert.Assert(c, err != nil, "Should err out disconnect from host")
  952. assert.Assert(c, strings.Contains(out, runconfig.ErrConflictHostNetwork.Error()))
  953. }
  954. func (s *DockerNetworkSuite) TestDockerNetworkConnectWithPortMapping(c *testing.T) {
  955. testRequires(c, NotArm)
  956. dockerCmd(c, "network", "create", "test1")
  957. dockerCmd(c, "run", "-d", "--name", "c1", "-p", "5000:5000", "busybox", "top")
  958. assert.Assert(c, waitRun("c1") == nil)
  959. dockerCmd(c, "network", "connect", "test1", "c1")
  960. }
  961. func verifyPortMap(c *testing.T, container, port, originalMapping string, mustBeEqual bool) {
  962. currentMapping, _ := dockerCmd(c, "port", container, port)
  963. if mustBeEqual {
  964. assert.Equal(c, currentMapping, originalMapping)
  965. } else {
  966. assert.Assert(c, currentMapping != originalMapping)
  967. }
  968. }
  969. func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectWithPortMapping(c *testing.T) {
  970. // Connect and disconnect a container with explicit and non-explicit
  971. // host port mapping to/from networks which do cause and do not cause
  972. // the container default gateway to change, and verify docker port cmd
  973. // returns congruent information
  974. testRequires(c, NotArm)
  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.55.44", "--ip6", "2001:db8:abcd::5544", "n1", "c0")
  1078. verifyIPAddressConfig(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  1079. verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
  1080. // 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.55.44", "2001:db8:abcd::5544")
  1087. verifyIPAddresses(c, "c0", "n1", "172.30.55.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, fmt.Sprintf("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, fmt.Sprintf("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, fmt.Sprintf("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, fmt.Sprintf("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", "top")
  1155. assert.ErrorContains(c, err, "")
  1156. _, _, err = dockerCmdWithError("run", "--link-local-ip", "2001:db8::89", "busybox", "top")
  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 *DockerSuite) TestUserDefinedNetworkConnectDisconnectLink(c *testing.T) {
  1190. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  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(fmt.Sprintf("Should contain '%s' network", netWorkName1)))
  1235. assert.Assert(c, strings.Contains(networks, netWorkName2), fmt.Sprintf(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, NotArm)
  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 *DockerSuite) TestUserDefinedNetworkConnectDisconnectAlias(c *testing.T) {
  1250. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  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", "top")
  1285. assert.Assert(c, err != nil, fmt.Sprintf("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, fmt.Sprintf("out: %s", out))
  1290. assert.Assert(c, strings.Contains(out, runconfig.ErrUnsupportedNetworkAndAlias.Error()))
  1291. }
  1292. func (s *DockerSuite) 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 *DockerSuite) 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:jessie", "bash", "-c", "echo InvalidQuery > /dev/udp/127.0.0.11/53")
  1314. }
  1315. func (s *DockerSuite) 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 *DockerSuite) 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, strings.Contains(out, "100% packet loss"))
  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. s.d.StartWithBusybox(t, "--live-restore")
  1354. defer s.d.Stop(t)
  1355. oldCon := "old"
  1356. _, err := s.d.Cmd("run", "-d", "--name", oldCon, "-p", "80:80", "busybox", "top")
  1357. if err != nil {
  1358. t.Fatal(err)
  1359. }
  1360. oldContainerIP, err := s.d.Cmd("inspect", "-f", "{{ .NetworkSettings.Networks.bridge.IPAddress }}", oldCon)
  1361. if err != nil {
  1362. t.Fatal(err)
  1363. }
  1364. // Kill the daemon
  1365. if err := s.d.Kill(); err != nil {
  1366. t.Fatal(err)
  1367. }
  1368. // restart the daemon
  1369. s.d.Start(t, "--live-restore")
  1370. // start a new container, the new container's ip should not be the same with
  1371. // old running container.
  1372. newCon := "new"
  1373. _, err = s.d.Cmd("run", "-d", "--name", newCon, "busybox", "top")
  1374. if err != nil {
  1375. t.Fatal(err)
  1376. }
  1377. newContainerIP, err := s.d.Cmd("inspect", "-f", "{{ .NetworkSettings.Networks.bridge.IPAddress }}", newCon)
  1378. if err != nil {
  1379. t.Fatal(err)
  1380. }
  1381. if strings.Compare(strings.TrimSpace(oldContainerIP), strings.TrimSpace(newContainerIP)) == 0 {
  1382. t.Fatalf("new container ip should not equal to old running container ip")
  1383. }
  1384. // start a new container, the new container should ping old running container
  1385. _, err = s.d.Cmd("run", "-t", "busybox", "ping", "-c", "1", oldContainerIP)
  1386. if err != nil {
  1387. t.Fatal(err)
  1388. }
  1389. // start a new container, trying to publish port 80:80 should fail
  1390. out, err := s.d.Cmd("run", "-p", "80:80", "-d", "busybox", "top")
  1391. if err == nil || !strings.Contains(out, "Bind for 0.0.0.0:80 failed: port is already allocated") {
  1392. t.Fatalf("80 port is allocated to old running container, it should failed on allocating to new container")
  1393. }
  1394. // kill old running container and try to allocate again
  1395. _, err = s.d.Cmd("kill", oldCon)
  1396. if err != nil {
  1397. t.Fatal(err)
  1398. }
  1399. id, err := s.d.Cmd("run", "-p", "80:80", "-d", "busybox", "top")
  1400. if err != nil {
  1401. t.Fatal(err)
  1402. }
  1403. // Cleanup because these containers will not be shut down by daemon
  1404. out, err = s.d.Cmd("stop", newCon)
  1405. if err != nil {
  1406. t.Fatalf("err: %v %v", err, string(out))
  1407. }
  1408. _, err = s.d.Cmd("stop", strings.TrimSpace(id))
  1409. if err != nil {
  1410. t.Fatal(err)
  1411. }
  1412. }
  1413. func (s *DockerNetworkSuite) TestDockerNetworkFlagAlias(c *testing.T) {
  1414. dockerCmd(c, "network", "create", "user")
  1415. output, status := dockerCmd(c, "run", "--rm", "--network=user", "--network-alias=foo", "busybox", "true")
  1416. assert.Equal(c, status, 0, fmt.Sprintf("unexpected status code %d (%s)", status, output))
  1417. output, status, _ = dockerCmdWithError("run", "--rm", "--net=user", "--network=user", "busybox", "true")
  1418. assert.Equal(c, status, 0, fmt.Sprintf("unexpected status code %d (%s)", status, output))
  1419. output, status, _ = dockerCmdWithError("run", "--rm", "--network=user", "--net-alias=foo", "--network-alias=bar", "busybox", "true")
  1420. assert.Equal(c, status, 0, fmt.Sprintf("unexpected status code %d (%s)", status, output))
  1421. }
  1422. func (s *DockerNetworkSuite) TestDockerNetworkValidateIP(c *testing.T) {
  1423. _, _, err := dockerCmdWithError("network", "create", "--ipv6", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "mynet")
  1424. assert.NilError(c, err)
  1425. assertNwIsAvailable(c, "mynet")
  1426. _, _, err = dockerCmdWithError("run", "-d", "--name", "mynet0", "--net=mynet", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
  1427. assert.NilError(c, err)
  1428. assert.Assert(c, waitRun("mynet0") == nil)
  1429. verifyIPAddressConfig(c, "mynet0", "mynet", "172.28.99.88", "2001:db8:1234::9988")
  1430. verifyIPAddresses(c, "mynet0", "mynet", "172.28.99.88", "2001:db8:1234::9988")
  1431. _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip", "mynet_ip", "--ip6", "2001:db8:1234::9999", "busybox", "top")
  1432. assert.ErrorContains(c, err, "invalid IPv4 address")
  1433. _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip", "172.28.99.99", "--ip6", "mynet_ip6", "busybox", "top")
  1434. assert.ErrorContains(c, err, "invalid IPv6 address")
  1435. // This is a case of IPv4 address to `--ip6`
  1436. _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip6", "172.28.99.99", "busybox", "top")
  1437. assert.ErrorContains(c, err, "invalid IPv6 address")
  1438. // This is a special case of an IPv4-mapped IPv6 address
  1439. _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip6", "::ffff:172.28.99.99", "busybox", "top")
  1440. assert.ErrorContains(c, err, "invalid IPv6 address")
  1441. }
  1442. // Test case for 26220
  1443. func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromBridge(c *testing.T) {
  1444. out, _ := dockerCmd(c, "network", "inspect", "--format", "{{.Id}}", "bridge")
  1445. network := strings.TrimSpace(out)
  1446. name := "test"
  1447. dockerCmd(c, "create", "--name", name, "busybox", "top")
  1448. _, _, err := dockerCmdWithError("network", "disconnect", network, name)
  1449. assert.NilError(c, err)
  1450. }
  1451. // TestConntrackFlowsLeak covers the failure scenario of ticket: https://github.com/docker/docker/issues/8795
  1452. // Validates that conntrack is correctly cleaned once a container is destroyed
  1453. func (s *DockerNetworkSuite) TestConntrackFlowsLeak(c *testing.T) {
  1454. testRequires(c, IsAmd64, DaemonIsLinux, Network, testEnv.IsLocalDaemon)
  1455. // Create a new network
  1456. 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")
  1457. assertNwIsAvailable(c, "testbind")
  1458. // Launch the server, this will remain listening on an exposed port and reply to any request in a ping/pong fashion
  1459. cmd := "while true; do echo hello | nc -w 1 -lu 8080; done"
  1460. cli.DockerCmd(c, "run", "-d", "--name", "server", "--net", "testbind", "-p", "8080:8080/udp", "appropriate/nc", "sh", "-c", cmd)
  1461. // Launch a container client, here the objective is to create a flow that is natted in order to expose the bug
  1462. cmd = "echo world | nc -q 1 -u 192.168.10.1 8080"
  1463. cli.DockerCmd(c, "run", "-d", "--name", "client", "--net=host", "appropriate/nc", "sh", "-c", cmd)
  1464. // Get all the flows using netlink
  1465. flows, err := netlink.ConntrackTableList(netlink.ConntrackTable, unix.AF_INET)
  1466. assert.NilError(c, err)
  1467. var flowMatch int
  1468. for _, flow := range flows {
  1469. // count only the flows that we are interested in, skipping others that can be laying around the host
  1470. if flow.Forward.Protocol == unix.IPPROTO_UDP &&
  1471. flow.Forward.DstIP.Equal(net.ParseIP("192.168.10.1")) &&
  1472. flow.Forward.DstPort == 8080 {
  1473. flowMatch++
  1474. }
  1475. }
  1476. // The client should have created only 1 flow
  1477. assert.Equal(c, flowMatch, 1)
  1478. // Now delete the server, this will trigger the conntrack cleanup
  1479. cli.DockerCmd(c, "rm", "-fv", "server")
  1480. // Fetch again all the flows and validate that there is no server flow in the conntrack laying around
  1481. flows, err = netlink.ConntrackTableList(netlink.ConntrackTable, unix.AF_INET)
  1482. assert.NilError(c, err)
  1483. flowMatch = 0
  1484. for _, flow := range flows {
  1485. if flow.Forward.Protocol == unix.IPPROTO_UDP &&
  1486. flow.Forward.DstIP.Equal(net.ParseIP("192.168.10.1")) &&
  1487. flow.Forward.DstPort == 8080 {
  1488. flowMatch++
  1489. }
  1490. }
  1491. // All the flows have to be gone
  1492. assert.Equal(c, flowMatch, 0)
  1493. }