docker_cli_network_unix_test.go 66 KB

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