docker_cli_network_unix_test.go 71 KB

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