docker_cli_network_unix_test.go 65 KB

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