docker_cli_network_unix_test.go 71 KB

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