docker_cli_network_unix_test.go 71 KB

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