github.com/miqui/docker@v1.9.1/integration-cli/docker_cli_network_unix_test.go (about) 1 // +build !windows 2 3 package main 4 5 import ( 6 "encoding/json" 7 "fmt" 8 "io/ioutil" 9 "net" 10 "net/http" 11 "net/http/httptest" 12 "os" 13 "strings" 14 15 "github.com/docker/docker/api/types" 16 "github.com/docker/docker/api/types/versions/v1p20" 17 "github.com/docker/docker/pkg/integration/checker" 18 "github.com/docker/docker/runconfig" 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 28 const dummyNetworkDriver = "dummy-network-driver" 29 const dummyIpamDriver = "dummy-ipam-driver" 30 31 var remoteDriverNetworkRequest remoteapi.CreateNetworkRequest 32 33 func init() { 34 check.Suite(&DockerNetworkSuite{ 35 ds: &DockerSuite{}, 36 }) 37 } 38 39 type DockerNetworkSuite struct { 40 server *httptest.Server 41 ds *DockerSuite 42 d *Daemon 43 } 44 45 func (s *DockerNetworkSuite) SetUpTest(c *check.C) { 46 s.d = NewDaemon(c) 47 } 48 49 func (s *DockerNetworkSuite) TearDownTest(c *check.C) { 50 s.d.Stop() 51 s.ds.TearDownTest(c) 52 } 53 54 func (s *DockerNetworkSuite) SetUpSuite(c *check.C) { 55 mux := http.NewServeMux() 56 s.server = httptest.NewServer(mux) 57 c.Assert(s.server, check.NotNil, check.Commentf("Failed to start a HTTP Server")) 58 59 mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) { 60 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 61 fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType) 62 }) 63 64 // Network driver implementation 65 mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { 66 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 67 fmt.Fprintf(w, `{"Scope":"local"}`) 68 }) 69 70 mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { 71 err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest) 72 if err != nil { 73 http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest) 74 return 75 } 76 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 77 fmt.Fprintf(w, "null") 78 }) 79 80 mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { 81 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 82 fmt.Fprintf(w, "null") 83 }) 84 85 mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { 86 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 87 fmt.Fprintf(w, `{"Interface":{"MacAddress":"a0:b1:c2:d3:e4:f5"}}`) 88 }) 89 90 mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { 91 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 92 93 veth := &netlink.Veth{ 94 LinkAttrs: netlink.LinkAttrs{Name: "randomIfName", TxQLen: 0}, PeerName: "cnt0"} 95 if err := netlink.LinkAdd(veth); err != nil { 96 fmt.Fprintf(w, `{"Error":"failed to add veth pair: `+err.Error()+`"}`) 97 } else { 98 fmt.Fprintf(w, `{"InterfaceName":{ "SrcName":"cnt0", "DstPrefix":"veth"}}`) 99 } 100 }) 101 102 mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { 103 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 104 fmt.Fprintf(w, "null") 105 }) 106 107 mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { 108 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 109 if link, err := netlink.LinkByName("cnt0"); err == nil { 110 netlink.LinkDel(link) 111 } 112 fmt.Fprintf(w, "null") 113 }) 114 115 // Ipam Driver implementation 116 var ( 117 poolRequest remoteipam.RequestPoolRequest 118 poolReleaseReq remoteipam.ReleasePoolRequest 119 addressRequest remoteipam.RequestAddressRequest 120 addressReleaseReq remoteipam.ReleaseAddressRequest 121 lAS = "localAS" 122 gAS = "globalAS" 123 pool = "172.28.0.0/16" 124 poolID = lAS + "/" + pool 125 gw = "172.28.255.254/16" 126 ) 127 128 mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) { 129 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 130 fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`) 131 }) 132 133 mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) { 134 err := json.NewDecoder(r.Body).Decode(&poolRequest) 135 if err != nil { 136 http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest) 137 return 138 } 139 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 140 if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS { 141 fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`) 142 } else if poolRequest.Pool != "" && poolRequest.Pool != pool { 143 fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`) 144 } else { 145 fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`) 146 } 147 }) 148 149 mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) { 150 err := json.NewDecoder(r.Body).Decode(&addressRequest) 151 if err != nil { 152 http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest) 153 return 154 } 155 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 156 // make sure libnetwork is now querying on the expected pool id 157 if addressRequest.PoolID != poolID { 158 fmt.Fprintf(w, `{"Error":"unknown pool id"}`) 159 } else if addressRequest.Address != "" { 160 fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`) 161 } else { 162 fmt.Fprintf(w, `{"Address":"`+gw+`"}`) 163 } 164 }) 165 166 mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) { 167 err := json.NewDecoder(r.Body).Decode(&addressReleaseReq) 168 if err != nil { 169 http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest) 170 return 171 } 172 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 173 // make sure libnetwork is now asking to release the expected address fro mthe expected poolid 174 if addressRequest.PoolID != poolID { 175 fmt.Fprintf(w, `{"Error":"unknown pool id"}`) 176 } else if addressReleaseReq.Address != gw { 177 fmt.Fprintf(w, `{"Error":"unknown address"}`) 178 } else { 179 fmt.Fprintf(w, "null") 180 } 181 }) 182 183 mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) { 184 err := json.NewDecoder(r.Body).Decode(&poolReleaseReq) 185 if err != nil { 186 http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest) 187 return 188 } 189 w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") 190 // make sure libnetwork is now asking to release the expected poolid 191 if addressRequest.PoolID != poolID { 192 fmt.Fprintf(w, `{"Error":"unknown pool id"}`) 193 } else { 194 fmt.Fprintf(w, "null") 195 } 196 }) 197 198 err := os.MkdirAll("/etc/docker/plugins", 0755) 199 c.Assert(err, checker.IsNil) 200 201 fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", dummyNetworkDriver) 202 err = ioutil.WriteFile(fileName, []byte(s.server.URL), 0644) 203 c.Assert(err, checker.IsNil) 204 205 ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", dummyIpamDriver) 206 err = ioutil.WriteFile(ipamFileName, []byte(s.server.URL), 0644) 207 c.Assert(err, checker.IsNil) 208 } 209 210 func (s *DockerNetworkSuite) TearDownSuite(c *check.C) { 211 if s.server == nil { 212 return 213 } 214 215 s.server.Close() 216 217 err := os.RemoveAll("/etc/docker/plugins") 218 c.Assert(err, checker.IsNil) 219 } 220 221 func assertNwIsAvailable(c *check.C, name string) { 222 if !isNwPresent(c, name) { 223 c.Fatalf("Network %s not found in network ls o/p", name) 224 } 225 } 226 227 func assertNwNotAvailable(c *check.C, name string) { 228 if isNwPresent(c, name) { 229 c.Fatalf("Found network %s in network ls o/p", name) 230 } 231 } 232 233 func isNwPresent(c *check.C, name string) bool { 234 out, _ := dockerCmd(c, "network", "ls") 235 lines := strings.Split(out, "\n") 236 for i := 1; i < len(lines)-1; i++ { 237 if strings.Contains(lines[i], name) { 238 return true 239 } 240 } 241 return false 242 } 243 244 func getNwResource(c *check.C, name string) *types.NetworkResource { 245 out, _ := dockerCmd(c, "network", "inspect", name) 246 nr := []types.NetworkResource{} 247 err := json.Unmarshal([]byte(out), &nr) 248 c.Assert(err, check.IsNil) 249 return &nr[0] 250 } 251 252 func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) { 253 defaults := []string{"bridge", "host", "none"} 254 for _, nn := range defaults { 255 assertNwIsAvailable(c, nn) 256 } 257 } 258 259 func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *check.C) { 260 dockerCmd(c, "network", "create", "test") 261 assertNwIsAvailable(c, "test") 262 263 dockerCmd(c, "network", "rm", "test") 264 assertNwNotAvailable(c, "test") 265 } 266 267 func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) { 268 out, _ := dockerCmd(c, "network", "inspect", "host", "none") 269 networkResources := []types.NetworkResource{} 270 err := json.Unmarshal([]byte(out), &networkResources) 271 c.Assert(err, check.IsNil) 272 c.Assert(networkResources, checker.HasLen, 2) 273 274 // Should print an error, return an exitCode 1 *but* should print the host network 275 out, exitCode, err := dockerCmdWithError("network", "inspect", "host", "nonexistent") 276 c.Assert(err, checker.NotNil) 277 c.Assert(exitCode, checker.Equals, 1) 278 c.Assert(out, checker.Contains, "Error: No such network: nonexistent") 279 networkResources = []types.NetworkResource{} 280 inspectOut := strings.SplitN(out, "\n", 2)[1] 281 err = json.Unmarshal([]byte(inspectOut), &networkResources) 282 c.Assert(networkResources, checker.HasLen, 1) 283 284 // Should print an error and return an exitCode, nothing else 285 out, exitCode, err = dockerCmdWithError("network", "inspect", "nonexistent") 286 c.Assert(err, checker.NotNil) 287 c.Assert(exitCode, checker.Equals, 1) 288 c.Assert(out, checker.Contains, "Error: No such network: nonexistent") 289 } 290 291 func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) { 292 dockerCmd(c, "network", "create", "test") 293 assertNwIsAvailable(c, "test") 294 nr := getNwResource(c, "test") 295 296 c.Assert(nr.Name, checker.Equals, "test") 297 c.Assert(len(nr.Containers), checker.Equals, 0) 298 299 // run a container 300 out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top") 301 c.Assert(waitRun("test"), check.IsNil) 302 containerID := strings.TrimSpace(out) 303 304 // connect the container to the test network 305 dockerCmd(c, "network", "connect", "test", containerID) 306 307 // inspect the network to make sure container is connected 308 nr = getNetworkResource(c, nr.ID) 309 c.Assert(len(nr.Containers), checker.Equals, 1) 310 c.Assert(nr.Containers[containerID], check.NotNil) 311 312 // check if container IP matches network inspect 313 ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address) 314 c.Assert(err, check.IsNil) 315 containerIP := findContainerIP(c, "test", "test") 316 c.Assert(ip.String(), checker.Equals, containerIP) 317 318 // disconnect container from the network 319 dockerCmd(c, "network", "disconnect", "test", containerID) 320 nr = getNwResource(c, "test") 321 c.Assert(nr.Name, checker.Equals, "test") 322 c.Assert(len(nr.Containers), checker.Equals, 0) 323 324 // check if network connect fails for inactive containers 325 dockerCmd(c, "stop", containerID) 326 _, _, err = dockerCmdWithError("network", "connect", "test", containerID) 327 c.Assert(err, check.NotNil) 328 329 dockerCmd(c, "network", "rm", "test") 330 assertNwNotAvailable(c, "test") 331 } 332 333 func (s *DockerNetworkSuite) TestDockerNetworkIpamMultipleNetworks(c *check.C) { 334 // test0 bridge network 335 dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1") 336 assertNwIsAvailable(c, "test1") 337 338 // test2 bridge network does not overlap 339 dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2") 340 assertNwIsAvailable(c, "test2") 341 342 // for networks w/o ipam specified, docker will choose proper non-overlapping subnets 343 dockerCmd(c, "network", "create", "test3") 344 assertNwIsAvailable(c, "test3") 345 dockerCmd(c, "network", "create", "test4") 346 assertNwIsAvailable(c, "test4") 347 dockerCmd(c, "network", "create", "test5") 348 assertNwIsAvailable(c, "test5") 349 350 // test network with multiple subnets 351 // bridge network doesnt support multiple subnets. hence, use a dummy driver that supports 352 353 dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6") 354 assertNwIsAvailable(c, "test6") 355 356 // test network with multiple subnets with valid ipam combinations 357 // also check same subnet across networks when the driver supports it. 358 dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, 359 "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", 360 "--gateway=192.168.0.100", "--gateway=192.170.0.100", 361 "--ip-range=192.168.1.0/24", 362 "--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6", 363 "--aux-address", "a=192.170.1.5", "--aux-address", "b=192.170.1.6", 364 "test7") 365 assertNwIsAvailable(c, "test7") 366 367 // cleanup 368 for i := 1; i < 8; i++ { 369 dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i)) 370 } 371 } 372 373 func (s *DockerNetworkSuite) TestDockerNetworkCustomIpam(c *check.C) { 374 // Create a bridge network using custom ipam driver 375 dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "br0") 376 assertNwIsAvailable(c, "br0") 377 378 // Verify expected network ipam fields are there 379 nr := getNetworkResource(c, "br0") 380 c.Assert(nr.Driver, checker.Equals, "bridge") 381 c.Assert(nr.IPAM.Driver, checker.Equals, dummyIpamDriver) 382 383 // remove network and exercise remote ipam driver 384 dockerCmd(c, "network", "rm", "br0") 385 assertNwNotAvailable(c, "br0") 386 } 387 388 func (s *DockerNetworkSuite) TestDockerNetworkInspect(c *check.C) { 389 // if unspecified, network gateway will be selected from inside preferred pool 390 dockerCmd(c, "network", "create", "--driver=bridge", "--subnet=172.28.0.0/16", "--ip-range=172.28.5.0/24", "--gateway=172.28.5.254", "br0") 391 assertNwIsAvailable(c, "br0") 392 393 nr := getNetworkResource(c, "br0") 394 c.Assert(nr.Driver, checker.Equals, "bridge") 395 c.Assert(nr.Scope, checker.Equals, "local") 396 c.Assert(nr.IPAM.Driver, checker.Equals, "default") 397 c.Assert(len(nr.IPAM.Config), checker.Equals, 1) 398 c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16") 399 c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24") 400 c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254") 401 dockerCmd(c, "network", "rm", "br0") 402 } 403 404 func (s *DockerNetworkSuite) TestDockerNetworkIpamInvalidCombinations(c *check.C) { 405 // network with ip-range out of subnet range 406 _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test") 407 c.Assert(err, check.NotNil) 408 409 // network with multiple gateways for a single subnet 410 _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test") 411 c.Assert(err, check.NotNil) 412 413 // Multiple overlaping subnets in the same network must fail 414 _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test") 415 c.Assert(err, check.NotNil) 416 417 // overlapping subnets across networks must fail 418 // create a valid test0 network 419 dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0") 420 assertNwIsAvailable(c, "test0") 421 // create an overlapping test1 network 422 _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1") 423 c.Assert(err, check.NotNil) 424 dockerCmd(c, "network", "rm", "test0") 425 } 426 427 func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) { 428 dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt") 429 assertNwIsAvailable(c, "testopt") 430 gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData] 431 c.Assert(gopts, checker.NotNil) 432 opts, ok := gopts.(map[string]interface{}) 433 c.Assert(ok, checker.Equals, true) 434 c.Assert(opts["opt1"], checker.Equals, "drv1") 435 c.Assert(opts["opt2"], checker.Equals, "drv2") 436 dockerCmd(c, "network", "rm", "testopt") 437 438 } 439 440 func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *check.C) { 441 // On default bridge network built-in service discovery should not happen 442 hostsFile := "/etc/hosts" 443 bridgeName := "external-bridge" 444 bridgeIP := "192.169.255.254/24" 445 out, err := createInterface(c, "bridge", bridgeName, bridgeIP) 446 c.Assert(err, check.IsNil, check.Commentf(out)) 447 defer deleteInterface(c, bridgeName) 448 449 err = s.d.StartWithBusybox("--bridge", bridgeName) 450 c.Assert(err, check.IsNil) 451 defer s.d.Restart() 452 453 // run two containers and store first container's etc/hosts content 454 out, err = s.d.Cmd("run", "-d", "busybox", "top") 455 c.Assert(err, check.IsNil) 456 cid1 := strings.TrimSpace(out) 457 defer s.d.Cmd("stop", cid1) 458 459 hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile) 460 c.Assert(err, checker.IsNil) 461 462 out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top") 463 c.Assert(err, check.IsNil) 464 cid2 := strings.TrimSpace(out) 465 466 // verify first container's etc/hosts file has not changed after spawning the second named container 467 hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile) 468 c.Assert(err, checker.IsNil) 469 c.Assert(string(hosts), checker.Equals, string(hostsPost), 470 check.Commentf("Unexpected %s change on second container creation", hostsFile)) 471 472 // stop container 2 and verify first container's etc/hosts has not changed 473 _, err = s.d.Cmd("stop", cid2) 474 c.Assert(err, check.IsNil) 475 476 hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile) 477 c.Assert(err, checker.IsNil) 478 c.Assert(string(hosts), checker.Equals, string(hostsPost), 479 check.Commentf("Unexpected %s change on second container creation", hostsFile)) 480 481 // but discovery is on when connecting to non default bridge network 482 network := "anotherbridge" 483 out, err = s.d.Cmd("network", "create", network) 484 c.Assert(err, check.IsNil, check.Commentf(out)) 485 defer s.d.Cmd("network", "rm", network) 486 487 out, err = s.d.Cmd("network", "connect", network, cid1) 488 c.Assert(err, check.IsNil, check.Commentf(out)) 489 490 hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile) 491 c.Assert(err, checker.IsNil) 492 c.Assert(string(hosts), checker.Equals, string(hostsPost), 493 check.Commentf("Unexpected %s change on second network connection", hostsFile)) 494 495 cName := "container3" 496 out, err = s.d.Cmd("run", "-d", "--net", network, "--name", cName, "busybox", "top") 497 c.Assert(err, check.IsNil, check.Commentf(out)) 498 cid3 := strings.TrimSpace(out) 499 defer s.d.Cmd("stop", cid3) 500 501 // container1 etc/hosts file should contain an entry for the third container 502 hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile) 503 c.Assert(err, checker.IsNil) 504 c.Assert(string(hostsPost), checker.Contains, cName, 505 check.Commentf("Container 1 %s file does not contain entries for named container %q: %s", hostsFile, cName, string(hostsPost))) 506 507 // on container3 disconnect, first container's etc/hosts should go back to original form 508 out, err = s.d.Cmd("network", "disconnect", network, cid3) 509 c.Assert(err, check.IsNil, check.Commentf(out)) 510 511 hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile) 512 c.Assert(err, checker.IsNil) 513 c.Assert(string(hosts), checker.Equals, string(hostsPost), 514 check.Commentf("Unexpected %s content after disconnecting from second network", hostsFile)) 515 } 516 517 func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) { 518 hostsFile := "/etc/hosts" 519 cstmBridgeNw := "custom-bridge-nw" 520 cstmBridgeNw1 := "custom-bridge-nw1" 521 522 dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw) 523 assertNwIsAvailable(c, cstmBridgeNw) 524 525 // run two anonymous containers and store their etc/hosts content 526 out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top") 527 cid1 := strings.TrimSpace(out) 528 529 hosts1, err := readContainerFileWithExec(cid1, hostsFile) 530 c.Assert(err, checker.IsNil) 531 532 out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top") 533 cid2 := strings.TrimSpace(out) 534 535 hosts2, err := readContainerFileWithExec(cid2, hostsFile) 536 c.Assert(err, checker.IsNil) 537 538 // verify first container etc/hosts file has not changed 539 hosts1post, err := readContainerFileWithExec(cid1, hostsFile) 540 c.Assert(err, checker.IsNil) 541 c.Assert(string(hosts1), checker.Equals, string(hosts1post), 542 check.Commentf("Unexpected %s change on anonymous container creation", hostsFile)) 543 544 // Connect the 2nd container to a new network and verify the 545 // first container /etc/hosts file still hasn't changed. 546 dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1) 547 assertNwIsAvailable(c, cstmBridgeNw1) 548 549 dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2) 550 551 hosts1post, err = readContainerFileWithExec(cid1, hostsFile) 552 c.Assert(err, checker.IsNil) 553 c.Assert(string(hosts1), checker.Equals, string(hosts1post), 554 check.Commentf("Unexpected %s change on container connect", hostsFile)) 555 556 // start a named container 557 cName := "AnyName" 558 out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top") 559 cid3 := strings.TrimSpace(out) 560 561 // verify etc/hosts file for first two containers contains the named container entry 562 hosts1post, err = readContainerFileWithExec(cid1, hostsFile) 563 c.Assert(err, checker.IsNil) 564 c.Assert(string(hosts1post), checker.Contains, cName, 565 check.Commentf("Container 1 %s file does not contain entries for named container %q: %s", hostsFile, cName, string(hosts1post))) 566 567 hosts2post, err := readContainerFileWithExec(cid2, hostsFile) 568 c.Assert(err, checker.IsNil) 569 c.Assert(string(hosts2post), checker.Contains, cName, 570 check.Commentf("Container 2 %s file does not contain entries for named container %q: %s", hostsFile, cName, string(hosts2post))) 571 572 // Stop named container and verify first two containers' etc/hosts entries are back to original 573 dockerCmd(c, "stop", cid3) 574 hosts1post, err = readContainerFileWithExec(cid1, hostsFile) 575 c.Assert(err, checker.IsNil) 576 c.Assert(string(hosts1), checker.Equals, string(hosts1post), 577 check.Commentf("Unexpected %s change on anonymous container creation", hostsFile)) 578 579 hosts2post, err = readContainerFileWithExec(cid2, hostsFile) 580 c.Assert(err, checker.IsNil) 581 c.Assert(string(hosts2), checker.Equals, string(hosts2post), 582 check.Commentf("Unexpected %s change on anonymous container creation", hostsFile)) 583 } 584 585 func (s *DockerNetworkSuite) TestDockerNetworkLinkOndefaultNetworkOnly(c *check.C) { 586 // Link feature must work only on default network, and not across networks 587 cnt1 := "container1" 588 cnt2 := "container2" 589 network := "anotherbridge" 590 591 // Run first container on default network 592 dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top") 593 594 // Create another network and run the second container on it 595 dockerCmd(c, "network", "create", network) 596 assertNwIsAvailable(c, network) 597 dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top") 598 599 // Try launching a container on default network, linking to the first container. Must succeed 600 dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top") 601 602 // Try launching a container on default network, linking to the second container. Must fail 603 _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top") 604 c.Assert(err, checker.NotNil) 605 606 // Connect second container to default network. Now a container on default network can link to it 607 dockerCmd(c, "network", "connect", "bridge", cnt2) 608 dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top") 609 } 610 611 func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) { 612 // Verify exposed ports are present in ps output when running a container on 613 // a network managed by a driver which does not provide the default gateway 614 // for the container 615 nwn := "ov" 616 ctn := "bb" 617 port1 := 80 618 port2 := 443 619 expose1 := fmt.Sprintf("--expose=%d", port1) 620 expose2 := fmt.Sprintf("--expose=%d", port2) 621 622 dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn) 623 assertNwIsAvailable(c, nwn) 624 625 dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top") 626 627 // Check docker ps o/p for last created container reports the unpublished ports 628 unpPort1 := fmt.Sprintf("%d/tcp", port1) 629 unpPort2 := fmt.Sprintf("%d/tcp", port2) 630 out, _ := dockerCmd(c, "ps", "-n=1") 631 // Missing unpublished ports in docker ps output 632 c.Assert(out, checker.Contains, unpPort1) 633 // Missing unpublished ports in docker ps output 634 c.Assert(out, checker.Contains, unpPort2) 635 } 636 637 func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) { 638 // Verify endpoint MAC address is correctly populated in container's network settings 639 nwn := "ov" 640 ctn := "bb" 641 642 dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn) 643 assertNwIsAvailable(c, nwn) 644 645 dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top") 646 647 mac, err := inspectField(ctn, "NetworkSettings.Networks."+nwn+".MacAddress") 648 c.Assert(err, checker.IsNil) 649 c.Assert(mac, checker.Equals, "a0:b1:c2:d3:e4:f5") 650 } 651 652 func (s *DockerSuite) TestInspectApiMultipeNetworks(c *check.C) { 653 dockerCmd(c, "network", "create", "mybridge1") 654 dockerCmd(c, "network", "create", "mybridge2") 655 out, _ := dockerCmd(c, "run", "-d", "busybox", "top") 656 id := strings.TrimSpace(out) 657 c.Assert(waitRun(id), check.IsNil) 658 659 dockerCmd(c, "network", "connect", "mybridge1", id) 660 dockerCmd(c, "network", "connect", "mybridge2", id) 661 662 body := getInspectBody(c, "v1.20", id) 663 var inspect120 v1p20.ContainerJSON 664 err := json.Unmarshal(body, &inspect120) 665 c.Assert(err, checker.IsNil) 666 667 versionedIP := inspect120.NetworkSettings.IPAddress 668 669 body = getInspectBody(c, "v1.21", id) 670 var inspect121 types.ContainerJSON 671 err = json.Unmarshal(body, &inspect121) 672 c.Assert(err, checker.IsNil) 673 c.Assert(inspect121.NetworkSettings.Networks, checker.HasLen, 3) 674 675 bridge := inspect121.NetworkSettings.Networks["bridge"] 676 c.Assert(bridge.IPAddress, checker.Equals, versionedIP) 677 c.Assert(bridge.IPAddress, checker.Equals, inspect121.NetworkSettings.IPAddress) 678 } 679 680 func connectContainerToNetworks(c *check.C, d *Daemon, cName string, nws []string) { 681 // Run a container on the default network 682 out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top") 683 c.Assert(err, checker.IsNil, check.Commentf(out)) 684 685 // Attach the container to other three networks 686 for _, nw := range nws { 687 out, err = d.Cmd("network", "create", nw) 688 c.Assert(err, checker.IsNil, check.Commentf(out)) 689 out, err = d.Cmd("network", "connect", nw, cName) 690 c.Assert(err, checker.IsNil, check.Commentf(out)) 691 } 692 } 693 694 func verifyContainerIsConnectedToNetworks(c *check.C, d *Daemon, cName string, nws []string) { 695 // Verify container is connected to all three networks 696 for _, nw := range nws { 697 out, err := d.Cmd("inspect", "-f", fmt.Sprintf("{{.NetworkSettings.Networks.%s}}", nw), cName) 698 c.Assert(err, checker.IsNil, check.Commentf(out)) 699 c.Assert(out, checker.Not(checker.Equals), "<no value>\n") 700 } 701 } 702 703 func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRestart(c *check.C) { 704 cName := "bb" 705 nwList := []string{"nw1", "nw2", "nw3"} 706 707 s.d.Start() 708 709 connectContainerToNetworks(c, s.d, cName, nwList) 710 verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList) 711 712 // Reload daemon 713 s.d.Restart() 714 715 _, err := s.d.Cmd("start", cName) 716 c.Assert(err, checker.IsNil) 717 718 verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList) 719 } 720 721 func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksUngracefulDaemonRestart(c *check.C) { 722 cName := "cc" 723 nwList := []string{"nw1", "nw2", "nw3"} 724 725 s.d.Start() 726 727 connectContainerToNetworks(c, s.d, cName, nwList) 728 verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList) 729 730 // Kill daemon and restart 731 if err := s.d.cmd.Process.Kill(); err != nil { 732 c.Fatal(err) 733 } 734 s.d.Restart() 735 736 // Restart container 737 _, err := s.d.Cmd("start", cName) 738 c.Assert(err, checker.IsNil) 739 740 verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList) 741 } 742 743 func (s *DockerNetworkSuite) TestDockerNetworkRunNetByID(c *check.C) { 744 out, _ := dockerCmd(c, "network", "create", "one") 745 dockerCmd(c, "run", "-d", "--net", strings.TrimSpace(out), "busybox", "top") 746 } 747 748 func (s *DockerNetworkSuite) TestDockerNetworkConnectToHostFromOtherNetwork(c *check.C) { 749 dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") 750 c.Assert(waitRun("container1"), check.IsNil) 751 dockerCmd(c, "network", "disconnect", "bridge", "container1") 752 out, _, err := dockerCmdWithError("network", "connect", "host", "container1") 753 c.Assert(err, checker.NotNil, check.Commentf(out)) 754 c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error()) 755 } 756 757 func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromHost(c *check.C) { 758 dockerCmd(c, "run", "-d", "--name", "container1", "--net=host", "busybox", "top") 759 c.Assert(waitRun("container1"), check.IsNil) 760 out, _, err := dockerCmdWithError("network", "disconnect", "host", "container1") 761 c.Assert(err, checker.NotNil, check.Commentf("Should err out disconnect from host")) 762 c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error()) 763 } 764 765 func (s *DockerNetworkSuite) TestDockerNetworkConnectWithPortMapping(c *check.C) { 766 dockerCmd(c, "network", "create", "test1") 767 dockerCmd(c, "run", "-d", "--name", "c1", "-p", "5000:5000", "busybox", "top") 768 c.Assert(waitRun("c1"), check.IsNil) 769 dockerCmd(c, "network", "connect", "test1", "c1") 770 } 771 772 func (s *DockerNetworkSuite) TestDockerNetworkConnectWithMac(c *check.C) { 773 macAddress := "02:42:ac:11:00:02" 774 dockerCmd(c, "network", "create", "mynetwork") 775 dockerCmd(c, "run", "--name=test", "-d", "--mac-address", macAddress, "busybox", "top") 776 c.Assert(waitRun("test"), check.IsNil) 777 mac1, err := inspectField("test", "NetworkSettings.Networks.bridge.MacAddress") 778 c.Assert(err, checker.IsNil) 779 c.Assert(strings.TrimSpace(mac1), checker.Equals, macAddress) 780 dockerCmd(c, "network", "connect", "mynetwork", "test") 781 mac2, err := inspectField("test", "NetworkSettings.Networks.mynetwork.MacAddress") 782 c.Assert(err, checker.IsNil) 783 c.Assert(strings.TrimSpace(mac2), checker.Not(checker.Equals), strings.TrimSpace(mac1)) 784 }