github.com/rita33cool1/iot-system-gateway@v0.0.0-20200911033302-e65bde238cc5/docker-engine/integration-cli/docker_cli_run_test.go (about) 1 package main 2 3 import ( 4 "bufio" 5 "bytes" 6 "encoding/json" 7 "fmt" 8 "io" 9 "io/ioutil" 10 "net" 11 "os" 12 "os/exec" 13 "path" 14 "path/filepath" 15 "reflect" 16 "regexp" 17 "runtime" 18 "sort" 19 "strconv" 20 "strings" 21 "sync" 22 "time" 23 24 "github.com/docker/docker/client" 25 "github.com/docker/docker/integration-cli/checker" 26 "github.com/docker/docker/integration-cli/cli" 27 "github.com/docker/docker/integration-cli/cli/build" 28 "github.com/docker/docker/internal/test/fakecontext" 29 "github.com/docker/docker/internal/testutil" 30 "github.com/docker/docker/pkg/mount" 31 "github.com/docker/docker/pkg/parsers/kernel" 32 "github.com/docker/docker/pkg/stringid" 33 "github.com/docker/docker/runconfig" 34 "github.com/docker/go-connections/nat" 35 "github.com/docker/libnetwork/resolvconf" 36 "github.com/docker/libnetwork/types" 37 "github.com/go-check/check" 38 "github.com/gotestyourself/gotestyourself/icmd" 39 "golang.org/x/net/context" 40 ) 41 42 // "test123" should be printed by docker run 43 func (s *DockerSuite) TestRunEchoStdout(c *check.C) { 44 out, _ := dockerCmd(c, "run", "busybox", "echo", "test123") 45 if out != "test123\n" { 46 c.Fatalf("container should've printed 'test123', got '%s'", out) 47 } 48 } 49 50 // "test" should be printed 51 func (s *DockerSuite) TestRunEchoNamedContainer(c *check.C) { 52 out, _ := dockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test") 53 if out != "test\n" { 54 c.Errorf("container should've printed 'test'") 55 } 56 } 57 58 // docker run should not leak file descriptors. This test relies on Unix 59 // specific functionality and cannot run on Windows. 60 func (s *DockerSuite) TestRunLeakyFileDescriptors(c *check.C) { 61 testRequires(c, DaemonIsLinux) 62 out, _ := dockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd") 63 64 // normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory 65 if out != "0 1 2 3\n" { 66 c.Errorf("container should've printed '0 1 2 3', not: %s", out) 67 } 68 } 69 70 // it should be possible to lookup Google DNS 71 // this will fail when Internet access is unavailable 72 func (s *DockerSuite) TestRunLookupGoogleDNS(c *check.C) { 73 testRequires(c, Network, NotArm) 74 if testEnv.OSType == "windows" { 75 // nslookup isn't present in Windows busybox. Is built-in. Further, 76 // nslookup isn't present in nanoserver. Hence just use PowerShell... 77 dockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "powershell", "Resolve-DNSName", "google.com") 78 } else { 79 dockerCmd(c, "run", "busybox", "nslookup", "google.com") 80 } 81 82 } 83 84 // the exit code should be 0 85 func (s *DockerSuite) TestRunExitCodeZero(c *check.C) { 86 dockerCmd(c, "run", "busybox", "true") 87 } 88 89 // the exit code should be 1 90 func (s *DockerSuite) TestRunExitCodeOne(c *check.C) { 91 _, exitCode, err := dockerCmdWithError("run", "busybox", "false") 92 c.Assert(err, checker.NotNil) 93 c.Assert(exitCode, checker.Equals, 1) 94 } 95 96 // it should be possible to pipe in data via stdin to a process running in a container 97 func (s *DockerSuite) TestRunStdinPipe(c *check.C) { 98 // TODO Windows: This needs some work to make compatible. 99 testRequires(c, DaemonIsLinux) 100 result := icmd.RunCmd(icmd.Cmd{ 101 Command: []string{dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat"}, 102 Stdin: strings.NewReader("blahblah"), 103 }) 104 result.Assert(c, icmd.Success) 105 out := result.Stdout() 106 107 out = strings.TrimSpace(out) 108 dockerCmd(c, "wait", out) 109 110 logsOut, _ := dockerCmd(c, "logs", out) 111 112 containerLogs := strings.TrimSpace(logsOut) 113 if containerLogs != "blahblah" { 114 c.Errorf("logs didn't print the container's logs %s", containerLogs) 115 } 116 117 dockerCmd(c, "rm", out) 118 } 119 120 // the container's ID should be printed when starting a container in detached mode 121 func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *check.C) { 122 out, _ := dockerCmd(c, "run", "-d", "busybox", "true") 123 124 out = strings.TrimSpace(out) 125 dockerCmd(c, "wait", out) 126 127 rmOut, _ := dockerCmd(c, "rm", out) 128 129 rmOut = strings.TrimSpace(rmOut) 130 if rmOut != out { 131 c.Errorf("rm didn't print the container ID %s %s", out, rmOut) 132 } 133 } 134 135 // the working directory should be set correctly 136 func (s *DockerSuite) TestRunWorkingDirectory(c *check.C) { 137 dir := "/root" 138 image := "busybox" 139 if testEnv.OSType == "windows" { 140 dir = `C:/Windows` 141 } 142 143 // First with -w 144 out, _ := dockerCmd(c, "run", "-w", dir, image, "pwd") 145 out = strings.TrimSpace(out) 146 if out != dir { 147 c.Errorf("-w failed to set working directory") 148 } 149 150 // Then with --workdir 151 out, _ = dockerCmd(c, "run", "--workdir", dir, image, "pwd") 152 out = strings.TrimSpace(out) 153 if out != dir { 154 c.Errorf("--workdir failed to set working directory") 155 } 156 } 157 158 // pinging Google's DNS resolver should fail when we disable the networking 159 func (s *DockerSuite) TestRunWithoutNetworking(c *check.C) { 160 count := "-c" 161 image := "busybox" 162 if testEnv.OSType == "windows" { 163 count = "-n" 164 image = testEnv.PlatformDefaults.BaseImage 165 } 166 167 // First using the long form --net 168 out, exitCode, err := dockerCmdWithError("run", "--net=none", image, "ping", count, "1", "8.8.8.8") 169 if err != nil && exitCode != 1 { 170 c.Fatal(out, err) 171 } 172 if exitCode != 1 { 173 c.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8") 174 } 175 } 176 177 //test --link use container name to link target 178 func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *check.C) { 179 // TODO Windows: This test cannot run on a Windows daemon as the networking 180 // settings are not populated back yet on inspect. 181 testRequires(c, DaemonIsLinux) 182 dockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox") 183 184 ip := inspectField(c, "parent", "NetworkSettings.Networks.bridge.IPAddress") 185 186 out, _ := dockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts") 187 if !strings.Contains(out, ip+" test") { 188 c.Fatalf("use a container name to link target failed") 189 } 190 } 191 192 //test --link use container id to link target 193 func (s *DockerSuite) TestRunLinksContainerWithContainerID(c *check.C) { 194 // TODO Windows: This test cannot run on a Windows daemon as the networking 195 // settings are not populated back yet on inspect. 196 testRequires(c, DaemonIsLinux) 197 cID, _ := dockerCmd(c, "run", "-i", "-t", "-d", "busybox") 198 199 cID = strings.TrimSpace(cID) 200 ip := inspectField(c, cID, "NetworkSettings.Networks.bridge.IPAddress") 201 202 out, _ := dockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts") 203 if !strings.Contains(out, ip+" test") { 204 c.Fatalf("use a container id to link target failed") 205 } 206 } 207 208 func (s *DockerSuite) TestUserDefinedNetworkLinks(c *check.C) { 209 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 210 dockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet") 211 212 dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top") 213 c.Assert(waitRun("first"), check.IsNil) 214 215 // run a container in user-defined network udlinkNet with a link for an existing container 216 // and a link for a container that doesn't exist 217 dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo", 218 "--link=third:bar", "busybox", "top") 219 c.Assert(waitRun("second"), check.IsNil) 220 221 // ping to first and its alias foo must succeed 222 _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 223 c.Assert(err, check.IsNil) 224 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") 225 c.Assert(err, check.IsNil) 226 227 // ping to third and its alias must fail 228 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third") 229 c.Assert(err, check.NotNil) 230 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar") 231 c.Assert(err, check.NotNil) 232 233 // start third container now 234 dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=third", "busybox", "top") 235 c.Assert(waitRun("third"), check.IsNil) 236 237 // ping to third and its alias must succeed now 238 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third") 239 c.Assert(err, check.IsNil) 240 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar") 241 c.Assert(err, check.IsNil) 242 } 243 244 func (s *DockerSuite) TestUserDefinedNetworkLinksWithRestart(c *check.C) { 245 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 246 dockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet") 247 248 dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top") 249 c.Assert(waitRun("first"), check.IsNil) 250 251 dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo", 252 "busybox", "top") 253 c.Assert(waitRun("second"), check.IsNil) 254 255 // ping to first and its alias foo must succeed 256 _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 257 c.Assert(err, check.IsNil) 258 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") 259 c.Assert(err, check.IsNil) 260 261 // Restart first container 262 dockerCmd(c, "restart", "first") 263 c.Assert(waitRun("first"), check.IsNil) 264 265 // ping to first and its alias foo must still succeed 266 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 267 c.Assert(err, check.IsNil) 268 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") 269 c.Assert(err, check.IsNil) 270 271 // Restart second container 272 dockerCmd(c, "restart", "second") 273 c.Assert(waitRun("second"), check.IsNil) 274 275 // ping to first and its alias foo must still succeed 276 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 277 c.Assert(err, check.IsNil) 278 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") 279 c.Assert(err, check.IsNil) 280 } 281 282 func (s *DockerSuite) TestRunWithNetAliasOnDefaultNetworks(c *check.C) { 283 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 284 285 defaults := []string{"bridge", "host", "none"} 286 for _, net := range defaults { 287 out, _, err := dockerCmdWithError("run", "-d", "--net", net, "--net-alias", "alias_"+net, "busybox", "top") 288 c.Assert(err, checker.NotNil) 289 c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error()) 290 } 291 } 292 293 func (s *DockerSuite) TestUserDefinedNetworkAlias(c *check.C) { 294 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 295 dockerCmd(c, "network", "create", "-d", "bridge", "net1") 296 297 cid1, _ := dockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo1", "--net-alias=foo2", "busybox:glibc", "top") 298 c.Assert(waitRun("first"), check.IsNil) 299 300 // Check if default short-id alias is added automatically 301 id := strings.TrimSpace(cid1) 302 aliases := inspectField(c, id, "NetworkSettings.Networks.net1.Aliases") 303 c.Assert(aliases, checker.Contains, stringid.TruncateID(id)) 304 305 cid2, _ := dockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox:glibc", "top") 306 c.Assert(waitRun("second"), check.IsNil) 307 308 // Check if default short-id alias is added automatically 309 id = strings.TrimSpace(cid2) 310 aliases = inspectField(c, id, "NetworkSettings.Networks.net1.Aliases") 311 c.Assert(aliases, checker.Contains, stringid.TruncateID(id)) 312 313 // ping to first and its network-scoped aliases 314 _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 315 c.Assert(err, check.IsNil) 316 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1") 317 c.Assert(err, check.IsNil) 318 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2") 319 c.Assert(err, check.IsNil) 320 // ping first container's short-id alias 321 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid1)) 322 c.Assert(err, check.IsNil) 323 324 // Restart first container 325 dockerCmd(c, "restart", "first") 326 c.Assert(waitRun("first"), check.IsNil) 327 328 // ping to first and its network-scoped aliases must succeed 329 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 330 c.Assert(err, check.IsNil) 331 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1") 332 c.Assert(err, check.IsNil) 333 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2") 334 c.Assert(err, check.IsNil) 335 // ping first container's short-id alias 336 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid1)) 337 c.Assert(err, check.IsNil) 338 } 339 340 // Issue 9677. 341 func (s *DockerSuite) TestRunWithDaemonFlags(c *check.C) { 342 out, _, err := dockerCmdWithError("--exec-opt", "foo=bar", "run", "-i", "busybox", "true") 343 c.Assert(err, checker.NotNil) 344 c.Assert(out, checker.Contains, "unknown flag: --exec-opt") 345 } 346 347 // Regression test for #4979 348 func (s *DockerSuite) TestRunWithVolumesFromExited(c *check.C) { 349 350 var ( 351 out string 352 exitCode int 353 ) 354 355 // Create a file in a volume 356 if testEnv.OSType == "windows" { 357 out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", `c:\some\dir`, testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `echo hello > c:\some\dir\file`) 358 } else { 359 out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file") 360 } 361 if exitCode != 0 { 362 c.Fatal("1", out, exitCode) 363 } 364 365 // Read the file from another container using --volumes-from to access the volume in the second container 366 if testEnv.OSType == "windows" { 367 out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `type c:\some\dir\file`) 368 } else { 369 out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file") 370 } 371 if exitCode != 0 { 372 c.Fatal("2", out, exitCode) 373 } 374 } 375 376 // Volume path is a symlink which also exists on the host, and the host side is a file not a dir 377 // But the volume call is just a normal volume, not a bind mount 378 func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) { 379 var ( 380 dockerFile string 381 containerPath string 382 cmd string 383 ) 384 // This test cannot run on a Windows daemon as 385 // Windows does not support symlinks inside a volume path 386 testRequires(c, SameHostDaemon, DaemonIsLinux) 387 name := "test-volume-symlink" 388 389 dir, err := ioutil.TempDir("", name) 390 if err != nil { 391 c.Fatal(err) 392 } 393 defer os.RemoveAll(dir) 394 395 // In the case of Windows to Windows CI, if the machine is setup so that 396 // the temp directory is not the C: drive, this test is invalid and will 397 // not work. 398 if testEnv.OSType == "windows" && strings.ToLower(dir[:1]) != "c" { 399 c.Skip("Requires TEMP to point to C: drive") 400 } 401 402 f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0700) 403 if err != nil { 404 c.Fatal(err) 405 } 406 f.Close() 407 408 if testEnv.OSType == "windows" { 409 dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir %s\nRUN mklink /D c:\\test %s", testEnv.PlatformDefaults.BaseImage, dir, dir) 410 containerPath = `c:\test\test` 411 cmd = "tasklist" 412 } else { 413 dockerFile = fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir) 414 containerPath = "/test/test" 415 cmd = "true" 416 } 417 buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile)) 418 dockerCmd(c, "run", "-v", containerPath, name, cmd) 419 } 420 421 // Volume path is a symlink in the container 422 func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir2(c *check.C) { 423 var ( 424 dockerFile string 425 containerPath string 426 cmd string 427 ) 428 // This test cannot run on a Windows daemon as 429 // Windows does not support symlinks inside a volume path 430 testRequires(c, SameHostDaemon, DaemonIsLinux) 431 name := "test-volume-symlink2" 432 433 if testEnv.OSType == "windows" { 434 dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir c:\\%s\nRUN mklink /D c:\\test c:\\%s", testEnv.PlatformDefaults.BaseImage, name, name) 435 containerPath = `c:\test\test` 436 cmd = "tasklist" 437 } else { 438 dockerFile = fmt.Sprintf("FROM busybox\nRUN mkdir -p /%s\nRUN ln -s /%s /test", name, name) 439 containerPath = "/test/test" 440 cmd = "true" 441 } 442 buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile)) 443 dockerCmd(c, "run", "-v", containerPath, name, cmd) 444 } 445 446 func (s *DockerSuite) TestRunVolumesMountedAsReadonly(c *check.C) { 447 if _, code, err := dockerCmdWithError("run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile"); err == nil || code == 0 { 448 c.Fatalf("run should fail because volume is ro: exit code %d", code) 449 } 450 } 451 452 func (s *DockerSuite) TestRunVolumesFromInReadonlyModeFails(c *check.C) { 453 var ( 454 volumeDir string 455 fileInVol string 456 ) 457 if testEnv.OSType == "windows" { 458 volumeDir = `c:/test` // Forward-slash as using busybox 459 fileInVol = `c:/test/file` 460 } else { 461 testRequires(c, DaemonIsLinux) 462 volumeDir = "/test" 463 fileInVol = `/test/file` 464 } 465 dockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true") 466 467 if _, code, err := dockerCmdWithError("run", "--volumes-from", "parent:ro", "busybox", "touch", fileInVol); err == nil || code == 0 { 468 c.Fatalf("run should fail because volume is ro: exit code %d", code) 469 } 470 } 471 472 // Regression test for #1201 473 func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) { 474 var ( 475 volumeDir string 476 fileInVol string 477 ) 478 if testEnv.OSType == "windows" { 479 volumeDir = `c:/test` // Forward-slash as using busybox 480 fileInVol = `c:/test/file` 481 } else { 482 volumeDir = "/test" 483 fileInVol = "/test/file" 484 } 485 486 dockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true") 487 dockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", fileInVol) 488 489 if out, _, err := dockerCmdWithError("run", "--volumes-from", "parent:bar", "busybox", "touch", fileInVol); err == nil || !strings.Contains(out, `invalid mode: bar`) { 490 c.Fatalf("running --volumes-from parent:bar should have failed with invalid mode: %q", out) 491 } 492 493 dockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", fileInVol) 494 } 495 496 func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) { 497 testRequires(c, SameHostDaemon) 498 prefix, slash := getPrefixAndSlashFromDaemonPlatform() 499 hostpath := RandomTmpDirPath("test", testEnv.OSType) 500 if err := os.MkdirAll(hostpath, 0755); err != nil { 501 c.Fatalf("Failed to create %s: %q", hostpath, err) 502 } 503 defer os.RemoveAll(hostpath) 504 505 dockerCmd(c, "run", "--name", "parent", "-v", hostpath+":"+prefix+slash+"test:ro", "busybox", "true") 506 507 // Expect this "rw" mode to be be ignored since the inherited volume is "ro" 508 if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent:rw", "busybox", "touch", prefix+slash+"test"+slash+"file"); err == nil { 509 c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`") 510 } 511 512 dockerCmd(c, "run", "--name", "parent2", "-v", hostpath+":"+prefix+slash+"test:ro", "busybox", "true") 513 514 // Expect this to be read-only since both are "ro" 515 if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent2:ro", "busybox", "touch", prefix+slash+"test"+slash+"file"); err == nil { 516 c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`") 517 } 518 } 519 520 // Test for GH#10618 521 func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) { 522 path1 := RandomTmpDirPath("test1", testEnv.OSType) 523 path2 := RandomTmpDirPath("test2", testEnv.OSType) 524 525 someplace := ":/someplace" 526 if testEnv.OSType == "windows" { 527 // Windows requires that the source directory exists before calling HCS 528 testRequires(c, SameHostDaemon) 529 someplace = `:c:\someplace` 530 if err := os.MkdirAll(path1, 0755); err != nil { 531 c.Fatalf("Failed to create %s: %q", path1, err) 532 } 533 defer os.RemoveAll(path1) 534 if err := os.MkdirAll(path2, 0755); err != nil { 535 c.Fatalf("Failed to create %s: %q", path1, err) 536 } 537 defer os.RemoveAll(path2) 538 } 539 mountstr1 := path1 + someplace 540 mountstr2 := path2 + someplace 541 542 if out, _, err := dockerCmdWithError("run", "-v", mountstr1, "-v", mountstr2, "busybox", "true"); err == nil { 543 c.Fatal("Expected error about duplicate mount definitions") 544 } else { 545 if !strings.Contains(out, "Duplicate mount point") { 546 c.Fatalf("Expected 'duplicate mount point' error, got %v", out) 547 } 548 } 549 550 // Test for https://github.com/docker/docker/issues/22093 551 volumename1 := "test1" 552 volumename2 := "test2" 553 volume1 := volumename1 + someplace 554 volume2 := volumename2 + someplace 555 if out, _, err := dockerCmdWithError("run", "-v", volume1, "-v", volume2, "busybox", "true"); err == nil { 556 c.Fatal("Expected error about duplicate mount definitions") 557 } else { 558 if !strings.Contains(out, "Duplicate mount point") { 559 c.Fatalf("Expected 'duplicate mount point' error, got %v", out) 560 } 561 } 562 // create failed should have create volume volumename1 or volumename2 563 // we should remove volumename2 or volumename2 successfully 564 out, _ := dockerCmd(c, "volume", "ls") 565 if strings.Contains(out, volumename1) { 566 dockerCmd(c, "volume", "rm", volumename1) 567 } else { 568 dockerCmd(c, "volume", "rm", volumename2) 569 } 570 } 571 572 // Test for #1351 573 func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *check.C) { 574 prefix := "" 575 if testEnv.OSType == "windows" { 576 prefix = `c:` 577 } 578 dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo") 579 dockerCmd(c, "run", "--volumes-from", "parent", "-v", prefix+"/test", "busybox", "cat", prefix+"/test/foo") 580 } 581 582 func (s *DockerSuite) TestRunMultipleVolumesFrom(c *check.C) { 583 prefix := "" 584 if testEnv.OSType == "windows" { 585 prefix = `c:` 586 } 587 dockerCmd(c, "run", "--name", "parent1", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo") 588 dockerCmd(c, "run", "--name", "parent2", "-v", prefix+"/other", "busybox", "touch", prefix+"/other/bar") 589 dockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar") 590 } 591 592 // this tests verifies the ID format for the container 593 func (s *DockerSuite) TestRunVerifyContainerID(c *check.C) { 594 out, exit, err := dockerCmdWithError("run", "-d", "busybox", "true") 595 if err != nil { 596 c.Fatal(err) 597 } 598 if exit != 0 { 599 c.Fatalf("expected exit code 0 received %d", exit) 600 } 601 602 match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n")) 603 if err != nil { 604 c.Fatal(err) 605 } 606 if !match { 607 c.Fatalf("Invalid container ID: %s", out) 608 } 609 } 610 611 // Test that creating a container with a volume doesn't crash. Regression test for #995. 612 func (s *DockerSuite) TestRunCreateVolume(c *check.C) { 613 prefix := "" 614 if testEnv.OSType == "windows" { 615 prefix = `c:` 616 } 617 dockerCmd(c, "run", "-v", prefix+"/var/lib/data", "busybox", "true") 618 } 619 620 // Test that creating a volume with a symlink in its path works correctly. Test for #5152. 621 // Note that this bug happens only with symlinks with a target that starts with '/'. 622 func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) { 623 // Cannot run on Windows as relies on Linux-specific functionality (sh -c mount...) 624 testRequires(c, DaemonIsLinux) 625 workingDirectory, err := ioutil.TempDir("", "TestRunCreateVolumeWithSymlink") 626 image := "docker-test-createvolumewithsymlink" 627 628 buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-") 629 buildCmd.Stdin = strings.NewReader(`FROM busybox 630 RUN ln -s home /bar`) 631 buildCmd.Dir = workingDirectory 632 err = buildCmd.Run() 633 if err != nil { 634 c.Fatalf("could not build '%s': %v", image, err) 635 } 636 637 _, exitCode, err := dockerCmdWithError("run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo") 638 if err != nil || exitCode != 0 { 639 c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode) 640 } 641 642 volPath, err := inspectMountSourceField("test-createvolumewithsymlink", "/bar/foo") 643 c.Assert(err, checker.IsNil) 644 645 _, exitCode, err = dockerCmdWithError("rm", "-v", "test-createvolumewithsymlink") 646 if err != nil || exitCode != 0 { 647 c.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode) 648 } 649 650 _, err = os.Stat(volPath) 651 if !os.IsNotExist(err) { 652 c.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath) 653 } 654 } 655 656 // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`. 657 func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) { 658 // This test cannot run on a Windows daemon as 659 // Windows does not support symlinks inside a volume path 660 testRequires(c, DaemonIsLinux) 661 662 workingDirectory, err := ioutil.TempDir("", "TestRunVolumesFromSymlinkPath") 663 c.Assert(err, checker.IsNil) 664 name := "docker-test-volumesfromsymlinkpath" 665 prefix := "" 666 dfContents := `FROM busybox 667 RUN ln -s home /foo 668 VOLUME ["/foo/bar"]` 669 670 if testEnv.OSType == "windows" { 671 prefix = `c:` 672 dfContents = `FROM ` + testEnv.PlatformDefaults.BaseImage + ` 673 RUN mkdir c:\home 674 RUN mklink /D c:\foo c:\home 675 VOLUME ["c:/foo/bar"] 676 ENTRYPOINT c:\windows\system32\cmd.exe` 677 } 678 679 buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-") 680 buildCmd.Stdin = strings.NewReader(dfContents) 681 buildCmd.Dir = workingDirectory 682 err = buildCmd.Run() 683 if err != nil { 684 c.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err) 685 } 686 687 out, exitCode, err := dockerCmdWithError("run", "--name", "test-volumesfromsymlinkpath", name) 688 if err != nil || exitCode != 0 { 689 c.Fatalf("[run] (volume) err: %v, exitcode: %d, out: %s", err, exitCode, out) 690 } 691 692 _, exitCode, err = dockerCmdWithError("run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls "+prefix+"/foo | grep -q bar") 693 if err != nil || exitCode != 0 { 694 c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode) 695 } 696 } 697 698 func (s *DockerSuite) TestRunExitCode(c *check.C) { 699 var ( 700 exit int 701 err error 702 ) 703 704 _, exit, err = dockerCmdWithError("run", "busybox", "/bin/sh", "-c", "exit 72") 705 706 if err == nil { 707 c.Fatal("should not have a non nil error") 708 } 709 if exit != 72 { 710 c.Fatalf("expected exit code 72 received %d", exit) 711 } 712 } 713 714 func (s *DockerSuite) TestRunUserDefaults(c *check.C) { 715 expected := "uid=0(root) gid=0(root)" 716 if testEnv.OSType == "windows" { 717 expected = "uid=1000(ContainerAdministrator) gid=1000(ContainerAdministrator)" 718 } 719 out, _ := dockerCmd(c, "run", "busybox", "id") 720 if !strings.Contains(out, expected) { 721 c.Fatalf("expected '%s' got %s", expected, out) 722 } 723 } 724 725 func (s *DockerSuite) TestRunUserByName(c *check.C) { 726 // TODO Windows: This test cannot run on a Windows daemon as Windows does 727 // not support the use of -u 728 testRequires(c, DaemonIsLinux) 729 out, _ := dockerCmd(c, "run", "-u", "root", "busybox", "id") 730 if !strings.Contains(out, "uid=0(root) gid=0(root)") { 731 c.Fatalf("expected root user got %s", out) 732 } 733 } 734 735 func (s *DockerSuite) TestRunUserByID(c *check.C) { 736 // TODO Windows: This test cannot run on a Windows daemon as Windows does 737 // not support the use of -u 738 testRequires(c, DaemonIsLinux) 739 out, _ := dockerCmd(c, "run", "-u", "1", "busybox", "id") 740 if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") { 741 c.Fatalf("expected daemon user got %s", out) 742 } 743 } 744 745 func (s *DockerSuite) TestRunUserByIDBig(c *check.C) { 746 // TODO Windows: This test cannot run on a Windows daemon as Windows does 747 // not support the use of -u 748 testRequires(c, DaemonIsLinux, NotArm) 749 out, _, err := dockerCmdWithError("run", "-u", "2147483648", "busybox", "id") 750 if err == nil { 751 c.Fatal("No error, but must be.", out) 752 } 753 if !strings.Contains(strings.ToLower(out), "uids and gids must be in range") { 754 c.Fatalf("expected error about uids range, got %s", out) 755 } 756 } 757 758 func (s *DockerSuite) TestRunUserByIDNegative(c *check.C) { 759 // TODO Windows: This test cannot run on a Windows daemon as Windows does 760 // not support the use of -u 761 testRequires(c, DaemonIsLinux) 762 out, _, err := dockerCmdWithError("run", "-u", "-1", "busybox", "id") 763 if err == nil { 764 c.Fatal("No error, but must be.", out) 765 } 766 if !strings.Contains(strings.ToLower(out), "uids and gids must be in range") { 767 c.Fatalf("expected error about uids range, got %s", out) 768 } 769 } 770 771 func (s *DockerSuite) TestRunUserByIDZero(c *check.C) { 772 // TODO Windows: This test cannot run on a Windows daemon as Windows does 773 // not support the use of -u 774 testRequires(c, DaemonIsLinux) 775 out, _, err := dockerCmdWithError("run", "-u", "0", "busybox", "id") 776 if err != nil { 777 c.Fatal(err, out) 778 } 779 if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") { 780 c.Fatalf("expected daemon user got %s", out) 781 } 782 } 783 784 func (s *DockerSuite) TestRunUserNotFound(c *check.C) { 785 // TODO Windows: This test cannot run on a Windows daemon as Windows does 786 // not support the use of -u 787 testRequires(c, DaemonIsLinux) 788 _, _, err := dockerCmdWithError("run", "-u", "notme", "busybox", "id") 789 if err == nil { 790 c.Fatal("unknown user should cause container to fail") 791 } 792 } 793 794 func (s *DockerSuite) TestRunTwoConcurrentContainers(c *check.C) { 795 sleepTime := "2" 796 group := sync.WaitGroup{} 797 group.Add(2) 798 799 errChan := make(chan error, 2) 800 for i := 0; i < 2; i++ { 801 go func() { 802 defer group.Done() 803 _, _, err := dockerCmdWithError("run", "busybox", "sleep", sleepTime) 804 errChan <- err 805 }() 806 } 807 808 group.Wait() 809 close(errChan) 810 811 for err := range errChan { 812 c.Assert(err, check.IsNil) 813 } 814 } 815 816 func (s *DockerSuite) TestRunEnvironment(c *check.C) { 817 // TODO Windows: Environment handling is different between Linux and 818 // Windows and this test relies currently on unix functionality. 819 testRequires(c, DaemonIsLinux) 820 result := icmd.RunCmd(icmd.Cmd{ 821 Command: []string{dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env"}, 822 Env: append(os.Environ(), 823 "TRUE=false", 824 "TRICKY=tri\ncky\n", 825 ), 826 }) 827 result.Assert(c, icmd.Success) 828 829 actualEnv := strings.Split(strings.TrimSuffix(result.Stdout(), "\n"), "\n") 830 sort.Strings(actualEnv) 831 832 goodEnv := []string{ 833 // The first two should not be tested here, those are "inherent" environment variable. This test validates 834 // the -e behavior, not the default environment variable (that could be subject to change) 835 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 836 "HOSTNAME=testing", 837 "FALSE=true", 838 "TRUE=false", 839 "TRICKY=tri", 840 "cky", 841 "", 842 "HOME=/root", 843 } 844 sort.Strings(goodEnv) 845 if len(goodEnv) != len(actualEnv) { 846 c.Fatalf("Wrong environment: should be %d variables, not %d: %q", len(goodEnv), len(actualEnv), strings.Join(actualEnv, ", ")) 847 } 848 for i := range goodEnv { 849 if actualEnv[i] != goodEnv[i] { 850 c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i]) 851 } 852 } 853 } 854 855 func (s *DockerSuite) TestRunEnvironmentErase(c *check.C) { 856 // TODO Windows: Environment handling is different between Linux and 857 // Windows and this test relies currently on unix functionality. 858 testRequires(c, DaemonIsLinux) 859 860 // Test to make sure that when we use -e on env vars that are 861 // not set in our local env that they're removed (if present) in 862 // the container 863 864 result := icmd.RunCmd(icmd.Cmd{ 865 Command: []string{dockerBinary, "run", "-e", "FOO", "-e", "HOSTNAME", "busybox", "env"}, 866 Env: appendBaseEnv(true), 867 }) 868 result.Assert(c, icmd.Success) 869 870 actualEnv := strings.Split(strings.TrimSpace(result.Combined()), "\n") 871 sort.Strings(actualEnv) 872 873 goodEnv := []string{ 874 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 875 "HOME=/root", 876 } 877 sort.Strings(goodEnv) 878 if len(goodEnv) != len(actualEnv) { 879 c.Fatalf("Wrong environment: should be %d variables, not %d: %q", len(goodEnv), len(actualEnv), strings.Join(actualEnv, ", ")) 880 } 881 for i := range goodEnv { 882 if actualEnv[i] != goodEnv[i] { 883 c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i]) 884 } 885 } 886 } 887 888 func (s *DockerSuite) TestRunEnvironmentOverride(c *check.C) { 889 // TODO Windows: Environment handling is different between Linux and 890 // Windows and this test relies currently on unix functionality. 891 testRequires(c, DaemonIsLinux) 892 893 // Test to make sure that when we use -e on env vars that are 894 // already in the env that we're overriding them 895 896 result := icmd.RunCmd(icmd.Cmd{ 897 Command: []string{dockerBinary, "run", "-e", "HOSTNAME", "-e", "HOME=/root2", "busybox", "env"}, 898 Env: appendBaseEnv(true, "HOSTNAME=bar"), 899 }) 900 result.Assert(c, icmd.Success) 901 902 actualEnv := strings.Split(strings.TrimSpace(result.Combined()), "\n") 903 sort.Strings(actualEnv) 904 905 goodEnv := []string{ 906 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 907 "HOME=/root2", 908 "HOSTNAME=bar", 909 } 910 sort.Strings(goodEnv) 911 if len(goodEnv) != len(actualEnv) { 912 c.Fatalf("Wrong environment: should be %d variables, not %d: %q", len(goodEnv), len(actualEnv), strings.Join(actualEnv, ", ")) 913 } 914 for i := range goodEnv { 915 if actualEnv[i] != goodEnv[i] { 916 c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i]) 917 } 918 } 919 } 920 921 func (s *DockerSuite) TestRunContainerNetwork(c *check.C) { 922 if testEnv.OSType == "windows" { 923 // Windows busybox does not have ping. Use built in ping instead. 924 dockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1") 925 } else { 926 dockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1") 927 } 928 } 929 930 func (s *DockerSuite) TestRunNetHostNotAllowedWithLinks(c *check.C) { 931 // TODO Windows: This is Linux specific as --link is not supported and 932 // this will be deprecated in favor of container networking model. 933 testRequires(c, DaemonIsLinux, NotUserNamespace) 934 dockerCmd(c, "run", "--name", "linked", "busybox", "true") 935 936 _, _, err := dockerCmdWithError("run", "--net=host", "--link", "linked:linked", "busybox", "true") 937 if err == nil { 938 c.Fatal("Expected error") 939 } 940 } 941 942 // #7851 hostname outside container shows FQDN, inside only shortname 943 // For testing purposes it is not required to set host's hostname directly 944 // and use "--net=host" (as the original issue submitter did), as the same 945 // codepath is executed with "docker run -h <hostname>". Both were manually 946 // tested, but this testcase takes the simpler path of using "run -h .." 947 func (s *DockerSuite) TestRunFullHostnameSet(c *check.C) { 948 // TODO Windows: -h is not yet functional. 949 testRequires(c, DaemonIsLinux) 950 out, _ := dockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname") 951 if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" { 952 c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual) 953 } 954 } 955 956 func (s *DockerSuite) TestRunPrivilegedCanMknod(c *check.C) { 957 // Not applicable for Windows as Windows daemon does not support 958 // the concept of --privileged, and mknod is a Unix concept. 959 testRequires(c, DaemonIsLinux, NotUserNamespace) 960 out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 961 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 962 c.Fatalf("expected output ok received %s", actual) 963 } 964 } 965 966 func (s *DockerSuite) TestRunUnprivilegedCanMknod(c *check.C) { 967 // Not applicable for Windows as Windows daemon does not support 968 // the concept of --privileged, and mknod is a Unix concept. 969 testRequires(c, DaemonIsLinux, NotUserNamespace) 970 out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 971 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 972 c.Fatalf("expected output ok received %s", actual) 973 } 974 } 975 976 func (s *DockerSuite) TestRunCapDropInvalid(c *check.C) { 977 // Not applicable for Windows as there is no concept of --cap-drop 978 testRequires(c, DaemonIsLinux) 979 out, _, err := dockerCmdWithError("run", "--cap-drop=CHPASS", "busybox", "ls") 980 if err == nil { 981 c.Fatal(err, out) 982 } 983 } 984 985 func (s *DockerSuite) TestRunCapDropCannotMknod(c *check.C) { 986 // Not applicable for Windows as there is no concept of --cap-drop or mknod 987 testRequires(c, DaemonIsLinux) 988 out, _, err := dockerCmdWithError("run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 989 990 if err == nil { 991 c.Fatal(err, out) 992 } 993 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 994 c.Fatalf("expected output not ok received %s", actual) 995 } 996 } 997 998 func (s *DockerSuite) TestRunCapDropCannotMknodLowerCase(c *check.C) { 999 // Not applicable for Windows as there is no concept of --cap-drop or mknod 1000 testRequires(c, DaemonIsLinux) 1001 out, _, err := dockerCmdWithError("run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 1002 1003 if err == nil { 1004 c.Fatal(err, out) 1005 } 1006 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 1007 c.Fatalf("expected output not ok received %s", actual) 1008 } 1009 } 1010 1011 func (s *DockerSuite) TestRunCapDropALLCannotMknod(c *check.C) { 1012 // Not applicable for Windows as there is no concept of --cap-drop or mknod 1013 testRequires(c, DaemonIsLinux) 1014 out, _, err := dockerCmdWithError("run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 1015 if err == nil { 1016 c.Fatal(err, out) 1017 } 1018 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 1019 c.Fatalf("expected output not ok received %s", actual) 1020 } 1021 } 1022 1023 func (s *DockerSuite) TestRunCapDropALLAddMknodCanMknod(c *check.C) { 1024 // Not applicable for Windows as there is no concept of --cap-drop or mknod 1025 testRequires(c, DaemonIsLinux, NotUserNamespace) 1026 out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 1027 1028 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 1029 c.Fatalf("expected output ok received %s", actual) 1030 } 1031 } 1032 1033 func (s *DockerSuite) TestRunCapAddInvalid(c *check.C) { 1034 // Not applicable for Windows as there is no concept of --cap-add 1035 testRequires(c, DaemonIsLinux) 1036 out, _, err := dockerCmdWithError("run", "--cap-add=CHPASS", "busybox", "ls") 1037 if err == nil { 1038 c.Fatal(err, out) 1039 } 1040 } 1041 1042 func (s *DockerSuite) TestRunCapAddCanDownInterface(c *check.C) { 1043 // Not applicable for Windows as there is no concept of --cap-add 1044 testRequires(c, DaemonIsLinux) 1045 out, _ := dockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok") 1046 1047 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 1048 c.Fatalf("expected output ok received %s", actual) 1049 } 1050 } 1051 1052 func (s *DockerSuite) TestRunCapAddALLCanDownInterface(c *check.C) { 1053 // Not applicable for Windows as there is no concept of --cap-add 1054 testRequires(c, DaemonIsLinux) 1055 out, _ := dockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok") 1056 1057 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 1058 c.Fatalf("expected output ok received %s", actual) 1059 } 1060 } 1061 1062 func (s *DockerSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *check.C) { 1063 // Not applicable for Windows as there is no concept of --cap-add 1064 testRequires(c, DaemonIsLinux) 1065 out, _, err := dockerCmdWithError("run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok") 1066 if err == nil { 1067 c.Fatal(err, out) 1068 } 1069 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 1070 c.Fatalf("expected output not ok received %s", actual) 1071 } 1072 } 1073 1074 func (s *DockerSuite) TestRunGroupAdd(c *check.C) { 1075 // Not applicable for Windows as there is no concept of --group-add 1076 testRequires(c, DaemonIsLinux) 1077 out, _ := dockerCmd(c, "run", "--group-add=audio", "--group-add=staff", "--group-add=777", "busybox", "sh", "-c", "id") 1078 1079 groupsList := "uid=0(root) gid=0(root) groups=10(wheel),29(audio),50(staff),777" 1080 if actual := strings.Trim(out, "\r\n"); actual != groupsList { 1081 c.Fatalf("expected output %s received %s", groupsList, actual) 1082 } 1083 } 1084 1085 func (s *DockerSuite) TestRunPrivilegedCanMount(c *check.C) { 1086 // Not applicable for Windows as there is no concept of --privileged 1087 testRequires(c, DaemonIsLinux, NotUserNamespace) 1088 out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok") 1089 1090 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 1091 c.Fatalf("expected output ok received %s", actual) 1092 } 1093 } 1094 1095 func (s *DockerSuite) TestRunUnprivilegedCannotMount(c *check.C) { 1096 // Not applicable for Windows as there is no concept of unprivileged 1097 testRequires(c, DaemonIsLinux) 1098 out, _, err := dockerCmdWithError("run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok") 1099 1100 if err == nil { 1101 c.Fatal(err, out) 1102 } 1103 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 1104 c.Fatalf("expected output not ok received %s", actual) 1105 } 1106 } 1107 1108 func (s *DockerSuite) TestRunSysNotWritableInNonPrivilegedContainers(c *check.C) { 1109 // Not applicable for Windows as there is no concept of unprivileged 1110 testRequires(c, DaemonIsLinux, NotArm) 1111 if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/sys/kernel/profiling"); err == nil || code == 0 { 1112 c.Fatal("sys should not be writable in a non privileged container") 1113 } 1114 } 1115 1116 func (s *DockerSuite) TestRunSysWritableInPrivilegedContainers(c *check.C) { 1117 // Not applicable for Windows as there is no concept of unprivileged 1118 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 1119 if _, code, err := dockerCmdWithError("run", "--privileged", "busybox", "touch", "/sys/kernel/profiling"); err != nil || code != 0 { 1120 c.Fatalf("sys should be writable in privileged container") 1121 } 1122 } 1123 1124 func (s *DockerSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *check.C) { 1125 // Not applicable for Windows as there is no concept of unprivileged 1126 testRequires(c, DaemonIsLinux) 1127 if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/proc/sysrq-trigger"); err == nil || code == 0 { 1128 c.Fatal("proc should not be writable in a non privileged container") 1129 } 1130 } 1131 1132 func (s *DockerSuite) TestRunProcWritableInPrivilegedContainers(c *check.C) { 1133 // Not applicable for Windows as there is no concept of --privileged 1134 testRequires(c, DaemonIsLinux, NotUserNamespace) 1135 if _, code := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "touch /proc/sysrq-trigger"); code != 0 { 1136 c.Fatalf("proc should be writable in privileged container") 1137 } 1138 } 1139 1140 func (s *DockerSuite) TestRunDeviceNumbers(c *check.C) { 1141 // Not applicable on Windows as /dev/ is a Unix specific concept 1142 // TODO: NotUserNamespace could be removed here if "root" "root" is replaced w user 1143 testRequires(c, DaemonIsLinux, NotUserNamespace) 1144 out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null") 1145 deviceLineFields := strings.Fields(out) 1146 deviceLineFields[6] = "" 1147 deviceLineFields[7] = "" 1148 deviceLineFields[8] = "" 1149 expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"} 1150 1151 if !(reflect.DeepEqual(deviceLineFields, expected)) { 1152 c.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out) 1153 } 1154 } 1155 1156 func (s *DockerSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *check.C) { 1157 // Not applicable on Windows as /dev/ is a Unix specific concept 1158 testRequires(c, DaemonIsLinux) 1159 out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero") 1160 if actual := strings.Trim(out, "\r\n"); actual[0] == '0' { 1161 c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual) 1162 } 1163 } 1164 1165 func (s *DockerSuite) TestRunUnprivilegedWithChroot(c *check.C) { 1166 // Not applicable on Windows as it does not support chroot 1167 testRequires(c, DaemonIsLinux) 1168 dockerCmd(c, "run", "busybox", "chroot", "/", "true") 1169 } 1170 1171 func (s *DockerSuite) TestRunAddingOptionalDevices(c *check.C) { 1172 // Not applicable on Windows as Windows does not support --device 1173 testRequires(c, DaemonIsLinux, NotUserNamespace) 1174 out, _ := dockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo") 1175 if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" { 1176 c.Fatalf("expected output /dev/nulo, received %s", actual) 1177 } 1178 } 1179 1180 func (s *DockerSuite) TestRunAddingOptionalDevicesNoSrc(c *check.C) { 1181 // Not applicable on Windows as Windows does not support --device 1182 testRequires(c, DaemonIsLinux, NotUserNamespace) 1183 out, _ := dockerCmd(c, "run", "--device", "/dev/zero:rw", "busybox", "sh", "-c", "ls /dev/zero") 1184 if actual := strings.Trim(out, "\r\n"); actual != "/dev/zero" { 1185 c.Fatalf("expected output /dev/zero, received %s", actual) 1186 } 1187 } 1188 1189 func (s *DockerSuite) TestRunAddingOptionalDevicesInvalidMode(c *check.C) { 1190 // Not applicable on Windows as Windows does not support --device 1191 testRequires(c, DaemonIsLinux, NotUserNamespace) 1192 _, _, err := dockerCmdWithError("run", "--device", "/dev/zero:ro", "busybox", "sh", "-c", "ls /dev/zero") 1193 if err == nil { 1194 c.Fatalf("run container with device mode ro should fail") 1195 } 1196 } 1197 1198 func (s *DockerSuite) TestRunModeHostname(c *check.C) { 1199 // Not applicable on Windows as Windows does not support -h 1200 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 1201 1202 out, _ := dockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname") 1203 1204 if actual := strings.Trim(out, "\r\n"); actual != "testhostname" { 1205 c.Fatalf("expected 'testhostname', but says: %q", actual) 1206 } 1207 1208 out, _ = dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname") 1209 1210 hostname, err := os.Hostname() 1211 if err != nil { 1212 c.Fatal(err) 1213 } 1214 if actual := strings.Trim(out, "\r\n"); actual != hostname { 1215 c.Fatalf("expected %q, but says: %q", hostname, actual) 1216 } 1217 } 1218 1219 func (s *DockerSuite) TestRunRootWorkdir(c *check.C) { 1220 out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd") 1221 expected := "/\n" 1222 if testEnv.OSType == "windows" { 1223 expected = "C:" + expected 1224 } 1225 if out != expected { 1226 c.Fatalf("pwd returned %q (expected %s)", s, expected) 1227 } 1228 } 1229 1230 func (s *DockerSuite) TestRunAllowBindMountingRoot(c *check.C) { 1231 if testEnv.OSType == "windows" { 1232 // Windows busybox will fail with Permission Denied on items such as pagefile.sys 1233 dockerCmd(c, "run", "-v", `c:\:c:\host`, testEnv.PlatformDefaults.BaseImage, "cmd", "-c", "dir", `c:\host`) 1234 } else { 1235 dockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host") 1236 } 1237 } 1238 1239 func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *check.C) { 1240 mount := "/:/" 1241 targetDir := "/host" 1242 if testEnv.OSType == "windows" { 1243 mount = `c:\:c\` 1244 targetDir = "c:/host" // Forward slash as using busybox 1245 } 1246 out, _, err := dockerCmdWithError("run", "-v", mount, "busybox", "ls", targetDir) 1247 if err == nil { 1248 c.Fatal(out, err) 1249 } 1250 } 1251 1252 // Verify that a container gets default DNS when only localhost resolvers exist 1253 func (s *DockerSuite) TestRunDNSDefaultOptions(c *check.C) { 1254 // Not applicable on Windows as this is testing Unix specific functionality 1255 testRequires(c, SameHostDaemon, DaemonIsLinux) 1256 1257 // preserve original resolv.conf for restoring after test 1258 origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf") 1259 if os.IsNotExist(err) { 1260 c.Fatalf("/etc/resolv.conf does not exist") 1261 } 1262 // defer restored original conf 1263 defer func() { 1264 if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil { 1265 c.Fatal(err) 1266 } 1267 }() 1268 1269 // test 3 cases: standard IPv4 localhost, commented out localhost, and IPv6 localhost 1270 // 2 are removed from the file at container start, and the 3rd (commented out) one is ignored by 1271 // GetNameservers(), leading to a replacement of nameservers with the default set 1272 tmpResolvConf := []byte("nameserver 127.0.0.1\n#nameserver 127.0.2.1\nnameserver ::1") 1273 if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil { 1274 c.Fatal(err) 1275 } 1276 1277 actual, _ := dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf") 1278 // check that the actual defaults are appended to the commented out 1279 // localhost resolver (which should be preserved) 1280 // NOTE: if we ever change the defaults from google dns, this will break 1281 expected := "#nameserver 127.0.2.1\n\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n" 1282 if actual != expected { 1283 c.Fatalf("expected resolv.conf be: %q, but was: %q", expected, actual) 1284 } 1285 } 1286 1287 func (s *DockerSuite) TestRunDNSOptions(c *check.C) { 1288 // Not applicable on Windows as Windows does not support --dns*, or 1289 // the Unix-specific functionality of resolv.conf. 1290 testRequires(c, DaemonIsLinux) 1291 result := cli.DockerCmd(c, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "--dns-opt=ndots:9", "busybox", "cat", "/etc/resolv.conf") 1292 1293 // The client will get a warning on stderr when setting DNS to a localhost address; verify this: 1294 if !strings.Contains(result.Stderr(), "Localhost DNS setting") { 1295 c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", result.Stderr()) 1296 } 1297 1298 actual := strings.Replace(strings.Trim(result.Stdout(), "\r\n"), "\n", " ", -1) 1299 if actual != "search mydomain nameserver 127.0.0.1 options ndots:9" { 1300 c.Fatalf("expected 'search mydomain nameserver 127.0.0.1 options ndots:9', but says: %q", actual) 1301 } 1302 1303 out := cli.DockerCmd(c, "run", "--dns=1.1.1.1", "--dns-search=.", "--dns-opt=ndots:3", "busybox", "cat", "/etc/resolv.conf").Combined() 1304 1305 actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1) 1306 if actual != "nameserver 1.1.1.1 options ndots:3" { 1307 c.Fatalf("expected 'nameserver 1.1.1.1 options ndots:3', but says: %q", actual) 1308 } 1309 } 1310 1311 func (s *DockerSuite) TestRunDNSRepeatOptions(c *check.C) { 1312 testRequires(c, DaemonIsLinux) 1313 out := cli.DockerCmd(c, "run", "--dns=1.1.1.1", "--dns=2.2.2.2", "--dns-search=mydomain", "--dns-search=mydomain2", "--dns-opt=ndots:9", "--dns-opt=timeout:3", "busybox", "cat", "/etc/resolv.conf").Stdout() 1314 1315 actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1) 1316 if actual != "search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3" { 1317 c.Fatalf("expected 'search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3', but says: %q", actual) 1318 } 1319 } 1320 1321 func (s *DockerSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *check.C) { 1322 // Not applicable on Windows as testing Unix specific functionality 1323 testRequires(c, SameHostDaemon, DaemonIsLinux) 1324 1325 origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf") 1326 if os.IsNotExist(err) { 1327 c.Fatalf("/etc/resolv.conf does not exist") 1328 } 1329 1330 hostNameservers := resolvconf.GetNameservers(origResolvConf, types.IP) 1331 hostSearch := resolvconf.GetSearchDomains(origResolvConf) 1332 1333 var out string 1334 out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf") 1335 1336 if actualNameservers := resolvconf.GetNameservers([]byte(out), types.IP); string(actualNameservers[0]) != "127.0.0.1" { 1337 c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0])) 1338 } 1339 1340 actualSearch := resolvconf.GetSearchDomains([]byte(out)) 1341 if len(actualSearch) != len(hostSearch) { 1342 c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch)) 1343 } 1344 for i := range actualSearch { 1345 if actualSearch[i] != hostSearch[i] { 1346 c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i]) 1347 } 1348 } 1349 1350 out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf") 1351 1352 actualNameservers := resolvconf.GetNameservers([]byte(out), types.IP) 1353 if len(actualNameservers) != len(hostNameservers) { 1354 c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNameservers), len(actualNameservers)) 1355 } 1356 for i := range actualNameservers { 1357 if actualNameservers[i] != hostNameservers[i] { 1358 c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNameservers[i]) 1359 } 1360 } 1361 1362 if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" { 1363 c.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0])) 1364 } 1365 1366 // test with file 1367 tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1") 1368 if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil { 1369 c.Fatal(err) 1370 } 1371 // put the old resolvconf back 1372 defer func() { 1373 if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil { 1374 c.Fatal(err) 1375 } 1376 }() 1377 1378 resolvConf, err := ioutil.ReadFile("/etc/resolv.conf") 1379 if os.IsNotExist(err) { 1380 c.Fatalf("/etc/resolv.conf does not exist") 1381 } 1382 1383 hostSearch = resolvconf.GetSearchDomains(resolvConf) 1384 1385 out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf") 1386 if actualNameservers = resolvconf.GetNameservers([]byte(out), types.IP); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 { 1387 c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers) 1388 } 1389 1390 actualSearch = resolvconf.GetSearchDomains([]byte(out)) 1391 if len(actualSearch) != len(hostSearch) { 1392 c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch)) 1393 } 1394 for i := range actualSearch { 1395 if actualSearch[i] != hostSearch[i] { 1396 c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i]) 1397 } 1398 } 1399 } 1400 1401 // Test to see if a non-root user can resolve a DNS name. Also 1402 // check if the container resolv.conf file has at least 0644 perm. 1403 func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) { 1404 // Not applicable on Windows as Windows does not support --user 1405 testRequires(c, SameHostDaemon, Network, DaemonIsLinux, NotArm) 1406 1407 dockerCmd(c, "run", "--name=testperm", "--user=nobody", "busybox", "nslookup", "apt.dockerproject.org") 1408 1409 cID := getIDByName(c, "testperm") 1410 1411 fmode := (os.FileMode)(0644) 1412 finfo, err := os.Stat(containerStorageFile(cID, "resolv.conf")) 1413 if err != nil { 1414 c.Fatal(err) 1415 } 1416 1417 if (finfo.Mode() & fmode) != fmode { 1418 c.Fatalf("Expected container resolv.conf mode to be at least %s, instead got %s", fmode.String(), finfo.Mode().String()) 1419 } 1420 } 1421 1422 // Test if container resolv.conf gets updated the next time it restarts 1423 // if host /etc/resolv.conf has changed. This only applies if the container 1424 // uses the host's /etc/resolv.conf and does not have any dns options provided. 1425 func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) { 1426 // Not applicable on Windows as testing unix specific functionality 1427 testRequires(c, SameHostDaemon, DaemonIsLinux) 1428 c.Skip("Unstable test, to be re-activated once #19937 is resolved") 1429 1430 tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\n") 1431 tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1") 1432 1433 //take a copy of resolv.conf for restoring after test completes 1434 resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf") 1435 if err != nil { 1436 c.Fatal(err) 1437 } 1438 1439 // This test case is meant to test monitoring resolv.conf when it is 1440 // a regular file not a bind mounc. So we unmount resolv.conf and replace 1441 // it with a file containing the original settings. 1442 mounted, err := mount.Mounted("/etc/resolv.conf") 1443 if err != nil { 1444 c.Fatal(err) 1445 } 1446 if mounted { 1447 icmd.RunCommand("umount", "/etc/resolv.conf").Assert(c, icmd.Success) 1448 } 1449 1450 //cleanup 1451 defer func() { 1452 if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { 1453 c.Fatal(err) 1454 } 1455 }() 1456 1457 //1. test that a restarting container gets an updated resolv.conf 1458 dockerCmd(c, "run", "--name=first", "busybox", "true") 1459 containerID1 := getIDByName(c, "first") 1460 1461 // replace resolv.conf with our temporary copy 1462 bytesResolvConf := []byte(tmpResolvConf) 1463 if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil { 1464 c.Fatal(err) 1465 } 1466 1467 // start the container again to pickup changes 1468 dockerCmd(c, "start", "first") 1469 1470 // check for update in container 1471 containerResolv := readContainerFile(c, containerID1, "resolv.conf") 1472 if !bytes.Equal(containerResolv, bytesResolvConf) { 1473 c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv)) 1474 } 1475 1476 /* //make a change to resolv.conf (in this case replacing our tmp copy with orig copy) 1477 if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { 1478 c.Fatal(err) 1479 } */ 1480 //2. test that a restarting container does not receive resolv.conf updates 1481 // if it modified the container copy of the starting point resolv.conf 1482 dockerCmd(c, "run", "--name=second", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf") 1483 containerID2 := getIDByName(c, "second") 1484 1485 //make a change to resolv.conf (in this case replacing our tmp copy with orig copy) 1486 if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { 1487 c.Fatal(err) 1488 } 1489 1490 // start the container again 1491 dockerCmd(c, "start", "second") 1492 1493 // check for update in container 1494 containerResolv = readContainerFile(c, containerID2, "resolv.conf") 1495 if bytes.Equal(containerResolv, resolvConfSystem) { 1496 c.Fatalf("Container's resolv.conf should not have been updated with host resolv.conf: %q", string(containerResolv)) 1497 } 1498 1499 //3. test that a running container's resolv.conf is not modified while running 1500 out, _ := dockerCmd(c, "run", "-d", "busybox", "top") 1501 runningContainerID := strings.TrimSpace(out) 1502 1503 // replace resolv.conf 1504 if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil { 1505 c.Fatal(err) 1506 } 1507 1508 // check for update in container 1509 containerResolv = readContainerFile(c, runningContainerID, "resolv.conf") 1510 if bytes.Equal(containerResolv, bytesResolvConf) { 1511 c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv)) 1512 } 1513 1514 //4. test that a running container's resolv.conf is updated upon restart 1515 // (the above container is still running..) 1516 dockerCmd(c, "restart", runningContainerID) 1517 1518 // check for update in container 1519 containerResolv = readContainerFile(c, runningContainerID, "resolv.conf") 1520 if !bytes.Equal(containerResolv, bytesResolvConf) { 1521 c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(bytesResolvConf), string(containerResolv)) 1522 } 1523 1524 //5. test that additions of a localhost resolver are cleaned from 1525 // host resolv.conf before updating container's resolv.conf copies 1526 1527 // replace resolv.conf with a localhost-only nameserver copy 1528 bytesResolvConf = []byte(tmpLocalhostResolvConf) 1529 if err = ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil { 1530 c.Fatal(err) 1531 } 1532 1533 // start the container again to pickup changes 1534 dockerCmd(c, "start", "first") 1535 1536 // our first exited container ID should have been updated, but with default DNS 1537 // after the cleanup of resolv.conf found only a localhost nameserver: 1538 containerResolv = readContainerFile(c, containerID1, "resolv.conf") 1539 expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n" 1540 if !bytes.Equal(containerResolv, []byte(expected)) { 1541 c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv)) 1542 } 1543 1544 //6. Test that replacing (as opposed to modifying) resolv.conf triggers an update 1545 // of containers' resolv.conf. 1546 1547 // Restore the original resolv.conf 1548 if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { 1549 c.Fatal(err) 1550 } 1551 1552 // Run the container so it picks up the old settings 1553 dockerCmd(c, "run", "--name=third", "busybox", "true") 1554 containerID3 := getIDByName(c, "third") 1555 1556 // Create a modified resolv.conf.aside and override resolv.conf with it 1557 bytesResolvConf = []byte(tmpResolvConf) 1558 if err := ioutil.WriteFile("/etc/resolv.conf.aside", bytesResolvConf, 0644); err != nil { 1559 c.Fatal(err) 1560 } 1561 1562 err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf") 1563 if err != nil { 1564 c.Fatal(err) 1565 } 1566 1567 // start the container again to pickup changes 1568 dockerCmd(c, "start", "third") 1569 1570 // check for update in container 1571 containerResolv = readContainerFile(c, containerID3, "resolv.conf") 1572 if !bytes.Equal(containerResolv, bytesResolvConf) { 1573 c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv)) 1574 } 1575 1576 //cleanup, restore original resolv.conf happens in defer func() 1577 } 1578 1579 func (s *DockerSuite) TestRunAddHost(c *check.C) { 1580 // Not applicable on Windows as it does not support --add-host 1581 testRequires(c, DaemonIsLinux) 1582 out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts") 1583 1584 actual := strings.Trim(out, "\r\n") 1585 if actual != "86.75.30.9\textra" { 1586 c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual) 1587 } 1588 } 1589 1590 // Regression test for #6983 1591 func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *check.C) { 1592 _, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true") 1593 if exitCode != 0 { 1594 c.Fatalf("Container should have exited with error code 0") 1595 } 1596 } 1597 1598 // Regression test for #6983 1599 func (s *DockerSuite) TestRunAttachStdOutOnlyTTYMode(c *check.C) { 1600 _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true") 1601 if exitCode != 0 { 1602 c.Fatalf("Container should have exited with error code 0") 1603 } 1604 } 1605 1606 // Regression test for #6983 1607 func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *check.C) { 1608 _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true") 1609 if exitCode != 0 { 1610 c.Fatalf("Container should have exited with error code 0") 1611 } 1612 } 1613 1614 // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode 1615 // but using --attach instead of -a to make sure we read the flag correctly 1616 func (s *DockerSuite) TestRunAttachWithDetach(c *check.C) { 1617 icmd.RunCommand(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true").Assert(c, icmd.Expected{ 1618 ExitCode: 1, 1619 Error: "exit status 1", 1620 Err: "Conflicting options: -a and -d", 1621 }) 1622 } 1623 1624 func (s *DockerSuite) TestRunState(c *check.C) { 1625 // TODO Windows: This needs some rework as Windows busybox does not support top 1626 testRequires(c, DaemonIsLinux) 1627 out, _ := dockerCmd(c, "run", "-d", "busybox", "top") 1628 1629 id := strings.TrimSpace(out) 1630 state := inspectField(c, id, "State.Running") 1631 if state != "true" { 1632 c.Fatal("Container state is 'not running'") 1633 } 1634 pid1 := inspectField(c, id, "State.Pid") 1635 if pid1 == "0" { 1636 c.Fatal("Container state Pid 0") 1637 } 1638 1639 dockerCmd(c, "stop", id) 1640 state = inspectField(c, id, "State.Running") 1641 if state != "false" { 1642 c.Fatal("Container state is 'running'") 1643 } 1644 pid2 := inspectField(c, id, "State.Pid") 1645 if pid2 == pid1 { 1646 c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1) 1647 } 1648 1649 dockerCmd(c, "start", id) 1650 state = inspectField(c, id, "State.Running") 1651 if state != "true" { 1652 c.Fatal("Container state is 'not running'") 1653 } 1654 pid3 := inspectField(c, id, "State.Pid") 1655 if pid3 == pid1 { 1656 c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1) 1657 } 1658 } 1659 1660 // Test for #1737 1661 func (s *DockerSuite) TestRunCopyVolumeUIDGID(c *check.C) { 1662 // Not applicable on Windows as it does not support uid or gid in this way 1663 testRequires(c, DaemonIsLinux) 1664 name := "testrunvolumesuidgid" 1665 buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox 1666 RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd 1667 RUN echo 'dockerio:x:1001:' >> /etc/group 1668 RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`)) 1669 1670 // Test that the uid and gid is copied from the image to the volume 1671 out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'") 1672 out = strings.TrimSpace(out) 1673 if out != "dockerio:dockerio" { 1674 c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out) 1675 } 1676 } 1677 1678 // Test for #1582 1679 func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) { 1680 // TODO Windows, post RS1. Windows does not yet support volume functionality 1681 // that copies from the image to the volume. 1682 testRequires(c, DaemonIsLinux) 1683 name := "testruncopyvolumecontent" 1684 buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox 1685 RUN mkdir -p /hello/local && echo hello > /hello/local/world`)) 1686 1687 // Test that the content is copied from the image to the volume 1688 out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello") 1689 if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) { 1690 c.Fatal("Container failed to transfer content to volume") 1691 } 1692 } 1693 1694 func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) { 1695 name := "testrunmdcleanuponentrypoint" 1696 buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox 1697 ENTRYPOINT ["echo"] 1698 CMD ["testingpoint"]`)) 1699 1700 out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name) 1701 if exit != 0 { 1702 c.Fatalf("expected exit code 0 received %d, out: %q", exit, out) 1703 } 1704 out = strings.TrimSpace(out) 1705 expected := "root" 1706 if testEnv.OSType == "windows" { 1707 if strings.Contains(testEnv.PlatformDefaults.BaseImage, "windowsservercore") { 1708 expected = `user manager\containeradministrator` 1709 } else { 1710 expected = `ContainerAdministrator` // nanoserver 1711 } 1712 } 1713 if out != expected { 1714 c.Fatalf("Expected output %s, got %q. %s", expected, out, testEnv.PlatformDefaults.BaseImage) 1715 } 1716 } 1717 1718 // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected 1719 func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *check.C) { 1720 existingFile := "/bin/cat" 1721 expected := "not a directory" 1722 if testEnv.OSType == "windows" { 1723 existingFile = `\windows\system32\ntdll.dll` 1724 expected = `The directory name is invalid.` 1725 } 1726 1727 out, exitCode, err := dockerCmdWithError("run", "-w", existingFile, "busybox") 1728 if !(err != nil && exitCode == 125 && strings.Contains(out, expected)) { 1729 c.Fatalf("Existing binary as a directory should error out with exitCode 125; we got: %s, exitCode: %d", out, exitCode) 1730 } 1731 } 1732 1733 func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) { 1734 name := "testrunexitonstdinclose" 1735 1736 meow := "/bin/cat" 1737 delay := 60 1738 if testEnv.OSType == "windows" { 1739 meow = "cat" 1740 } 1741 runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", meow) 1742 1743 stdin, err := runCmd.StdinPipe() 1744 if err != nil { 1745 c.Fatal(err) 1746 } 1747 stdout, err := runCmd.StdoutPipe() 1748 if err != nil { 1749 c.Fatal(err) 1750 } 1751 1752 if err := runCmd.Start(); err != nil { 1753 c.Fatal(err) 1754 } 1755 if _, err := stdin.Write([]byte("hello\n")); err != nil { 1756 c.Fatal(err) 1757 } 1758 1759 r := bufio.NewReader(stdout) 1760 line, err := r.ReadString('\n') 1761 if err != nil { 1762 c.Fatal(err) 1763 } 1764 line = strings.TrimSpace(line) 1765 if line != "hello" { 1766 c.Fatalf("Output should be 'hello', got '%q'", line) 1767 } 1768 if err := stdin.Close(); err != nil { 1769 c.Fatal(err) 1770 } 1771 finish := make(chan error) 1772 go func() { 1773 finish <- runCmd.Wait() 1774 close(finish) 1775 }() 1776 select { 1777 case err := <-finish: 1778 c.Assert(err, check.IsNil) 1779 case <-time.After(time.Duration(delay) * time.Second): 1780 c.Fatal("docker run failed to exit on stdin close") 1781 } 1782 state := inspectField(c, name, "State.Running") 1783 1784 if state != "false" { 1785 c.Fatal("Container must be stopped after stdin closing") 1786 } 1787 } 1788 1789 // Test run -i --restart xxx doesn't hang 1790 func (s *DockerSuite) TestRunInteractiveWithRestartPolicy(c *check.C) { 1791 name := "test-inter-restart" 1792 1793 result := icmd.StartCmd(icmd.Cmd{ 1794 Command: []string{dockerBinary, "run", "-i", "--name", name, "--restart=always", "busybox", "sh"}, 1795 Stdin: bytes.NewBufferString("exit 11"), 1796 }) 1797 c.Assert(result.Error, checker.IsNil) 1798 defer func() { 1799 dockerCmdWithResult("stop", name).Assert(c, icmd.Success) 1800 }() 1801 1802 result = icmd.WaitOnCmd(60*time.Second, result) 1803 result.Assert(c, icmd.Expected{ExitCode: 11}) 1804 } 1805 1806 // Test for #2267 1807 func (s *DockerSuite) TestRunWriteSpecialFilesAndNotCommit(c *check.C) { 1808 // Cannot run on Windows as this files are not present in Windows 1809 testRequires(c, DaemonIsLinux) 1810 1811 testRunWriteSpecialFilesAndNotCommit(c, "writehosts", "/etc/hosts") 1812 testRunWriteSpecialFilesAndNotCommit(c, "writehostname", "/etc/hostname") 1813 testRunWriteSpecialFilesAndNotCommit(c, "writeresolv", "/etc/resolv.conf") 1814 } 1815 1816 func testRunWriteSpecialFilesAndNotCommit(c *check.C, name, path string) { 1817 command := fmt.Sprintf("echo test2267 >> %s && cat %s", path, path) 1818 out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", command) 1819 if !strings.Contains(out, "test2267") { 1820 c.Fatalf("%s should contain 'test2267'", path) 1821 } 1822 1823 out, _ = dockerCmd(c, "diff", name) 1824 if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) { 1825 c.Fatal("diff should be empty") 1826 } 1827 } 1828 1829 func eqToBaseDiff(out string, c *check.C) bool { 1830 name := "eqToBaseDiff" + testutil.GenerateRandomAlphaOnlyString(32) 1831 dockerCmd(c, "run", "--name", name, "busybox", "echo", "hello") 1832 cID := getIDByName(c, name) 1833 baseDiff, _ := dockerCmd(c, "diff", cID) 1834 baseArr := strings.Split(baseDiff, "\n") 1835 sort.Strings(baseArr) 1836 outArr := strings.Split(out, "\n") 1837 sort.Strings(outArr) 1838 return sliceEq(baseArr, outArr) 1839 } 1840 1841 func sliceEq(a, b []string) bool { 1842 if len(a) != len(b) { 1843 return false 1844 } 1845 1846 for i := range a { 1847 if a[i] != b[i] { 1848 return false 1849 } 1850 } 1851 1852 return true 1853 } 1854 1855 func (s *DockerSuite) TestRunWithBadDevice(c *check.C) { 1856 // Cannot run on Windows as Windows does not support --device 1857 testRequires(c, DaemonIsLinux) 1858 name := "baddevice" 1859 out, _, err := dockerCmdWithError("run", "--name", name, "--device", "/etc", "busybox", "true") 1860 1861 if err == nil { 1862 c.Fatal("Run should fail with bad device") 1863 } 1864 expected := `"/etc": not a device node` 1865 if !strings.Contains(out, expected) { 1866 c.Fatalf("Output should contain %q, actual out: %q", expected, out) 1867 } 1868 } 1869 1870 func (s *DockerSuite) TestRunEntrypoint(c *check.C) { 1871 name := "entrypoint" 1872 1873 out, _ := dockerCmd(c, "run", "--name", name, "--entrypoint", "echo", "busybox", "-n", "foobar") 1874 expected := "foobar" 1875 1876 if out != expected { 1877 c.Fatalf("Output should be %q, actual out: %q", expected, out) 1878 } 1879 } 1880 1881 func (s *DockerSuite) TestRunBindMounts(c *check.C) { 1882 testRequires(c, SameHostDaemon) 1883 if testEnv.OSType == "linux" { 1884 testRequires(c, DaemonIsLinux, NotUserNamespace) 1885 } 1886 1887 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 1888 1889 tmpDir, err := ioutil.TempDir("", "docker-test-container") 1890 if err != nil { 1891 c.Fatal(err) 1892 } 1893 1894 defer os.RemoveAll(tmpDir) 1895 writeFile(path.Join(tmpDir, "touch-me"), "", c) 1896 1897 // Test reading from a read-only bind mount 1898 out, _ := dockerCmd(c, "run", "-v", fmt.Sprintf("%s:%s/tmp:ro", tmpDir, prefix), "busybox", "ls", prefix+"/tmp") 1899 if !strings.Contains(out, "touch-me") { 1900 c.Fatal("Container failed to read from bind mount") 1901 } 1902 1903 // test writing to bind mount 1904 if testEnv.OSType == "windows" { 1905 dockerCmd(c, "run", "-v", fmt.Sprintf(`%s:c:\tmp:rw`, tmpDir), "busybox", "touch", "c:/tmp/holla") 1906 } else { 1907 dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla") 1908 } 1909 1910 readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist 1911 1912 // test mounting to an illegal destination directory 1913 _, _, err = dockerCmdWithError("run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".") 1914 if err == nil { 1915 c.Fatal("Container bind mounted illegal directory") 1916 } 1917 1918 // Windows does not (and likely never will) support mounting a single file 1919 if testEnv.OSType != "windows" { 1920 // test mount a file 1921 dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla") 1922 content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist 1923 expected := "yotta" 1924 if content != expected { 1925 c.Fatalf("Output should be %q, actual out: %q", expected, content) 1926 } 1927 } 1928 } 1929 1930 // Ensure that CIDFile gets deleted if it's empty 1931 // Perform this test by making `docker run` fail 1932 func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) { 1933 // Skip on Windows. Base image on Windows has a CMD set in the image. 1934 testRequires(c, DaemonIsLinux) 1935 1936 tmpDir, err := ioutil.TempDir("", "TestRunCidFile") 1937 if err != nil { 1938 c.Fatal(err) 1939 } 1940 defer os.RemoveAll(tmpDir) 1941 tmpCidFile := path.Join(tmpDir, "cid") 1942 1943 image := "emptyfs" 1944 if testEnv.OSType == "windows" { 1945 // Windows can't support an emptyfs image. Just use the regular Windows image 1946 image = testEnv.PlatformDefaults.BaseImage 1947 } 1948 out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, image) 1949 if err == nil { 1950 c.Fatalf("Run without command must fail. out=%s", out) 1951 } else if !strings.Contains(out, "No command specified") { 1952 c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err) 1953 } 1954 1955 if _, err := os.Stat(tmpCidFile); err == nil { 1956 c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile) 1957 } 1958 } 1959 1960 // #2098 - Docker cidFiles only contain short version of the containerId 1961 //sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test" 1962 // TestRunCidFile tests that run --cidfile returns the longid 1963 func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) { 1964 tmpDir, err := ioutil.TempDir("", "TestRunCidFile") 1965 if err != nil { 1966 c.Fatal(err) 1967 } 1968 tmpCidFile := path.Join(tmpDir, "cid") 1969 defer os.RemoveAll(tmpDir) 1970 1971 out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true") 1972 1973 id := strings.TrimSpace(out) 1974 buffer, err := ioutil.ReadFile(tmpCidFile) 1975 if err != nil { 1976 c.Fatal(err) 1977 } 1978 cid := string(buffer) 1979 if len(cid) != 64 { 1980 c.Fatalf("--cidfile should be a long id, not %q", id) 1981 } 1982 if cid != id { 1983 c.Fatalf("cid must be equal to %s, got %s", id, cid) 1984 } 1985 } 1986 1987 func (s *DockerSuite) TestRunSetMacAddress(c *check.C) { 1988 mac := "12:34:56:78:9a:bc" 1989 var out string 1990 if testEnv.OSType == "windows" { 1991 out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'") 1992 mac = strings.Replace(strings.ToUpper(mac), ":", "-", -1) // To Windows-style MACs 1993 } else { 1994 out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'") 1995 } 1996 1997 actualMac := strings.TrimSpace(out) 1998 if actualMac != mac { 1999 c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac) 2000 } 2001 } 2002 2003 func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) { 2004 // TODO Windows. Network settings are not propagated back to inspect. 2005 testRequires(c, DaemonIsLinux) 2006 mac := "12:34:56:78:9a:bc" 2007 out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top") 2008 2009 id := strings.TrimSpace(out) 2010 inspectedMac := inspectField(c, id, "NetworkSettings.Networks.bridge.MacAddress") 2011 if inspectedMac != mac { 2012 c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac) 2013 } 2014 } 2015 2016 // test docker run use an invalid mac address 2017 func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) { 2018 out, _, err := dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29", "busybox") 2019 //use an invalid mac address should with an error out 2020 if err == nil || !strings.Contains(out, "is not a valid mac address") { 2021 c.Fatalf("run with an invalid --mac-address should with error out") 2022 } 2023 } 2024 2025 func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) { 2026 // TODO Windows. Network settings are not propagated back to inspect. 2027 testRequires(c, SameHostDaemon, DaemonIsLinux) 2028 2029 out := cli.DockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top").Combined() 2030 2031 id := strings.TrimSpace(out) 2032 ip := inspectField(c, id, "NetworkSettings.Networks.bridge.IPAddress") 2033 icmd.RunCommand("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip), 2034 "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT").Assert(c, icmd.Success) 2035 2036 cli.DockerCmd(c, "rm", "-fv", id) 2037 2038 cli.DockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top") 2039 } 2040 2041 func (s *DockerSuite) TestRunPortInUse(c *check.C) { 2042 // TODO Windows. The duplicate NAT message returned by Windows will be 2043 // changing as is currently completely undecipherable. Does need modifying 2044 // to run sh rather than top though as top isn't in Windows busybox. 2045 testRequires(c, SameHostDaemon, DaemonIsLinux) 2046 2047 port := "1234" 2048 dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top") 2049 2050 out, _, err := dockerCmdWithError("run", "-d", "-p", port+":80", "busybox", "top") 2051 if err == nil { 2052 c.Fatalf("Binding on used port must fail") 2053 } 2054 if !strings.Contains(out, "port is already allocated") { 2055 c.Fatalf("Out must be about \"port is already allocated\", got %s", out) 2056 } 2057 } 2058 2059 // https://github.com/docker/docker/issues/12148 2060 func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) { 2061 // TODO Windows. -P is not yet supported 2062 testRequires(c, DaemonIsLinux) 2063 // allocate a dynamic port to get the most recent 2064 out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top") 2065 2066 id := strings.TrimSpace(out) 2067 out, _ = dockerCmd(c, "port", id, "80") 2068 2069 strPort := strings.Split(strings.TrimSpace(out), ":")[1] 2070 port, err := strconv.ParseInt(strPort, 10, 64) 2071 if err != nil { 2072 c.Fatalf("invalid port, got: %s, error: %s", strPort, err) 2073 } 2074 2075 // allocate a static port and a dynamic port together, with static port 2076 // takes the next recent port in dynamic port range. 2077 dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top") 2078 } 2079 2080 // Regression test for #7792 2081 func (s *DockerSuite) TestRunMountOrdering(c *check.C) { 2082 // TODO Windows: Post RS1. Windows does not support nested mounts. 2083 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2084 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 2085 2086 tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test") 2087 if err != nil { 2088 c.Fatal(err) 2089 } 2090 defer os.RemoveAll(tmpDir) 2091 2092 tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2") 2093 if err != nil { 2094 c.Fatal(err) 2095 } 2096 defer os.RemoveAll(tmpDir2) 2097 2098 // Create a temporary tmpfs mounc. 2099 fooDir := filepath.Join(tmpDir, "foo") 2100 if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil { 2101 c.Fatalf("failed to mkdir at %s - %s", fooDir, err) 2102 } 2103 2104 if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil { 2105 c.Fatal(err) 2106 } 2107 2108 if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil { 2109 c.Fatal(err) 2110 } 2111 2112 if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil { 2113 c.Fatal(err) 2114 } 2115 2116 dockerCmd(c, "run", 2117 "-v", fmt.Sprintf("%s:"+prefix+"/tmp", tmpDir), 2118 "-v", fmt.Sprintf("%s:"+prefix+"/tmp/foo", fooDir), 2119 "-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2", tmpDir2), 2120 "-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2/foo", fooDir), 2121 "busybox:latest", "sh", "-c", 2122 "ls "+prefix+"/tmp/touch-me && ls "+prefix+"/tmp/foo/touch-me && ls "+prefix+"/tmp/tmp2/touch-me && ls "+prefix+"/tmp/tmp2/foo/touch-me") 2123 } 2124 2125 // Regression test for https://github.com/docker/docker/issues/8259 2126 func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) { 2127 // Not applicable on Windows as Windows does not support volumes 2128 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2129 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 2130 2131 tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink") 2132 if err != nil { 2133 c.Fatal(err) 2134 } 2135 defer os.RemoveAll(tmpDir) 2136 2137 linkPath := os.TempDir() + "/testlink2" 2138 if err := os.Symlink(tmpDir, linkPath); err != nil { 2139 c.Fatal(err) 2140 } 2141 defer os.RemoveAll(linkPath) 2142 2143 // Create first container 2144 dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test") 2145 2146 // Create second container with same symlinked path 2147 // This will fail if the referenced issue is hit with a "Volume exists" error 2148 dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test") 2149 } 2150 2151 //GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container 2152 func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) { 2153 // While Windows supports volumes, it does not support --add-host hence 2154 // this test is not applicable on Windows. 2155 testRequires(c, DaemonIsLinux) 2156 out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf") 2157 if !strings.Contains(out, "nameserver 127.0.0.1") { 2158 c.Fatal("/etc volume mount hides /etc/resolv.conf") 2159 } 2160 2161 out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname") 2162 if !strings.Contains(out, "test123") { 2163 c.Fatal("/etc volume mount hides /etc/hostname") 2164 } 2165 2166 out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts") 2167 out = strings.Replace(out, "\n", " ", -1) 2168 if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") { 2169 c.Fatal("/etc volume mount hides /etc/hosts") 2170 } 2171 } 2172 2173 func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) { 2174 // TODO Windows (Post RS1). Windows does not support volumes which 2175 // are pre-populated such as is built in the dockerfile used in this test. 2176 testRequires(c, DaemonIsLinux) 2177 prefix, slash := getPrefixAndSlashFromDaemonPlatform() 2178 buildImageSuccessfully(c, "dataimage", build.WithDockerfile(`FROM busybox 2179 RUN ["mkdir", "-p", "/foo"] 2180 RUN ["touch", "/foo/bar"]`)) 2181 dockerCmd(c, "run", "--name", "test", "-v", prefix+slash+"foo", "busybox") 2182 2183 if out, _, err := dockerCmdWithError("run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") { 2184 c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out) 2185 } 2186 2187 tmpDir := RandomTmpDirPath("docker_test_bind_mount_copy_data", testEnv.OSType) 2188 if out, _, err := dockerCmdWithError("run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") { 2189 c.Fatalf("Data was copied on bind mount but shouldn't be:\n%q", out) 2190 } 2191 } 2192 2193 func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) { 2194 // just run with unknown image 2195 cmd := exec.Command(dockerBinary, "run", "asdfsg") 2196 stdout := bytes.NewBuffer(nil) 2197 cmd.Stdout = stdout 2198 if err := cmd.Run(); err == nil { 2199 c.Fatal("Run with unknown image should fail") 2200 } 2201 if stdout.Len() != 0 { 2202 c.Fatalf("Stdout contains output from pull: %s", stdout) 2203 } 2204 } 2205 2206 func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) { 2207 testRequires(c, SameHostDaemon) 2208 prefix, slash := getPrefixAndSlashFromDaemonPlatform() 2209 buildImageSuccessfully(c, "run_volumes_clean_paths", build.WithDockerfile(`FROM busybox 2210 VOLUME `+prefix+`/foo/`)) 2211 dockerCmd(c, "run", "-v", prefix+"/foo", "-v", prefix+"/bar/", "--name", "dark_helmet", "run_volumes_clean_paths") 2212 2213 out, err := inspectMountSourceField("dark_helmet", prefix+slash+"foo"+slash) 2214 if err != errMountNotFound { 2215 c.Fatalf("Found unexpected volume entry for '%s/foo/' in volumes\n%q", prefix, out) 2216 } 2217 2218 out, err = inspectMountSourceField("dark_helmet", prefix+slash+`foo`) 2219 c.Assert(err, check.IsNil) 2220 if !strings.Contains(strings.ToLower(out), strings.ToLower(testEnv.PlatformDefaults.VolumesConfigPath)) { 2221 c.Fatalf("Volume was not defined for %s/foo\n%q", prefix, out) 2222 } 2223 2224 out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar"+slash) 2225 if err != errMountNotFound { 2226 c.Fatalf("Found unexpected volume entry for '%s/bar/' in volumes\n%q", prefix, out) 2227 } 2228 2229 out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar") 2230 c.Assert(err, check.IsNil) 2231 if !strings.Contains(strings.ToLower(out), strings.ToLower(testEnv.PlatformDefaults.VolumesConfigPath)) { 2232 c.Fatalf("Volume was not defined for %s/bar\n%q", prefix, out) 2233 } 2234 } 2235 2236 // Regression test for #3631 2237 func (s *DockerSuite) TestRunSlowStdoutConsumer(c *check.C) { 2238 // TODO Windows: This should be able to run on Windows if can find an 2239 // alternate to /dev/zero and /dev/stdout. 2240 testRequires(c, DaemonIsLinux) 2241 2242 args := []string{"run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | cat -v"} 2243 cont := exec.Command(dockerBinary, args...) 2244 2245 stdout, err := cont.StdoutPipe() 2246 if err != nil { 2247 c.Fatal(err) 2248 } 2249 2250 if err := cont.Start(); err != nil { 2251 c.Fatal(err) 2252 } 2253 defer func() { go cont.Wait() }() 2254 n, err := ConsumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil) 2255 if err != nil { 2256 c.Fatal(err) 2257 } 2258 2259 expected := 2 * 1024 * 2000 2260 if n != expected { 2261 c.Fatalf("Expected %d, got %d", expected, n) 2262 } 2263 } 2264 2265 func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) { 2266 // TODO Windows: -P is not currently supported. Also network 2267 // settings are not propagated back. 2268 testRequires(c, DaemonIsLinux) 2269 out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top") 2270 2271 id := strings.TrimSpace(out) 2272 portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports") 2273 var ports nat.PortMap 2274 if err := json.Unmarshal([]byte(portstr), &ports); err != nil { 2275 c.Fatal(err) 2276 } 2277 for port, binding := range ports { 2278 portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0]) 2279 if portnum < 3000 || portnum > 3003 { 2280 c.Fatalf("Port %d is out of range ", portnum) 2281 } 2282 if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 { 2283 c.Fatalf("Port is not mapped for the port %s", port) 2284 } 2285 } 2286 } 2287 2288 func (s *DockerSuite) TestRunExposePort(c *check.C) { 2289 out, _, err := dockerCmdWithError("run", "--expose", "80000", "busybox") 2290 c.Assert(err, checker.NotNil, check.Commentf("--expose with an invalid port should error out")) 2291 c.Assert(out, checker.Contains, "invalid range format for --expose") 2292 } 2293 2294 func (s *DockerSuite) TestRunModeIpcHost(c *check.C) { 2295 // Not applicable on Windows as uses Unix-specific capabilities 2296 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2297 2298 hostIpc, err := os.Readlink("/proc/1/ns/ipc") 2299 if err != nil { 2300 c.Fatal(err) 2301 } 2302 2303 out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc") 2304 out = strings.Trim(out, "\n") 2305 if hostIpc != out { 2306 c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out) 2307 } 2308 2309 out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc") 2310 out = strings.Trim(out, "\n") 2311 if hostIpc == out { 2312 c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out) 2313 } 2314 } 2315 2316 func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) { 2317 // Not applicable on Windows as uses Unix-specific capabilities 2318 testRequires(c, DaemonIsLinux) 2319 out, _, err := dockerCmdWithError("run", "-d", "--ipc", "container:abcd1234", "busybox", "top") 2320 if !strings.Contains(out, "abcd1234") || err == nil { 2321 c.Fatalf("run IPC from a non exists container should with correct error out") 2322 } 2323 } 2324 2325 func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) { 2326 // Not applicable on Windows as uses Unix-specific capabilities 2327 testRequires(c, SameHostDaemon, DaemonIsLinux) 2328 2329 out, _ := dockerCmd(c, "create", "busybox") 2330 2331 id := strings.TrimSpace(out) 2332 out, _, err := dockerCmdWithError("run", fmt.Sprintf("--ipc=container:%s", id), "busybox") 2333 if err == nil { 2334 c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err) 2335 } 2336 } 2337 2338 func (s *DockerSuite) TestRunModePIDContainer(c *check.C) { 2339 // Not applicable on Windows as uses Unix-specific capabilities 2340 testRequires(c, SameHostDaemon, DaemonIsLinux) 2341 2342 out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "top") 2343 2344 id := strings.TrimSpace(out) 2345 state := inspectField(c, id, "State.Running") 2346 if state != "true" { 2347 c.Fatal("Container state is 'not running'") 2348 } 2349 pid1 := inspectField(c, id, "State.Pid") 2350 2351 parentContainerPid, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/pid", pid1)) 2352 if err != nil { 2353 c.Fatal(err) 2354 } 2355 2356 out, _ = dockerCmd(c, "run", fmt.Sprintf("--pid=container:%s", id), "busybox", "readlink", "/proc/self/ns/pid") 2357 out = strings.Trim(out, "\n") 2358 if parentContainerPid != out { 2359 c.Fatalf("PID different with --pid=container:%s %s != %s\n", id, parentContainerPid, out) 2360 } 2361 } 2362 2363 func (s *DockerSuite) TestRunModePIDContainerNotExists(c *check.C) { 2364 // Not applicable on Windows as uses Unix-specific capabilities 2365 testRequires(c, DaemonIsLinux) 2366 out, _, err := dockerCmdWithError("run", "-d", "--pid", "container:abcd1234", "busybox", "top") 2367 if !strings.Contains(out, "abcd1234") || err == nil { 2368 c.Fatalf("run PID from a non exists container should with correct error out") 2369 } 2370 } 2371 2372 func (s *DockerSuite) TestRunModePIDContainerNotRunning(c *check.C) { 2373 // Not applicable on Windows as uses Unix-specific capabilities 2374 testRequires(c, SameHostDaemon, DaemonIsLinux) 2375 2376 out, _ := dockerCmd(c, "create", "busybox") 2377 2378 id := strings.TrimSpace(out) 2379 out, _, err := dockerCmdWithError("run", fmt.Sprintf("--pid=container:%s", id), "busybox") 2380 if err == nil { 2381 c.Fatalf("Run container with pid mode container should fail with non running container: %s\n%s", out, err) 2382 } 2383 } 2384 2385 func (s *DockerSuite) TestRunMountShmMqueueFromHost(c *check.C) { 2386 // Not applicable on Windows as uses Unix-specific capabilities 2387 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2388 2389 dockerCmd(c, "run", "-d", "--name", "shmfromhost", "-v", "/dev/shm:/dev/shm", "-v", "/dev/mqueue:/dev/mqueue", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && touch /dev/mqueue/toto && top") 2390 defer os.Remove("/dev/mqueue/toto") 2391 defer os.Remove("/dev/shm/test") 2392 volPath, err := inspectMountSourceField("shmfromhost", "/dev/shm") 2393 c.Assert(err, checker.IsNil) 2394 if volPath != "/dev/shm" { 2395 c.Fatalf("volumePath should have been /dev/shm, was %s", volPath) 2396 } 2397 2398 out, _ := dockerCmd(c, "run", "--name", "ipchost", "--ipc", "host", "busybox", "cat", "/dev/shm/test") 2399 if out != "test" { 2400 c.Fatalf("Output of /dev/shm/test expected test but found: %s", out) 2401 } 2402 2403 // Check that the mq was created 2404 if _, err := os.Stat("/dev/mqueue/toto"); err != nil { 2405 c.Fatalf("Failed to confirm '/dev/mqueue/toto' presence on host: %s", err.Error()) 2406 } 2407 } 2408 2409 func (s *DockerSuite) TestContainerNetworkMode(c *check.C) { 2410 // Not applicable on Windows as uses Unix-specific capabilities 2411 testRequires(c, SameHostDaemon, DaemonIsLinux) 2412 2413 out, _ := dockerCmd(c, "run", "-d", "busybox", "top") 2414 id := strings.TrimSpace(out) 2415 c.Assert(waitRun(id), check.IsNil) 2416 pid1 := inspectField(c, id, "State.Pid") 2417 2418 parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1)) 2419 if err != nil { 2420 c.Fatal(err) 2421 } 2422 2423 out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net") 2424 out = strings.Trim(out, "\n") 2425 if parentContainerNet != out { 2426 c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out) 2427 } 2428 } 2429 2430 func (s *DockerSuite) TestRunModePIDHost(c *check.C) { 2431 // Not applicable on Windows as uses Unix-specific capabilities 2432 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2433 2434 hostPid, err := os.Readlink("/proc/1/ns/pid") 2435 if err != nil { 2436 c.Fatal(err) 2437 } 2438 2439 out, _ := dockerCmd(c, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid") 2440 out = strings.Trim(out, "\n") 2441 if hostPid != out { 2442 c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out) 2443 } 2444 2445 out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/pid") 2446 out = strings.Trim(out, "\n") 2447 if hostPid == out { 2448 c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out) 2449 } 2450 } 2451 2452 func (s *DockerSuite) TestRunModeUTSHost(c *check.C) { 2453 // Not applicable on Windows as uses Unix-specific capabilities 2454 testRequires(c, SameHostDaemon, DaemonIsLinux) 2455 2456 hostUTS, err := os.Readlink("/proc/1/ns/uts") 2457 if err != nil { 2458 c.Fatal(err) 2459 } 2460 2461 out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts") 2462 out = strings.Trim(out, "\n") 2463 if hostUTS != out { 2464 c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out) 2465 } 2466 2467 out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts") 2468 out = strings.Trim(out, "\n") 2469 if hostUTS == out { 2470 c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out) 2471 } 2472 2473 out, _ = dockerCmdWithFail(c, "run", "-h=name", "--uts=host", "busybox", "ps") 2474 c.Assert(out, checker.Contains, runconfig.ErrConflictUTSHostname.Error()) 2475 } 2476 2477 func (s *DockerSuite) TestRunTLSVerify(c *check.C) { 2478 // Remote daemons use TLS and this test is not applicable when TLS is required. 2479 testRequires(c, SameHostDaemon) 2480 if out, code, err := dockerCmdWithError("ps"); err != nil || code != 0 { 2481 c.Fatalf("Should have worked: %v:\n%v", err, out) 2482 } 2483 2484 // Regardless of whether we specify true or false we need to 2485 // test to make sure tls is turned on if --tlsverify is specified at all 2486 result := dockerCmdWithResult("--tlsverify=false", "ps") 2487 result.Assert(c, icmd.Expected{ExitCode: 1, Err: "error during connect"}) 2488 2489 result = dockerCmdWithResult("--tlsverify=true", "ps") 2490 result.Assert(c, icmd.Expected{ExitCode: 1, Err: "cert"}) 2491 } 2492 2493 func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) { 2494 // TODO Windows. Once moved to libnetwork/CNM, this may be able to be 2495 // re-instated. 2496 testRequires(c, DaemonIsLinux) 2497 // first find allocator current position 2498 out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top") 2499 2500 id := strings.TrimSpace(out) 2501 out, _ = dockerCmd(c, "port", id) 2502 2503 out = strings.TrimSpace(out) 2504 if out == "" { 2505 c.Fatal("docker port command output is empty") 2506 } 2507 out = strings.Split(out, ":")[1] 2508 lastPort, err := strconv.Atoi(out) 2509 if err != nil { 2510 c.Fatal(err) 2511 } 2512 port := lastPort + 1 2513 l, err := net.Listen("tcp", ":"+strconv.Itoa(port)) 2514 if err != nil { 2515 c.Fatal(err) 2516 } 2517 defer l.Close() 2518 2519 out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top") 2520 2521 id = strings.TrimSpace(out) 2522 dockerCmd(c, "port", id) 2523 } 2524 2525 func (s *DockerSuite) TestRunTTYWithPipe(c *check.C) { 2526 errChan := make(chan error) 2527 go func() { 2528 defer close(errChan) 2529 2530 cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true") 2531 if _, err := cmd.StdinPipe(); err != nil { 2532 errChan <- err 2533 return 2534 } 2535 2536 expected := "the input device is not a TTY" 2537 if runtime.GOOS == "windows" { 2538 expected += ". If you are using mintty, try prefixing the command with 'winpty'" 2539 } 2540 if out, _, err := runCommandWithOutput(cmd); err == nil { 2541 errChan <- fmt.Errorf("run should have failed") 2542 return 2543 } else if !strings.Contains(out, expected) { 2544 errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected) 2545 return 2546 } 2547 }() 2548 2549 select { 2550 case err := <-errChan: 2551 c.Assert(err, check.IsNil) 2552 case <-time.After(30 * time.Second): 2553 c.Fatal("container is running but should have failed") 2554 } 2555 } 2556 2557 func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) { 2558 addr := "00:16:3E:08:00:50" 2559 args := []string{"run", "--mac-address", addr} 2560 expected := addr 2561 2562 if testEnv.OSType != "windows" { 2563 args = append(args, "busybox", "ifconfig") 2564 } else { 2565 args = append(args, testEnv.PlatformDefaults.BaseImage, "ipconfig", "/all") 2566 expected = strings.Replace(strings.ToUpper(addr), ":", "-", -1) 2567 } 2568 2569 if out, _ := dockerCmd(c, args...); !strings.Contains(out, expected) { 2570 c.Fatalf("Output should have contained %q: %s", expected, out) 2571 } 2572 } 2573 2574 func (s *DockerSuite) TestRunNetHost(c *check.C) { 2575 // Not applicable on Windows as uses Unix-specific capabilities 2576 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2577 2578 hostNet, err := os.Readlink("/proc/1/ns/net") 2579 if err != nil { 2580 c.Fatal(err) 2581 } 2582 2583 out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net") 2584 out = strings.Trim(out, "\n") 2585 if hostNet != out { 2586 c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out) 2587 } 2588 2589 out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net") 2590 out = strings.Trim(out, "\n") 2591 if hostNet == out { 2592 c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out) 2593 } 2594 } 2595 2596 func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) { 2597 // TODO Windows. As Windows networking evolves and converges towards 2598 // CNM, this test may be possible to enable on Windows. 2599 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2600 2601 dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") 2602 dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") 2603 } 2604 2605 func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) { 2606 // Not applicable on Windows as uses Unix-specific capabilities 2607 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2608 2609 hostNet, err := os.Readlink("/proc/1/ns/net") 2610 if err != nil { 2611 c.Fatal(err) 2612 } 2613 2614 dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top") 2615 2616 out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net") 2617 out = strings.Trim(out, "\n") 2618 if hostNet != out { 2619 c.Fatalf("Container should have host network namespace") 2620 } 2621 } 2622 2623 func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) { 2624 // TODO Windows. This may be possible to enable in the future. However, 2625 // Windows does not currently support --expose, or populate the network 2626 // settings seen through inspect. 2627 testRequires(c, DaemonIsLinux) 2628 out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top") 2629 2630 id := strings.TrimSpace(out) 2631 portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports") 2632 2633 var ports nat.PortMap 2634 err := json.Unmarshal([]byte(portstr), &ports) 2635 c.Assert(err, checker.IsNil, check.Commentf("failed to unmarshal: %v", portstr)) 2636 for port, binding := range ports { 2637 portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0]) 2638 if portnum < 3000 || portnum > 3003 { 2639 c.Fatalf("Port %d is out of range ", portnum) 2640 } 2641 if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 { 2642 c.Fatal("Port is not mapped for the port "+port, out) 2643 } 2644 } 2645 } 2646 2647 func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) { 2648 runSleepingContainer(c, "--name=testrunsetdefaultrestartpolicy") 2649 out := inspectField(c, "testrunsetdefaultrestartpolicy", "HostConfig.RestartPolicy.Name") 2650 if out != "no" { 2651 c.Fatalf("Set default restart policy failed") 2652 } 2653 } 2654 2655 func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) { 2656 out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false") 2657 timeout := 10 * time.Second 2658 if testEnv.OSType == "windows" { 2659 timeout = 120 * time.Second 2660 } 2661 2662 id := strings.TrimSpace(string(out)) 2663 if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", timeout); err != nil { 2664 c.Fatal(err) 2665 } 2666 2667 count := inspectField(c, id, "RestartCount") 2668 if count != "3" { 2669 c.Fatalf("Container was restarted %s times, expected %d", count, 3) 2670 } 2671 2672 MaximumRetryCount := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") 2673 if MaximumRetryCount != "3" { 2674 c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3") 2675 } 2676 } 2677 2678 func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *check.C) { 2679 dockerCmd(c, "run", "--rm", "busybox", "touch", "/file") 2680 } 2681 2682 func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *check.C) { 2683 // Not applicable on Windows which does not support --read-only 2684 testRequires(c, DaemonIsLinux, UserNamespaceROMount) 2685 2686 testPriv := true 2687 // don't test privileged mode subtest if user namespaces enabled 2688 if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" { 2689 testPriv = false 2690 } 2691 testReadOnlyFile(c, testPriv, "/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname", "/sys/kernel") 2692 } 2693 2694 func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *check.C) { 2695 // Not applicable on Windows due to use of Unix specific functionality, plus 2696 // the use of --read-only which is not supported. 2697 testRequires(c, DaemonIsLinux, UserNamespaceROMount) 2698 2699 // Ensure we have not broken writing /dev/pts 2700 out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount") 2701 if status != 0 { 2702 c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.") 2703 } 2704 expected := "type devpts (rw," 2705 if !strings.Contains(string(out), expected) { 2706 c.Fatalf("expected output to contain %s but contains %s", expected, out) 2707 } 2708 } 2709 2710 func testReadOnlyFile(c *check.C, testPriv bool, filenames ...string) { 2711 touch := "touch " + strings.Join(filenames, " ") 2712 out, _, err := dockerCmdWithError("run", "--read-only", "--rm", "busybox", "sh", "-c", touch) 2713 c.Assert(err, checker.NotNil) 2714 2715 for _, f := range filenames { 2716 expected := "touch: " + f + ": Read-only file system" 2717 c.Assert(out, checker.Contains, expected) 2718 } 2719 2720 if !testPriv { 2721 return 2722 } 2723 2724 out, _, err = dockerCmdWithError("run", "--read-only", "--privileged", "--rm", "busybox", "sh", "-c", touch) 2725 c.Assert(err, checker.NotNil) 2726 2727 for _, f := range filenames { 2728 expected := "touch: " + f + ": Read-only file system" 2729 c.Assert(out, checker.Contains, expected) 2730 } 2731 } 2732 2733 func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *check.C) { 2734 // Not applicable on Windows which does not support --link 2735 testRequires(c, DaemonIsLinux, UserNamespaceROMount) 2736 2737 dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top") 2738 2739 out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts") 2740 if !strings.Contains(string(out), "testlinked") { 2741 c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled") 2742 } 2743 } 2744 2745 func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDNSFlag(c *check.C) { 2746 // Not applicable on Windows which does not support either --read-only or --dns. 2747 testRequires(c, DaemonIsLinux, UserNamespaceROMount) 2748 2749 out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf") 2750 if !strings.Contains(string(out), "1.1.1.1") { 2751 c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used") 2752 } 2753 } 2754 2755 func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *check.C) { 2756 // Not applicable on Windows which does not support --read-only 2757 testRequires(c, DaemonIsLinux, UserNamespaceROMount) 2758 2759 out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts") 2760 if !strings.Contains(string(out), "testreadonly") { 2761 c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used") 2762 } 2763 } 2764 2765 func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *check.C) { 2766 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 2767 runSleepingContainer(c, "--name=voltest", "-v", prefix+"/foo") 2768 runSleepingContainer(c, "--name=restarter", "--volumes-from", "voltest") 2769 2770 // Remove the main volume container and restart the consuming container 2771 dockerCmd(c, "rm", "-f", "voltest") 2772 2773 // This should not fail since the volumes-from were already applied 2774 dockerCmd(c, "restart", "restarter") 2775 } 2776 2777 // run container with --rm should remove container if exit code != 0 2778 func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.C) { 2779 existingContainers := ExistingContainerIDs(c) 2780 name := "flowers" 2781 cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "ls", "/notexists")).Assert(c, icmd.Expected{ 2782 ExitCode: 1, 2783 }) 2784 2785 out := cli.DockerCmd(c, "ps", "-q", "-a").Combined() 2786 out = RemoveOutputForExistingElements(out, existingContainers) 2787 if out != "" { 2788 c.Fatal("Expected not to have containers", out) 2789 } 2790 } 2791 2792 func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C) { 2793 existingContainers := ExistingContainerIDs(c) 2794 name := "sparkles" 2795 cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "commandNotFound")).Assert(c, icmd.Expected{ 2796 ExitCode: 127, 2797 }) 2798 out := cli.DockerCmd(c, "ps", "-q", "-a").Combined() 2799 out = RemoveOutputForExistingElements(out, existingContainers) 2800 if out != "" { 2801 c.Fatal("Expected not to have containers", out) 2802 } 2803 } 2804 2805 func (s *DockerSuite) TestRunPIDHostWithChildIsKillable(c *check.C) { 2806 // Not applicable on Windows as uses Unix specific functionality 2807 testRequires(c, DaemonIsLinux, NotUserNamespace) 2808 name := "ibuildthecloud" 2809 dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi") 2810 2811 c.Assert(waitRun(name), check.IsNil) 2812 2813 errchan := make(chan error) 2814 go func() { 2815 if out, _, err := dockerCmdWithError("kill", name); err != nil { 2816 errchan <- fmt.Errorf("%v:\n%s", err, out) 2817 } 2818 close(errchan) 2819 }() 2820 select { 2821 case err := <-errchan: 2822 c.Assert(err, check.IsNil) 2823 case <-time.After(5 * time.Second): 2824 c.Fatal("Kill container timed out") 2825 } 2826 } 2827 2828 func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *check.C) { 2829 // TODO Windows. This may be possible to enable once Windows supports 2830 // memory limits on containers 2831 testRequires(c, DaemonIsLinux) 2832 // this memory limit is 1 byte less than the min, which is 4MB 2833 // https://github.com/docker/docker/blob/v1.5.0/daemon/create.go#L22 2834 out, _, err := dockerCmdWithError("run", "-m", "4194303", "busybox") 2835 if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 4MB") { 2836 c.Fatalf("expected run to fail when using too low a memory limit: %q", out) 2837 } 2838 } 2839 2840 func (s *DockerSuite) TestRunWriteToProcAsound(c *check.C) { 2841 // Not applicable on Windows as uses Unix specific functionality 2842 testRequires(c, DaemonIsLinux) 2843 _, code, err := dockerCmdWithError("run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version") 2844 if err == nil || code == 0 { 2845 c.Fatal("standard container should not be able to write to /proc/asound") 2846 } 2847 } 2848 2849 func (s *DockerSuite) TestRunReadProcTimer(c *check.C) { 2850 // Not applicable on Windows as uses Unix specific functionality 2851 testRequires(c, DaemonIsLinux) 2852 out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/timer_stats") 2853 if code != 0 { 2854 return 2855 } 2856 if err != nil { 2857 c.Fatal(err) 2858 } 2859 if strings.Trim(out, "\n ") != "" { 2860 c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out) 2861 } 2862 } 2863 2864 func (s *DockerSuite) TestRunReadProcLatency(c *check.C) { 2865 // Not applicable on Windows as uses Unix specific functionality 2866 testRequires(c, DaemonIsLinux) 2867 // some kernels don't have this configured so skip the test if this file is not found 2868 // on the host running the tests. 2869 if _, err := os.Stat("/proc/latency_stats"); err != nil { 2870 c.Skip("kernel doesn't have latency_stats configured") 2871 return 2872 } 2873 out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/latency_stats") 2874 if code != 0 { 2875 return 2876 } 2877 if err != nil { 2878 c.Fatal(err) 2879 } 2880 if strings.Trim(out, "\n ") != "" { 2881 c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out) 2882 } 2883 } 2884 2885 func (s *DockerSuite) TestRunReadFilteredProc(c *check.C) { 2886 // Not applicable on Windows as uses Unix specific functionality 2887 testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace) 2888 2889 testReadPaths := []string{ 2890 "/proc/latency_stats", 2891 "/proc/timer_stats", 2892 "/proc/kcore", 2893 } 2894 for i, filePath := range testReadPaths { 2895 name := fmt.Sprintf("procsieve-%d", i) 2896 shellCmd := fmt.Sprintf("exec 3<%s", filePath) 2897 2898 out, exitCode, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd) 2899 if exitCode != 0 { 2900 return 2901 } 2902 if err != nil { 2903 c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err) 2904 } 2905 } 2906 } 2907 2908 func (s *DockerSuite) TestMountIntoProc(c *check.C) { 2909 // Not applicable on Windows as uses Unix specific functionality 2910 testRequires(c, DaemonIsLinux) 2911 _, code, err := dockerCmdWithError("run", "-v", "/proc//sys", "busybox", "true") 2912 if err == nil || code == 0 { 2913 c.Fatal("container should not be able to mount into /proc") 2914 } 2915 } 2916 2917 func (s *DockerSuite) TestMountIntoSys(c *check.C) { 2918 // Not applicable on Windows as uses Unix specific functionality 2919 testRequires(c, DaemonIsLinux) 2920 testRequires(c, NotUserNamespace) 2921 dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true") 2922 } 2923 2924 func (s *DockerSuite) TestRunUnshareProc(c *check.C) { 2925 // Not applicable on Windows as uses Unix specific functionality 2926 testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace) 2927 2928 // In this test goroutines are used to run test cases in parallel to prevent the test from taking a long time to run. 2929 errChan := make(chan error) 2930 2931 go func() { 2932 name := "acidburn" 2933 out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount") 2934 if err == nil || 2935 !(strings.Contains(strings.ToLower(out), "permission denied") || 2936 strings.Contains(strings.ToLower(out), "operation not permitted")) { 2937 errChan <- fmt.Errorf("unshare with --mount-proc should have failed with 'permission denied' or 'operation not permitted', got: %s, %v", out, err) 2938 } else { 2939 errChan <- nil 2940 } 2941 }() 2942 2943 go func() { 2944 name := "cereal" 2945 out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc") 2946 if err == nil || 2947 !(strings.Contains(strings.ToLower(out), "mount: cannot mount none") || 2948 strings.Contains(strings.ToLower(out), "permission denied") || 2949 strings.Contains(strings.ToLower(out), "operation not permitted")) { 2950 errChan <- fmt.Errorf("unshare and mount of /proc should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err) 2951 } else { 2952 errChan <- nil 2953 } 2954 }() 2955 2956 /* Ensure still fails if running privileged with the default policy */ 2957 go func() { 2958 name := "crashoverride" 2959 out, _, err := dockerCmdWithError("run", "--privileged", "--security-opt", "seccomp=unconfined", "--security-opt", "apparmor=docker-default", "--name", name, "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc") 2960 if err == nil || 2961 !(strings.Contains(strings.ToLower(out), "mount: cannot mount none") || 2962 strings.Contains(strings.ToLower(out), "permission denied") || 2963 strings.Contains(strings.ToLower(out), "operation not permitted")) { 2964 errChan <- fmt.Errorf("privileged unshare with apparmor should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err) 2965 } else { 2966 errChan <- nil 2967 } 2968 }() 2969 2970 var retErr error 2971 for i := 0; i < 3; i++ { 2972 err := <-errChan 2973 if retErr == nil && err != nil { 2974 retErr = err 2975 } 2976 } 2977 if retErr != nil { 2978 c.Fatal(retErr) 2979 } 2980 } 2981 2982 func (s *DockerSuite) TestRunPublishPort(c *check.C) { 2983 // TODO Windows: This may be possible once Windows moves to libnetwork and CNM 2984 testRequires(c, DaemonIsLinux) 2985 dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top") 2986 out, _ := dockerCmd(c, "port", "test") 2987 out = strings.Trim(out, "\r\n") 2988 if out != "" { 2989 c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out) 2990 } 2991 } 2992 2993 // Issue #10184. 2994 func (s *DockerSuite) TestDevicePermissions(c *check.C) { 2995 // Not applicable on Windows as uses Unix specific functionality 2996 testRequires(c, DaemonIsLinux) 2997 const permissions = "crw-rw-rw-" 2998 out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse") 2999 if status != 0 { 3000 c.Fatalf("expected status 0, got %d", status) 3001 } 3002 if !strings.HasPrefix(out, permissions) { 3003 c.Fatalf("output should begin with %q, got %q", permissions, out) 3004 } 3005 } 3006 3007 func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) { 3008 // Not applicable on Windows as uses Unix specific functionality 3009 testRequires(c, DaemonIsLinux) 3010 out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok") 3011 3012 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 3013 c.Fatalf("expected output ok received %s", actual) 3014 } 3015 } 3016 3017 // https://github.com/docker/docker/pull/14498 3018 func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) { 3019 prefix, slash := getPrefixAndSlashFromDaemonPlatform() 3020 3021 dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "true") 3022 3023 dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true") 3024 dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true") 3025 3026 if testEnv.OSType != "windows" { 3027 mRO, err := inspectMountPoint("test-volumes-1", prefix+slash+"test") 3028 c.Assert(err, checker.IsNil, check.Commentf("failed to inspect mount point")) 3029 if mRO.RW { 3030 c.Fatalf("Expected RO volume was RW") 3031 } 3032 } 3033 3034 mRW, err := inspectMountPoint("test-volumes-2", prefix+slash+"test") 3035 c.Assert(err, checker.IsNil, check.Commentf("failed to inspect mount point")) 3036 if !mRW.RW { 3037 c.Fatalf("Expected RW volume was RO") 3038 } 3039 } 3040 3041 func (s *DockerSuite) TestRunWriteFilteredProc(c *check.C) { 3042 // Not applicable on Windows as uses Unix specific functionality 3043 testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace) 3044 3045 testWritePaths := []string{ 3046 /* modprobe and core_pattern should both be denied by generic 3047 * policy of denials for /proc/sys/kernel. These files have been 3048 * picked to be checked as they are particularly sensitive to writes */ 3049 "/proc/sys/kernel/modprobe", 3050 "/proc/sys/kernel/core_pattern", 3051 "/proc/sysrq-trigger", 3052 "/proc/kcore", 3053 } 3054 for i, filePath := range testWritePaths { 3055 name := fmt.Sprintf("writeprocsieve-%d", i) 3056 3057 shellCmd := fmt.Sprintf("exec 3>%s", filePath) 3058 out, code, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd) 3059 if code != 0 { 3060 return 3061 } 3062 if err != nil { 3063 c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err) 3064 } 3065 } 3066 } 3067 3068 func (s *DockerSuite) TestRunNetworkFilesBindMount(c *check.C) { 3069 // Not applicable on Windows as uses Unix specific functionality 3070 testRequires(c, SameHostDaemon, DaemonIsLinux) 3071 3072 expected := "test123" 3073 3074 filename := createTmpFile(c, expected) 3075 defer os.Remove(filename) 3076 3077 // for user namespaced test runs, the temp file must be accessible to unprivileged root 3078 if err := os.Chmod(filename, 0646); err != nil { 3079 c.Fatalf("error modifying permissions of %s: %v", filename, err) 3080 } 3081 3082 nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} 3083 3084 for i := range nwfiles { 3085 actual, _ := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i]) 3086 if actual != expected { 3087 c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual) 3088 } 3089 } 3090 } 3091 3092 func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *check.C) { 3093 // Not applicable on Windows as uses Unix specific functionality 3094 testRequires(c, SameHostDaemon, DaemonIsLinux) 3095 3096 filename := createTmpFile(c, "test123") 3097 defer os.Remove(filename) 3098 3099 // for user namespaced test runs, the temp file must be accessible to unprivileged root 3100 if err := os.Chmod(filename, 0646); err != nil { 3101 c.Fatalf("error modifying permissions of %s: %v", filename, err) 3102 } 3103 3104 nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} 3105 3106 for i := range nwfiles { 3107 _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "busybox", "touch", nwfiles[i]) 3108 if err == nil || exitCode == 0 { 3109 c.Fatalf("run should fail because bind mount of %s is ro: exit code %d", nwfiles[i], exitCode) 3110 } 3111 } 3112 } 3113 3114 func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *check.C) { 3115 // Not applicable on Windows as uses Unix specific functionality 3116 testRequires(c, SameHostDaemon, DaemonIsLinux, UserNamespaceROMount) 3117 3118 filename := createTmpFile(c, "test123") 3119 defer os.Remove(filename) 3120 3121 // for user namespaced test runs, the temp file must be accessible to unprivileged root 3122 if err := os.Chmod(filename, 0646); err != nil { 3123 c.Fatalf("error modifying permissions of %s: %v", filename, err) 3124 } 3125 3126 nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} 3127 3128 for i := range nwfiles { 3129 _, exitCode := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i]) 3130 if exitCode != 0 { 3131 c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode) 3132 } 3133 } 3134 3135 for i := range nwfiles { 3136 _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "--read-only", "busybox", "touch", nwfiles[i]) 3137 if err == nil || exitCode == 0 { 3138 c.Fatalf("run should fail because %s is mounted read-only on read-only root filesystem: exit code %d", nwfiles[i], exitCode) 3139 } 3140 } 3141 } 3142 3143 func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *check.C) { 3144 // Not applicable on Windows as uses Unix specific functionality 3145 testRequires(c, DaemonIsLinux, SameHostDaemon) 3146 3147 out, _ := dockerCmd(c, "run", "-d", "busybox", "top") 3148 id := strings.TrimSpace(out) 3149 c.Assert(waitRun(id), check.IsNil) 3150 pid1 := inspectField(c, id, "State.Pid") 3151 3152 _, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1)) 3153 if err != nil { 3154 c.Fatal(err) 3155 } 3156 } 3157 3158 func (s *DockerSuite) TestAppArmorDeniesPtrace(c *check.C) { 3159 // Not applicable on Windows as uses Unix specific functionality 3160 testRequires(c, SameHostDaemon, Apparmor, DaemonIsLinux) 3161 3162 // Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace 3163 // itself, but pid>1 should not be able to trace pid1. 3164 _, exitCode, _ := dockerCmdWithError("run", "busybox", "sh", "-c", "sh -c readlink /proc/1/ns/net") 3165 if exitCode == 0 { 3166 c.Fatal("ptrace was not successfully restricted by AppArmor") 3167 } 3168 } 3169 3170 func (s *DockerSuite) TestAppArmorTraceSelf(c *check.C) { 3171 // Not applicable on Windows as uses Unix specific functionality 3172 testRequires(c, DaemonIsLinux, SameHostDaemon, Apparmor) 3173 3174 _, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net") 3175 if exitCode != 0 { 3176 c.Fatal("ptrace of self failed.") 3177 } 3178 } 3179 3180 func (s *DockerSuite) TestAppArmorDeniesChmodProc(c *check.C) { 3181 // Not applicable on Windows as uses Unix specific functionality 3182 testRequires(c, SameHostDaemon, Apparmor, DaemonIsLinux, NotUserNamespace) 3183 _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo") 3184 if exitCode == 0 { 3185 // If our test failed, attempt to repair the host system... 3186 _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "444", "/proc/cpuinfo") 3187 if exitCode == 0 { 3188 c.Fatal("AppArmor was unsuccessful in prohibiting chmod of /proc/* files.") 3189 } 3190 } 3191 } 3192 3193 func (s *DockerSuite) TestRunCapAddSYSTIME(c *check.C) { 3194 // Not applicable on Windows as uses Unix specific functionality 3195 testRequires(c, DaemonIsLinux) 3196 3197 dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$") 3198 } 3199 3200 // run create container failed should clean up the container 3201 func (s *DockerSuite) TestRunCreateContainerFailedCleanUp(c *check.C) { 3202 // TODO Windows. This may be possible to enable once link is supported 3203 testRequires(c, DaemonIsLinux) 3204 name := "unique_name" 3205 _, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox") 3206 c.Assert(err, check.NotNil, check.Commentf("Expected docker run to fail!")) 3207 3208 containerID, err := inspectFieldWithError(name, "Id") 3209 c.Assert(err, checker.NotNil, check.Commentf("Expected not to have this container: %s!", containerID)) 3210 c.Assert(containerID, check.Equals, "", check.Commentf("Expected not to have this container: %s!", containerID)) 3211 } 3212 3213 func (s *DockerSuite) TestRunNamedVolume(c *check.C) { 3214 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 3215 testRequires(c, DaemonIsLinux) 3216 dockerCmd(c, "run", "--name=test", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "echo hello > "+prefix+"/foo/bar") 3217 3218 out, _ := dockerCmd(c, "run", "--volumes-from", "test", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar") 3219 c.Assert(strings.TrimSpace(out), check.Equals, "hello") 3220 3221 out, _ = dockerCmd(c, "run", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar") 3222 c.Assert(strings.TrimSpace(out), check.Equals, "hello") 3223 } 3224 3225 func (s *DockerSuite) TestRunWithUlimits(c *check.C) { 3226 // Not applicable on Windows as uses Unix specific functionality 3227 testRequires(c, DaemonIsLinux) 3228 3229 out, _ := dockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n") 3230 ul := strings.TrimSpace(out) 3231 if ul != "42" { 3232 c.Fatalf("expected `ulimit -n` to be 42, got %s", ul) 3233 } 3234 } 3235 3236 func (s *DockerSuite) TestRunContainerWithCgroupParent(c *check.C) { 3237 // Not applicable on Windows as uses Unix specific functionality 3238 testRequires(c, DaemonIsLinux) 3239 3240 // cgroup-parent relative path 3241 testRunContainerWithCgroupParent(c, "test", "cgroup-test") 3242 3243 // cgroup-parent absolute path 3244 testRunContainerWithCgroupParent(c, "/cgroup-parent/test", "cgroup-test-absolute") 3245 } 3246 3247 func testRunContainerWithCgroupParent(c *check.C, cgroupParent, name string) { 3248 out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") 3249 if err != nil { 3250 c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err) 3251 } 3252 cgroupPaths := ParseCgroupPaths(string(out)) 3253 if len(cgroupPaths) == 0 { 3254 c.Fatalf("unexpected output - %q", string(out)) 3255 } 3256 id := getIDByName(c, name) 3257 expectedCgroup := path.Join(cgroupParent, id) 3258 found := false 3259 for _, path := range cgroupPaths { 3260 if strings.HasSuffix(path, expectedCgroup) { 3261 found = true 3262 break 3263 } 3264 } 3265 if !found { 3266 c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths) 3267 } 3268 } 3269 3270 // TestRunInvalidCgroupParent checks that a specially-crafted cgroup parent doesn't cause Docker to crash or start modifying /. 3271 func (s *DockerSuite) TestRunInvalidCgroupParent(c *check.C) { 3272 // Not applicable on Windows as uses Unix specific functionality 3273 testRequires(c, DaemonIsLinux) 3274 3275 testRunInvalidCgroupParent(c, "../../../../../../../../SHOULD_NOT_EXIST", "SHOULD_NOT_EXIST", "cgroup-invalid-test") 3276 3277 testRunInvalidCgroupParent(c, "/../../../../../../../../SHOULD_NOT_EXIST", "/SHOULD_NOT_EXIST", "cgroup-absolute-invalid-test") 3278 } 3279 3280 func testRunInvalidCgroupParent(c *check.C, cgroupParent, cleanCgroupParent, name string) { 3281 out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") 3282 if err != nil { 3283 // XXX: This may include a daemon crash. 3284 c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err) 3285 } 3286 3287 // We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue. 3288 if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) { 3289 c.Fatalf("SECURITY: --cgroup-parent with ../../ relative paths cause files to be created in the host (this is bad) !!") 3290 } 3291 3292 cgroupPaths := ParseCgroupPaths(string(out)) 3293 if len(cgroupPaths) == 0 { 3294 c.Fatalf("unexpected output - %q", string(out)) 3295 } 3296 id := getIDByName(c, name) 3297 expectedCgroup := path.Join(cleanCgroupParent, id) 3298 found := false 3299 for _, path := range cgroupPaths { 3300 if strings.HasSuffix(path, expectedCgroup) { 3301 found = true 3302 break 3303 } 3304 } 3305 if !found { 3306 c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths) 3307 } 3308 } 3309 3310 func (s *DockerSuite) TestRunContainerWithCgroupMountRO(c *check.C) { 3311 // Not applicable on Windows as uses Unix specific functionality 3312 // --read-only + userns has remount issues 3313 testRequires(c, DaemonIsLinux, NotUserNamespace) 3314 3315 filename := "/sys/fs/cgroup/devices/test123" 3316 out, _, err := dockerCmdWithError("run", "busybox", "touch", filename) 3317 if err == nil { 3318 c.Fatal("expected cgroup mount point to be read-only, touch file should fail") 3319 } 3320 expected := "Read-only file system" 3321 if !strings.Contains(out, expected) { 3322 c.Fatalf("expected output from failure to contain %s but contains %s", expected, out) 3323 } 3324 } 3325 3326 func (s *DockerSuite) TestRunContainerNetworkModeToSelf(c *check.C) { 3327 // Not applicable on Windows which does not support --net=container 3328 testRequires(c, DaemonIsLinux) 3329 out, _, err := dockerCmdWithError("run", "--name=me", "--net=container:me", "busybox", "true") 3330 if err == nil || !strings.Contains(out, "cannot join own network") { 3331 c.Fatalf("using container net mode to self should result in an error\nerr: %q\nout: %s", err, out) 3332 } 3333 } 3334 3335 func (s *DockerSuite) TestRunContainerNetModeWithDNSMacHosts(c *check.C) { 3336 // Not applicable on Windows which does not support --net=container 3337 testRequires(c, DaemonIsLinux) 3338 out, _, err := dockerCmdWithError("run", "-d", "--name", "parent", "busybox", "top") 3339 if err != nil { 3340 c.Fatalf("failed to run container: %v, output: %q", err, out) 3341 } 3342 3343 out, _, err = dockerCmdWithError("run", "--dns", "1.2.3.4", "--net=container:parent", "busybox") 3344 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkAndDNS.Error()) { 3345 c.Fatalf("run --net=container with --dns should error out") 3346 } 3347 3348 out, _, err = dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29:33", "--net=container:parent", "busybox") 3349 if err == nil || !strings.Contains(out, runconfig.ErrConflictContainerNetworkAndMac.Error()) { 3350 c.Fatalf("run --net=container with --mac-address should error out") 3351 } 3352 3353 out, _, err = dockerCmdWithError("run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox") 3354 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkHosts.Error()) { 3355 c.Fatalf("run --net=container with --add-host should error out") 3356 } 3357 } 3358 3359 func (s *DockerSuite) TestRunContainerNetModeWithExposePort(c *check.C) { 3360 // Not applicable on Windows which does not support --net=container 3361 testRequires(c, DaemonIsLinux) 3362 dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") 3363 3364 out, _, err := dockerCmdWithError("run", "-p", "5000:5000", "--net=container:parent", "busybox") 3365 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) { 3366 c.Fatalf("run --net=container with -p should error out") 3367 } 3368 3369 out, _, err = dockerCmdWithError("run", "-P", "--net=container:parent", "busybox") 3370 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) { 3371 c.Fatalf("run --net=container with -P should error out") 3372 } 3373 3374 out, _, err = dockerCmdWithError("run", "--expose", "5000", "--net=container:parent", "busybox") 3375 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkExposePorts.Error()) { 3376 c.Fatalf("run --net=container with --expose should error out") 3377 } 3378 } 3379 3380 func (s *DockerSuite) TestRunLinkToContainerNetMode(c *check.C) { 3381 // Not applicable on Windows which does not support --net=container or --link 3382 testRequires(c, DaemonIsLinux) 3383 dockerCmd(c, "run", "--name", "test", "-d", "busybox", "top") 3384 dockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top") 3385 dockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top") 3386 dockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top") 3387 dockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top") 3388 } 3389 3390 func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *check.C) { 3391 // TODO Windows: This may be possible to convert. 3392 testRequires(c, DaemonIsLinux) 3393 out, _ := dockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up") 3394 3395 var ( 3396 count = 0 3397 parts = strings.Split(out, "\n") 3398 ) 3399 3400 for _, l := range parts { 3401 if l != "" { 3402 count++ 3403 } 3404 } 3405 3406 if count != 1 { 3407 c.Fatalf("Wrong interface count in container %d", count) 3408 } 3409 3410 if !strings.HasPrefix(out, "1: lo") { 3411 c.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out) 3412 } 3413 } 3414 3415 // Issue #4681 3416 func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *check.C) { 3417 if testEnv.OSType == "windows" { 3418 dockerCmd(c, "run", "--net=none", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1") 3419 } else { 3420 dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1") 3421 } 3422 } 3423 3424 func (s *DockerSuite) TestRunModeNetContainerHostname(c *check.C) { 3425 // Windows does not support --net=container 3426 testRequires(c, DaemonIsLinux, ExecSupport) 3427 3428 dockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top") 3429 out, _ := dockerCmd(c, "exec", "parent", "cat", "/etc/hostname") 3430 out1, _ := dockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname") 3431 3432 if out1 != out { 3433 c.Fatal("containers with shared net namespace should have same hostname") 3434 } 3435 } 3436 3437 func (s *DockerSuite) TestRunNetworkNotInitializedNoneMode(c *check.C) { 3438 // TODO Windows: Network settings are not currently propagated. This may 3439 // be resolved in the future with the move to libnetwork and CNM. 3440 testRequires(c, DaemonIsLinux) 3441 out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top") 3442 id := strings.TrimSpace(out) 3443 res := inspectField(c, id, "NetworkSettings.Networks.none.IPAddress") 3444 if res != "" { 3445 c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res) 3446 } 3447 } 3448 3449 func (s *DockerSuite) TestTwoContainersInNetHost(c *check.C) { 3450 // Not applicable as Windows does not support --net=host 3451 testRequires(c, DaemonIsLinux, NotUserNamespace, NotUserNamespace) 3452 dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") 3453 dockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top") 3454 dockerCmd(c, "stop", "first") 3455 dockerCmd(c, "stop", "second") 3456 } 3457 3458 func (s *DockerSuite) TestContainersInUserDefinedNetwork(c *check.C) { 3459 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 3460 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork") 3461 dockerCmd(c, "run", "-d", "--net=testnetwork", "--name=first", "busybox", "top") 3462 c.Assert(waitRun("first"), check.IsNil) 3463 dockerCmd(c, "run", "-t", "--net=testnetwork", "--name=second", "busybox", "ping", "-c", "1", "first") 3464 } 3465 3466 func (s *DockerSuite) TestContainersInMultipleNetworks(c *check.C) { 3467 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 3468 // Create 2 networks using bridge driver 3469 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3470 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") 3471 // Run and connect containers to testnetwork1 3472 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3473 c.Assert(waitRun("first"), check.IsNil) 3474 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3475 c.Assert(waitRun("second"), check.IsNil) 3476 // Check connectivity between containers in testnetwork2 3477 dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") 3478 // Connect containers to testnetwork2 3479 dockerCmd(c, "network", "connect", "testnetwork2", "first") 3480 dockerCmd(c, "network", "connect", "testnetwork2", "second") 3481 // Check connectivity between containers 3482 dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") 3483 } 3484 3485 func (s *DockerSuite) TestContainersNetworkIsolation(c *check.C) { 3486 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 3487 // Create 2 networks using bridge driver 3488 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3489 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") 3490 // Run 1 container in testnetwork1 and another in testnetwork2 3491 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3492 c.Assert(waitRun("first"), check.IsNil) 3493 dockerCmd(c, "run", "-d", "--net=testnetwork2", "--name=second", "busybox", "top") 3494 c.Assert(waitRun("second"), check.IsNil) 3495 3496 // Check Isolation between containers : ping must fail 3497 _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") 3498 c.Assert(err, check.NotNil) 3499 // Connect first container to testnetwork2 3500 dockerCmd(c, "network", "connect", "testnetwork2", "first") 3501 // ping must succeed now 3502 _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") 3503 c.Assert(err, check.IsNil) 3504 3505 // Disconnect first container from testnetwork2 3506 dockerCmd(c, "network", "disconnect", "testnetwork2", "first") 3507 // ping must fail again 3508 _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") 3509 c.Assert(err, check.NotNil) 3510 } 3511 3512 func (s *DockerSuite) TestNetworkRmWithActiveContainers(c *check.C) { 3513 testRequires(c, DaemonIsLinux, NotUserNamespace) 3514 // Create 2 networks using bridge driver 3515 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3516 // Run and connect containers to testnetwork1 3517 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3518 c.Assert(waitRun("first"), check.IsNil) 3519 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3520 c.Assert(waitRun("second"), check.IsNil) 3521 // Network delete with active containers must fail 3522 _, _, err := dockerCmdWithError("network", "rm", "testnetwork1") 3523 c.Assert(err, check.NotNil) 3524 3525 dockerCmd(c, "stop", "first") 3526 _, _, err = dockerCmdWithError("network", "rm", "testnetwork1") 3527 c.Assert(err, check.NotNil) 3528 } 3529 3530 func (s *DockerSuite) TestContainerRestartInMultipleNetworks(c *check.C) { 3531 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 3532 // Create 2 networks using bridge driver 3533 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3534 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") 3535 3536 // Run and connect containers to testnetwork1 3537 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3538 c.Assert(waitRun("first"), check.IsNil) 3539 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3540 c.Assert(waitRun("second"), check.IsNil) 3541 // Check connectivity between containers in testnetwork2 3542 dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") 3543 // Connect containers to testnetwork2 3544 dockerCmd(c, "network", "connect", "testnetwork2", "first") 3545 dockerCmd(c, "network", "connect", "testnetwork2", "second") 3546 // Check connectivity between containers 3547 dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") 3548 3549 // Stop second container and test ping failures on both networks 3550 dockerCmd(c, "stop", "second") 3551 _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork1") 3552 c.Assert(err, check.NotNil) 3553 _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork2") 3554 c.Assert(err, check.NotNil) 3555 3556 // Start second container and connectivity must be restored on both networks 3557 dockerCmd(c, "start", "second") 3558 dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") 3559 dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") 3560 } 3561 3562 func (s *DockerSuite) TestContainerWithConflictingHostNetworks(c *check.C) { 3563 testRequires(c, DaemonIsLinux, NotUserNamespace) 3564 // Run a container with --net=host 3565 dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") 3566 c.Assert(waitRun("first"), check.IsNil) 3567 3568 // Create a network using bridge driver 3569 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3570 3571 // Connecting to the user defined network must fail 3572 _, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first") 3573 c.Assert(err, check.NotNil) 3574 } 3575 3576 func (s *DockerSuite) TestContainerWithConflictingSharedNetwork(c *check.C) { 3577 testRequires(c, DaemonIsLinux) 3578 dockerCmd(c, "run", "-d", "--name=first", "busybox", "top") 3579 c.Assert(waitRun("first"), check.IsNil) 3580 // Run second container in first container's network namespace 3581 dockerCmd(c, "run", "-d", "--net=container:first", "--name=second", "busybox", "top") 3582 c.Assert(waitRun("second"), check.IsNil) 3583 3584 // Create a network using bridge driver 3585 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3586 3587 // Connecting to the user defined network must fail 3588 out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "second") 3589 c.Assert(err, check.NotNil) 3590 c.Assert(out, checker.Contains, runconfig.ErrConflictSharedNetwork.Error()) 3591 } 3592 3593 func (s *DockerSuite) TestContainerWithConflictingNoneNetwork(c *check.C) { 3594 testRequires(c, DaemonIsLinux) 3595 dockerCmd(c, "run", "-d", "--net=none", "--name=first", "busybox", "top") 3596 c.Assert(waitRun("first"), check.IsNil) 3597 3598 // Create a network using bridge driver 3599 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3600 3601 // Connecting to the user defined network must fail 3602 out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first") 3603 c.Assert(err, check.NotNil) 3604 c.Assert(out, checker.Contains, runconfig.ErrConflictNoNetwork.Error()) 3605 3606 // create a container connected to testnetwork1 3607 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3608 c.Assert(waitRun("second"), check.IsNil) 3609 3610 // Connect second container to none network. it must fail as well 3611 _, _, err = dockerCmdWithError("network", "connect", "none", "second") 3612 c.Assert(err, check.NotNil) 3613 } 3614 3615 // #11957 - stdin with no tty does not exit if stdin is not closed even though container exited 3616 func (s *DockerSuite) TestRunStdinBlockedAfterContainerExit(c *check.C) { 3617 cmd := exec.Command(dockerBinary, "run", "-i", "--name=test", "busybox", "true") 3618 in, err := cmd.StdinPipe() 3619 c.Assert(err, check.IsNil) 3620 defer in.Close() 3621 stdout := bytes.NewBuffer(nil) 3622 cmd.Stdout = stdout 3623 cmd.Stderr = stdout 3624 c.Assert(cmd.Start(), check.IsNil) 3625 3626 waitChan := make(chan error) 3627 go func() { 3628 waitChan <- cmd.Wait() 3629 }() 3630 3631 select { 3632 case err := <-waitChan: 3633 c.Assert(err, check.IsNil, check.Commentf(stdout.String())) 3634 case <-time.After(30 * time.Second): 3635 c.Fatal("timeout waiting for command to exit") 3636 } 3637 } 3638 3639 func (s *DockerSuite) TestRunWrongCpusetCpusFlagValue(c *check.C) { 3640 // TODO Windows: This needs validation (error out) in the daemon. 3641 testRequires(c, DaemonIsLinux) 3642 out, exitCode, err := dockerCmdWithError("run", "--cpuset-cpus", "1-10,11--", "busybox", "true") 3643 c.Assert(err, check.NotNil) 3644 expected := "Error response from daemon: Invalid value 1-10,11-- for cpuset cpus.\n" 3645 if !(strings.Contains(out, expected) || exitCode == 125) { 3646 c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode) 3647 } 3648 } 3649 3650 func (s *DockerSuite) TestRunWrongCpusetMemsFlagValue(c *check.C) { 3651 // TODO Windows: This needs validation (error out) in the daemon. 3652 testRequires(c, DaemonIsLinux) 3653 out, exitCode, err := dockerCmdWithError("run", "--cpuset-mems", "1-42--", "busybox", "true") 3654 c.Assert(err, check.NotNil) 3655 expected := "Error response from daemon: Invalid value 1-42-- for cpuset mems.\n" 3656 if !(strings.Contains(out, expected) || exitCode == 125) { 3657 c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode) 3658 } 3659 } 3660 3661 // TestRunNonExecutableCmd checks that 'docker run busybox foo' exits with error code 127' 3662 func (s *DockerSuite) TestRunNonExecutableCmd(c *check.C) { 3663 name := "testNonExecutableCmd" 3664 icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "foo").Assert(c, icmd.Expected{ 3665 ExitCode: 127, 3666 Error: "exit status 127", 3667 }) 3668 } 3669 3670 // TestRunNonExistingCmd checks that 'docker run busybox /bin/foo' exits with code 127. 3671 func (s *DockerSuite) TestRunNonExistingCmd(c *check.C) { 3672 name := "testNonExistingCmd" 3673 icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "/bin/foo").Assert(c, icmd.Expected{ 3674 ExitCode: 127, 3675 Error: "exit status 127", 3676 }) 3677 } 3678 3679 // TestCmdCannotBeInvoked checks that 'docker run busybox /etc' exits with 126, or 3680 // 127 on Windows. The difference is that in Windows, the container must be started 3681 // as that's when the check is made (and yes, by its design...) 3682 func (s *DockerSuite) TestCmdCannotBeInvoked(c *check.C) { 3683 expected := 126 3684 if testEnv.OSType == "windows" { 3685 expected = 127 3686 } 3687 name := "testCmdCannotBeInvoked" 3688 icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "/etc").Assert(c, icmd.Expected{ 3689 ExitCode: expected, 3690 Error: fmt.Sprintf("exit status %d", expected), 3691 }) 3692 } 3693 3694 // TestRunNonExistingImage checks that 'docker run foo' exits with error msg 125 and contains 'Unable to find image' 3695 // FIXME(vdemeester) should be a unit test 3696 func (s *DockerSuite) TestRunNonExistingImage(c *check.C) { 3697 icmd.RunCommand(dockerBinary, "run", "foo").Assert(c, icmd.Expected{ 3698 ExitCode: 125, 3699 Err: "Unable to find image", 3700 }) 3701 } 3702 3703 // TestDockerFails checks that 'docker run -foo busybox' exits with 125 to signal docker run failed 3704 // FIXME(vdemeester) should be a unit test 3705 func (s *DockerSuite) TestDockerFails(c *check.C) { 3706 icmd.RunCommand(dockerBinary, "run", "-foo", "busybox").Assert(c, icmd.Expected{ 3707 ExitCode: 125, 3708 Error: "exit status 125", 3709 }) 3710 } 3711 3712 // TestRunInvalidReference invokes docker run with a bad reference. 3713 func (s *DockerSuite) TestRunInvalidReference(c *check.C) { 3714 out, exit, _ := dockerCmdWithError("run", "busybox@foo") 3715 if exit == 0 { 3716 c.Fatalf("expected non-zero exist code; received %d", exit) 3717 } 3718 3719 if !strings.Contains(out, "invalid reference format") { 3720 c.Fatalf(`Expected "invalid reference format" in output; got: %s`, out) 3721 } 3722 } 3723 3724 // Test fix for issue #17854 3725 func (s *DockerSuite) TestRunInitLayerPathOwnership(c *check.C) { 3726 // Not applicable on Windows as it does not support Linux uid/gid ownership 3727 testRequires(c, DaemonIsLinux) 3728 name := "testetcfileownership" 3729 buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox 3730 RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd 3731 RUN echo 'dockerio:x:1001:' >> /etc/group 3732 RUN chown dockerio:dockerio /etc`)) 3733 3734 // Test that dockerio ownership of /etc is retained at runtime 3735 out, _ := dockerCmd(c, "run", "--rm", name, "stat", "-c", "%U:%G", "/etc") 3736 out = strings.TrimSpace(out) 3737 if out != "dockerio:dockerio" { 3738 c.Fatalf("Wrong /etc ownership: expected dockerio:dockerio, got %q", out) 3739 } 3740 } 3741 3742 func (s *DockerSuite) TestRunWithOomScoreAdj(c *check.C) { 3743 testRequires(c, DaemonIsLinux) 3744 3745 expected := "642" 3746 out, _ := dockerCmd(c, "run", "--oom-score-adj", expected, "busybox", "cat", "/proc/self/oom_score_adj") 3747 oomScoreAdj := strings.TrimSpace(out) 3748 if oomScoreAdj != "642" { 3749 c.Fatalf("Expected oom_score_adj set to %q, got %q instead", expected, oomScoreAdj) 3750 } 3751 } 3752 3753 func (s *DockerSuite) TestRunWithOomScoreAdjInvalidRange(c *check.C) { 3754 testRequires(c, DaemonIsLinux) 3755 3756 out, _, err := dockerCmdWithError("run", "--oom-score-adj", "1001", "busybox", "true") 3757 c.Assert(err, check.NotNil) 3758 expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]." 3759 if !strings.Contains(out, expected) { 3760 c.Fatalf("Expected output to contain %q, got %q instead", expected, out) 3761 } 3762 out, _, err = dockerCmdWithError("run", "--oom-score-adj", "-1001", "busybox", "true") 3763 c.Assert(err, check.NotNil) 3764 expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]." 3765 if !strings.Contains(out, expected) { 3766 c.Fatalf("Expected output to contain %q, got %q instead", expected, out) 3767 } 3768 } 3769 3770 func (s *DockerSuite) TestRunVolumesMountedAsShared(c *check.C) { 3771 // Volume propagation is linux only. Also it creates directories for 3772 // bind mounting, so needs to be same host. 3773 testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace) 3774 3775 // Prepare a source directory to bind mount 3776 tmpDir, err := ioutil.TempDir("", "volume-source") 3777 if err != nil { 3778 c.Fatal(err) 3779 } 3780 defer os.RemoveAll(tmpDir) 3781 3782 if err := os.Mkdir(path.Join(tmpDir, "mnt1"), 0755); err != nil { 3783 c.Fatal(err) 3784 } 3785 3786 // Convert this directory into a shared mount point so that we do 3787 // not rely on propagation properties of parent mount. 3788 icmd.RunCommand("mount", "--bind", tmpDir, tmpDir).Assert(c, icmd.Success) 3789 icmd.RunCommand("mount", "--make-private", "--make-shared", tmpDir).Assert(c, icmd.Success) 3790 3791 dockerCmd(c, "run", "--privileged", "-v", fmt.Sprintf("%s:/volume-dest:shared", tmpDir), "busybox", "mount", "--bind", "/volume-dest/mnt1", "/volume-dest/mnt1") 3792 3793 // Make sure a bind mount under a shared volume propagated to host. 3794 if mounted, _ := mount.Mounted(path.Join(tmpDir, "mnt1")); !mounted { 3795 c.Fatalf("Bind mount under shared volume did not propagate to host") 3796 } 3797 3798 mount.Unmount(path.Join(tmpDir, "mnt1")) 3799 } 3800 3801 func (s *DockerSuite) TestRunVolumesMountedAsSlave(c *check.C) { 3802 // Volume propagation is linux only. Also it creates directories for 3803 // bind mounting, so needs to be same host. 3804 testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace) 3805 3806 // Prepare a source directory to bind mount 3807 tmpDir, err := ioutil.TempDir("", "volume-source") 3808 if err != nil { 3809 c.Fatal(err) 3810 } 3811 defer os.RemoveAll(tmpDir) 3812 3813 if err := os.Mkdir(path.Join(tmpDir, "mnt1"), 0755); err != nil { 3814 c.Fatal(err) 3815 } 3816 3817 // Prepare a source directory with file in it. We will bind mount this 3818 // directory and see if file shows up. 3819 tmpDir2, err := ioutil.TempDir("", "volume-source2") 3820 if err != nil { 3821 c.Fatal(err) 3822 } 3823 defer os.RemoveAll(tmpDir2) 3824 3825 if err := ioutil.WriteFile(path.Join(tmpDir2, "slave-testfile"), []byte("Test"), 0644); err != nil { 3826 c.Fatal(err) 3827 } 3828 3829 // Convert this directory into a shared mount point so that we do 3830 // not rely on propagation properties of parent mount. 3831 icmd.RunCommand("mount", "--bind", tmpDir, tmpDir).Assert(c, icmd.Success) 3832 icmd.RunCommand("mount", "--make-private", "--make-shared", tmpDir).Assert(c, icmd.Success) 3833 3834 dockerCmd(c, "run", "-i", "-d", "--name", "parent", "-v", fmt.Sprintf("%s:/volume-dest:slave", tmpDir), "busybox", "top") 3835 3836 // Bind mount tmpDir2/ onto tmpDir/mnt1. If mount propagates inside 3837 // container then contents of tmpDir2/slave-testfile should become 3838 // visible at "/volume-dest/mnt1/slave-testfile" 3839 icmd.RunCommand("mount", "--bind", tmpDir2, path.Join(tmpDir, "mnt1")).Assert(c, icmd.Success) 3840 3841 out, _ := dockerCmd(c, "exec", "parent", "cat", "/volume-dest/mnt1/slave-testfile") 3842 3843 mount.Unmount(path.Join(tmpDir, "mnt1")) 3844 3845 if out != "Test" { 3846 c.Fatalf("Bind mount under slave volume did not propagate to container") 3847 } 3848 } 3849 3850 func (s *DockerSuite) TestRunNamedVolumesMountedAsShared(c *check.C) { 3851 testRequires(c, DaemonIsLinux, NotUserNamespace) 3852 out, exitCode, _ := dockerCmdWithError("run", "-v", "foo:/test:shared", "busybox", "touch", "/test/somefile") 3853 c.Assert(exitCode, checker.Not(checker.Equals), 0) 3854 c.Assert(out, checker.Contains, "invalid mount config") 3855 } 3856 3857 func (s *DockerSuite) TestRunNamedVolumeCopyImageData(c *check.C) { 3858 testRequires(c, DaemonIsLinux) 3859 3860 testImg := "testvolumecopy" 3861 buildImageSuccessfully(c, testImg, build.WithDockerfile(` 3862 FROM busybox 3863 RUN mkdir -p /foo && echo hello > /foo/hello 3864 `)) 3865 3866 dockerCmd(c, "run", "-v", "foo:/foo", testImg) 3867 out, _ := dockerCmd(c, "run", "-v", "foo:/foo", "busybox", "cat", "/foo/hello") 3868 c.Assert(strings.TrimSpace(out), check.Equals, "hello") 3869 } 3870 3871 func (s *DockerSuite) TestRunNamedVolumeNotRemoved(c *check.C) { 3872 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 3873 3874 dockerCmd(c, "volume", "create", "test") 3875 3876 dockerCmd(c, "run", "--rm", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") 3877 dockerCmd(c, "volume", "inspect", "test") 3878 out, _ := dockerCmd(c, "volume", "ls", "-q") 3879 c.Assert(strings.TrimSpace(out), checker.Contains, "test") 3880 3881 dockerCmd(c, "run", "--name=test", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") 3882 dockerCmd(c, "rm", "-fv", "test") 3883 dockerCmd(c, "volume", "inspect", "test") 3884 out, _ = dockerCmd(c, "volume", "ls", "-q") 3885 c.Assert(strings.TrimSpace(out), checker.Contains, "test") 3886 } 3887 3888 func (s *DockerSuite) TestRunNamedVolumesFromNotRemoved(c *check.C) { 3889 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 3890 3891 dockerCmd(c, "volume", "create", "test") 3892 cid, _ := dockerCmd(c, "run", "-d", "--name=parent", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") 3893 dockerCmd(c, "run", "--name=child", "--volumes-from=parent", "busybox", "true") 3894 3895 cli, err := client.NewEnvClient() 3896 c.Assert(err, checker.IsNil) 3897 defer cli.Close() 3898 3899 container, err := cli.ContainerInspect(context.Background(), strings.TrimSpace(cid)) 3900 c.Assert(err, checker.IsNil) 3901 var vname string 3902 for _, v := range container.Mounts { 3903 if v.Name != "test" { 3904 vname = v.Name 3905 } 3906 } 3907 c.Assert(vname, checker.Not(checker.Equals), "") 3908 3909 // Remove the parent so there are not other references to the volumes 3910 dockerCmd(c, "rm", "-f", "parent") 3911 // now remove the child and ensure the named volume (and only the named volume) still exists 3912 dockerCmd(c, "rm", "-fv", "child") 3913 dockerCmd(c, "volume", "inspect", "test") 3914 out, _ := dockerCmd(c, "volume", "ls", "-q") 3915 c.Assert(strings.TrimSpace(out), checker.Contains, "test") 3916 c.Assert(strings.TrimSpace(out), checker.Not(checker.Contains), vname) 3917 } 3918 3919 func (s *DockerSuite) TestRunAttachFailedNoLeak(c *check.C) { 3920 // TODO @msabansal - https://github.com/moby/moby/issues/35023. Duplicate 3921 // port mappings are not errored out on RS3 builds. Temporarily disabling 3922 // this test pending further investigation. Note we parse kernel.GetKernelVersion 3923 // rather than system.GetOSVersion as test binaries aren't manifested, so would 3924 // otherwise report build 9200. 3925 if runtime.GOOS == "windows" { 3926 v, err := kernel.GetKernelVersion() 3927 c.Assert(err, checker.IsNil) 3928 build, _ := strconv.Atoi(strings.Split(strings.SplitN(v.String(), " ", 3)[2][1:], ".")[0]) 3929 if build == 16299 { 3930 c.Skip("Temporarily disabled on RS3 builds") 3931 } 3932 } 3933 3934 nroutines, err := getGoroutineNumber() 3935 c.Assert(err, checker.IsNil) 3936 3937 runSleepingContainer(c, "--name=test", "-p", "8000:8000") 3938 3939 // Wait until container is fully up and running 3940 c.Assert(waitRun("test"), check.IsNil) 3941 3942 out, _, err := dockerCmdWithError("run", "--name=fail", "-p", "8000:8000", "busybox", "true") 3943 // We will need the following `inspect` to diagnose the issue if test fails (#21247) 3944 out1, err1 := dockerCmd(c, "inspect", "--format", "{{json .State}}", "test") 3945 out2, err2 := dockerCmd(c, "inspect", "--format", "{{json .State}}", "fail") 3946 c.Assert(err, checker.NotNil, check.Commentf("Command should have failed but succeeded with: %s\nContainer 'test' [%+v]: %s\nContainer 'fail' [%+v]: %s", out, err1, out1, err2, out2)) 3947 // check for windows error as well 3948 // TODO Windows Post TP5. Fix the error message string 3949 c.Assert(strings.Contains(string(out), "port is already allocated") || 3950 strings.Contains(string(out), "were not connected because a duplicate name exists") || 3951 strings.Contains(string(out), "HNS failed with error : Failed to create endpoint") || 3952 strings.Contains(string(out), "HNS failed with error : The object already exists"), checker.Equals, true, check.Commentf("Output: %s", out)) 3953 dockerCmd(c, "rm", "-f", "test") 3954 3955 // NGoroutines is not updated right away, so we need to wait before failing 3956 c.Assert(waitForGoroutines(nroutines), checker.IsNil) 3957 } 3958 3959 // Test for one character directory name case (#20122) 3960 func (s *DockerSuite) TestRunVolumeWithOneCharacter(c *check.C) { 3961 testRequires(c, DaemonIsLinux) 3962 3963 out, _ := dockerCmd(c, "run", "-v", "/tmp/q:/foo", "busybox", "sh", "-c", "find /foo") 3964 c.Assert(strings.TrimSpace(out), checker.Equals, "/foo") 3965 } 3966 3967 func (s *DockerSuite) TestRunVolumeCopyFlag(c *check.C) { 3968 testRequires(c, DaemonIsLinux) // Windows does not support copying data from image to the volume 3969 buildImageSuccessfully(c, "volumecopy", build.WithDockerfile(`FROM busybox 3970 RUN mkdir /foo && echo hello > /foo/bar 3971 CMD cat /foo/bar`)) 3972 dockerCmd(c, "volume", "create", "test") 3973 3974 // test with the nocopy flag 3975 out, _, err := dockerCmdWithError("run", "-v", "test:/foo:nocopy", "volumecopy") 3976 c.Assert(err, checker.NotNil, check.Commentf(out)) 3977 // test default behavior which is to copy for non-binds 3978 out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy") 3979 c.Assert(strings.TrimSpace(out), checker.Equals, "hello") 3980 // error out when the volume is already populated 3981 out, _, err = dockerCmdWithError("run", "-v", "test:/foo:copy", "volumecopy") 3982 c.Assert(err, checker.NotNil, check.Commentf(out)) 3983 // do not error out when copy isn't explicitly set even though it's already populated 3984 out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy") 3985 c.Assert(strings.TrimSpace(out), checker.Equals, "hello") 3986 3987 // do not allow copy modes on volumes-from 3988 dockerCmd(c, "run", "--name=test", "-v", "/foo", "busybox", "true") 3989 out, _, err = dockerCmdWithError("run", "--volumes-from=test:copy", "busybox", "true") 3990 c.Assert(err, checker.NotNil, check.Commentf(out)) 3991 out, _, err = dockerCmdWithError("run", "--volumes-from=test:nocopy", "busybox", "true") 3992 c.Assert(err, checker.NotNil, check.Commentf(out)) 3993 3994 // do not allow copy modes on binds 3995 out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:copy", "busybox", "true") 3996 c.Assert(err, checker.NotNil, check.Commentf(out)) 3997 out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:nocopy", "busybox", "true") 3998 c.Assert(err, checker.NotNil, check.Commentf(out)) 3999 } 4000 4001 // Test case for #21976 4002 func (s *DockerSuite) TestRunDNSInHostMode(c *check.C) { 4003 testRequires(c, DaemonIsLinux, NotUserNamespace) 4004 4005 expectedOutput := "nameserver 127.0.0.1" 4006 expectedWarning := "Localhost DNS setting" 4007 cli.DockerCmd(c, "run", "--dns=127.0.0.1", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{ 4008 Out: expectedOutput, 4009 Err: expectedWarning, 4010 }) 4011 4012 expectedOutput = "nameserver 1.2.3.4" 4013 cli.DockerCmd(c, "run", "--dns=1.2.3.4", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{ 4014 Out: expectedOutput, 4015 }) 4016 4017 expectedOutput = "search example.com" 4018 cli.DockerCmd(c, "run", "--dns-search=example.com", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{ 4019 Out: expectedOutput, 4020 }) 4021 4022 expectedOutput = "options timeout:3" 4023 cli.DockerCmd(c, "run", "--dns-opt=timeout:3", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{ 4024 Out: expectedOutput, 4025 }) 4026 4027 expectedOutput1 := "nameserver 1.2.3.4" 4028 expectedOutput2 := "search example.com" 4029 expectedOutput3 := "options timeout:3" 4030 out := cli.DockerCmd(c, "run", "--dns=1.2.3.4", "--dns-search=example.com", "--dns-opt=timeout:3", "--net=host", "busybox", "cat", "/etc/resolv.conf").Combined() 4031 c.Assert(out, checker.Contains, expectedOutput1, check.Commentf("Expected '%s', but got %q", expectedOutput1, out)) 4032 c.Assert(out, checker.Contains, expectedOutput2, check.Commentf("Expected '%s', but got %q", expectedOutput2, out)) 4033 c.Assert(out, checker.Contains, expectedOutput3, check.Commentf("Expected '%s', but got %q", expectedOutput3, out)) 4034 } 4035 4036 // Test case for #21976 4037 func (s *DockerSuite) TestRunAddHostInHostMode(c *check.C) { 4038 testRequires(c, DaemonIsLinux, NotUserNamespace) 4039 4040 expectedOutput := "1.2.3.4\textra" 4041 out, _ := dockerCmd(c, "run", "--add-host=extra:1.2.3.4", "--net=host", "busybox", "cat", "/etc/hosts") 4042 c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out)) 4043 } 4044 4045 func (s *DockerSuite) TestRunRmAndWait(c *check.C) { 4046 dockerCmd(c, "run", "--name=test", "--rm", "-d", "busybox", "sh", "-c", "sleep 3;exit 2") 4047 4048 out, code, err := dockerCmdWithError("wait", "test") 4049 c.Assert(err, checker.IsNil, check.Commentf("out: %s; exit code: %d", out, code)) 4050 c.Assert(out, checker.Equals, "2\n", check.Commentf("exit code: %d", code)) 4051 c.Assert(code, checker.Equals, 0) 4052 } 4053 4054 // Test that auto-remove is performed by the daemon (API 1.25 and above) 4055 func (s *DockerSuite) TestRunRm(c *check.C) { 4056 name := "miss-me-when-im-gone" 4057 cli.DockerCmd(c, "run", "--name="+name, "--rm", "busybox") 4058 4059 cli.Docker(cli.Inspect(name), cli.Format(".name")).Assert(c, icmd.Expected{ 4060 ExitCode: 1, 4061 Err: "No such object: " + name, 4062 }) 4063 } 4064 4065 // Test that auto-remove is performed by the client on API versions that do not support daemon-side api-remove (API < 1.25) 4066 func (s *DockerSuite) TestRunRmPre125Api(c *check.C) { 4067 name := "miss-me-when-im-gone" 4068 envs := appendBaseEnv(os.Getenv("DOCKER_TLS_VERIFY") != "", "DOCKER_API_VERSION=1.24") 4069 cli.Docker(cli.Args("run", "--name="+name, "--rm", "busybox"), cli.WithEnvironmentVariables(envs...)).Assert(c, icmd.Success) 4070 4071 cli.Docker(cli.Inspect(name), cli.Format(".name")).Assert(c, icmd.Expected{ 4072 ExitCode: 1, 4073 Err: "No such object: " + name, 4074 }) 4075 } 4076 4077 // Test case for #23498 4078 func (s *DockerSuite) TestRunUnsetEntrypoint(c *check.C) { 4079 testRequires(c, DaemonIsLinux) 4080 name := "test-entrypoint" 4081 dockerfile := `FROM busybox 4082 ADD entrypoint.sh /entrypoint.sh 4083 RUN chmod 755 /entrypoint.sh 4084 ENTRYPOINT ["/entrypoint.sh"] 4085 CMD echo foobar` 4086 4087 ctx := fakecontext.New(c, "", 4088 fakecontext.WithDockerfile(dockerfile), 4089 fakecontext.WithFiles(map[string]string{ 4090 "entrypoint.sh": `#!/bin/sh 4091 echo "I am an entrypoint" 4092 exec "$@"`, 4093 })) 4094 defer ctx.Close() 4095 4096 cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx)) 4097 4098 out := cli.DockerCmd(c, "run", "--entrypoint=", "-t", name, "echo", "foo").Combined() 4099 c.Assert(strings.TrimSpace(out), check.Equals, "foo") 4100 4101 // CMD will be reset as well (the same as setting a custom entrypoint) 4102 cli.Docker(cli.Args("run", "--entrypoint=", "-t", name)).Assert(c, icmd.Expected{ 4103 ExitCode: 125, 4104 Err: "No command specified", 4105 }) 4106 } 4107 4108 func (s *DockerDaemonSuite) TestRunWithUlimitAndDaemonDefault(c *check.C) { 4109 s.d.StartWithBusybox(c, "--debug", "--default-ulimit=nofile=65535") 4110 4111 name := "test-A" 4112 _, err := s.d.Cmd("run", "--name", name, "-d", "busybox", "top") 4113 c.Assert(err, checker.IsNil) 4114 c.Assert(s.d.WaitRun(name), check.IsNil) 4115 4116 out, err := s.d.Cmd("inspect", "--format", "{{.HostConfig.Ulimits}}", name) 4117 c.Assert(err, checker.IsNil) 4118 c.Assert(out, checker.Contains, "[nofile=65535:65535]") 4119 4120 name = "test-B" 4121 _, err = s.d.Cmd("run", "--name", name, "--ulimit=nofile=42", "-d", "busybox", "top") 4122 c.Assert(err, checker.IsNil) 4123 c.Assert(s.d.WaitRun(name), check.IsNil) 4124 4125 out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.Ulimits}}", name) 4126 c.Assert(err, checker.IsNil) 4127 c.Assert(out, checker.Contains, "[nofile=42:42]") 4128 } 4129 4130 func (s *DockerSuite) TestRunStoppedLoggingDriverNoLeak(c *check.C) { 4131 nroutines, err := getGoroutineNumber() 4132 c.Assert(err, checker.IsNil) 4133 4134 out, _, err := dockerCmdWithError("run", "--name=fail", "--log-driver=splunk", "busybox", "true") 4135 c.Assert(err, checker.NotNil) 4136 c.Assert(out, checker.Contains, "failed to initialize logging driver", check.Commentf("error should be about logging driver, got output %s", out)) 4137 4138 // NGoroutines is not updated right away, so we need to wait before failing 4139 c.Assert(waitForGoroutines(nroutines), checker.IsNil) 4140 } 4141 4142 // Handles error conditions for --credentialspec. Validating E2E success cases 4143 // requires additional infrastructure (AD for example) on CI servers. 4144 func (s *DockerSuite) TestRunCredentialSpecFailures(c *check.C) { 4145 testRequires(c, DaemonIsWindows) 4146 attempts := []struct{ value, expectedError string }{ 4147 {"rubbish", "invalid credential spec security option - value must be prefixed file:// or registry://"}, 4148 {"rubbish://", "invalid credential spec security option - value must be prefixed file:// or registry://"}, 4149 {"file://", "no value supplied for file:// credential spec security option"}, 4150 {"registry://", "no value supplied for registry:// credential spec security option"}, 4151 {`file://c:\blah.txt`, "path cannot be absolute"}, 4152 {`file://doesnotexist.txt`, "The system cannot find the file specified"}, 4153 } 4154 for _, attempt := range attempts { 4155 _, _, err := dockerCmdWithError("run", "--security-opt=credentialspec="+attempt.value, "busybox", "true") 4156 c.Assert(err, checker.NotNil, check.Commentf("%s expected non-nil err", attempt.value)) 4157 c.Assert(err.Error(), checker.Contains, attempt.expectedError, check.Commentf("%s expected %s got %s", attempt.value, attempt.expectedError, err)) 4158 } 4159 } 4160 4161 // Windows specific test to validate credential specs with a well-formed spec. 4162 // Note it won't actually do anything in CI configuration with the spec, but 4163 // it should not fail to run a container. 4164 func (s *DockerSuite) TestRunCredentialSpecWellFormed(c *check.C) { 4165 testRequires(c, DaemonIsWindows, SameHostDaemon) 4166 validCS := readFile(`fixtures\credentialspecs\valid.json`, c) 4167 writeFile(filepath.Join(testEnv.DaemonInfo.DockerRootDir, `credentialspecs\valid.json`), validCS, c) 4168 dockerCmd(c, "run", `--security-opt=credentialspec=file://valid.json`, "busybox", "true") 4169 } 4170 4171 // Windows specific test to ensure that a servicing app container is started 4172 // if necessary once a container exits. It does this by forcing a no-op 4173 // servicing event and verifying the event from Hyper-V-Compute 4174 func (s *DockerSuite) TestRunServicingContainer(c *check.C) { 4175 testRequires(c, DaemonIsWindows, SameHostDaemon) 4176 4177 // This functionality does not exist in post-RS3 builds. 4178 // Note we get the version number from the full build string, as Windows 4179 // reports Windows 8 version 6.2 build 9200 from non-manifested binaries. 4180 // Ref: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx 4181 v, err := kernel.GetKernelVersion() 4182 c.Assert(err, checker.IsNil) 4183 build, _ := strconv.Atoi(strings.Split(strings.SplitN(v.String(), " ", 3)[2][1:], ".")[0]) 4184 if build > 16299 { 4185 c.Skip("Disabled on post-RS3 builds") 4186 } 4187 4188 out := cli.DockerCmd(c, "run", "-d", testEnv.PlatformDefaults.BaseImage, "cmd", "/c", "mkdir c:\\programdata\\Microsoft\\Windows\\ContainerUpdates\\000_000_d99f45d0-ffc8-4af7-bd9c-ea6a62e035c9_200 && sc control cexecsvc 255").Combined() 4189 containerID := strings.TrimSpace(out) 4190 cli.WaitExited(c, containerID, 60*time.Second) 4191 4192 result := icmd.RunCommand("powershell", "echo", `(Get-WinEvent -ProviderName "Microsoft-Windows-Hyper-V-Compute" -FilterXPath 'Event[System[EventID=2010]]' -MaxEvents 1).Message`) 4193 result.Assert(c, icmd.Success) 4194 out2 := result.Combined() 4195 c.Assert(out2, checker.Contains, `"Servicing":true`, check.Commentf("Servicing container does not appear to have been started: %s", out2)) 4196 c.Assert(out2, checker.Contains, `Windows Container (Servicing)`, check.Commentf("Didn't find 'Windows Container (Servicing): %s", out2)) 4197 c.Assert(out2, checker.Contains, containerID+"_servicing", check.Commentf("Didn't find '%s_servicing': %s", containerID+"_servicing", out2)) 4198 } 4199 4200 func (s *DockerSuite) TestRunDuplicateMount(c *check.C) { 4201 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 4202 4203 tmpFile, err := ioutil.TempFile("", "touch-me") 4204 c.Assert(err, checker.IsNil) 4205 defer tmpFile.Close() 4206 4207 data := "touch-me-foo-bar\n" 4208 if _, err := tmpFile.Write([]byte(data)); err != nil { 4209 c.Fatal(err) 4210 } 4211 4212 name := "test" 4213 out, _ := dockerCmd(c, "run", "--name", name, "-v", "/tmp:/tmp", "-v", "/tmp:/tmp", "busybox", "sh", "-c", "cat "+tmpFile.Name()+" && ls /") 4214 c.Assert(out, checker.Not(checker.Contains), "tmp:") 4215 c.Assert(out, checker.Contains, data) 4216 4217 out = inspectFieldJSON(c, name, "Config.Volumes") 4218 c.Assert(out, checker.Contains, "null") 4219 } 4220 4221 func (s *DockerSuite) TestRunWindowsWithCPUCount(c *check.C) { 4222 testRequires(c, DaemonIsWindows) 4223 4224 out, _ := dockerCmd(c, "run", "--cpu-count=1", "--name", "test", "busybox", "echo", "testing") 4225 c.Assert(strings.TrimSpace(out), checker.Equals, "testing") 4226 4227 out = inspectField(c, "test", "HostConfig.CPUCount") 4228 c.Assert(out, check.Equals, "1") 4229 } 4230 4231 func (s *DockerSuite) TestRunWindowsWithCPUShares(c *check.C) { 4232 testRequires(c, DaemonIsWindows) 4233 4234 out, _ := dockerCmd(c, "run", "--cpu-shares=1000", "--name", "test", "busybox", "echo", "testing") 4235 c.Assert(strings.TrimSpace(out), checker.Equals, "testing") 4236 4237 out = inspectField(c, "test", "HostConfig.CPUShares") 4238 c.Assert(out, check.Equals, "1000") 4239 } 4240 4241 func (s *DockerSuite) TestRunWindowsWithCPUPercent(c *check.C) { 4242 testRequires(c, DaemonIsWindows) 4243 4244 out, _ := dockerCmd(c, "run", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing") 4245 c.Assert(strings.TrimSpace(out), checker.Equals, "testing") 4246 4247 out = inspectField(c, "test", "HostConfig.CPUPercent") 4248 c.Assert(out, check.Equals, "80") 4249 } 4250 4251 func (s *DockerSuite) TestRunProcessIsolationWithCPUCountCPUSharesAndCPUPercent(c *check.C) { 4252 testRequires(c, DaemonIsWindows, IsolationIsProcess) 4253 4254 out, _ := dockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing") 4255 c.Assert(strings.TrimSpace(out), checker.Contains, "WARNING: Conflicting options: CPU count takes priority over CPU shares on Windows Server Containers. CPU shares discarded") 4256 c.Assert(strings.TrimSpace(out), checker.Contains, "WARNING: Conflicting options: CPU count takes priority over CPU percent on Windows Server Containers. CPU percent discarded") 4257 c.Assert(strings.TrimSpace(out), checker.Contains, "testing") 4258 4259 out = inspectField(c, "test", "HostConfig.CPUCount") 4260 c.Assert(out, check.Equals, "1") 4261 4262 out = inspectField(c, "test", "HostConfig.CPUShares") 4263 c.Assert(out, check.Equals, "0") 4264 4265 out = inspectField(c, "test", "HostConfig.CPUPercent") 4266 c.Assert(out, check.Equals, "0") 4267 } 4268 4269 func (s *DockerSuite) TestRunHypervIsolationWithCPUCountCPUSharesAndCPUPercent(c *check.C) { 4270 testRequires(c, DaemonIsWindows, IsolationIsHyperv) 4271 4272 out, _ := dockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing") 4273 c.Assert(strings.TrimSpace(out), checker.Contains, "testing") 4274 4275 out = inspectField(c, "test", "HostConfig.CPUCount") 4276 c.Assert(out, check.Equals, "1") 4277 4278 out = inspectField(c, "test", "HostConfig.CPUShares") 4279 c.Assert(out, check.Equals, "1000") 4280 4281 out = inspectField(c, "test", "HostConfig.CPUPercent") 4282 c.Assert(out, check.Equals, "80") 4283 } 4284 4285 // Test for #25099 4286 func (s *DockerSuite) TestRunEmptyEnv(c *check.C) { 4287 testRequires(c, DaemonIsLinux) 4288 4289 expectedOutput := "invalid environment variable:" 4290 4291 out, _, err := dockerCmdWithError("run", "-e", "", "busybox", "true") 4292 c.Assert(err, checker.NotNil) 4293 c.Assert(out, checker.Contains, expectedOutput) 4294 4295 out, _, err = dockerCmdWithError("run", "-e", "=", "busybox", "true") 4296 c.Assert(err, checker.NotNil) 4297 c.Assert(out, checker.Contains, expectedOutput) 4298 4299 out, _, err = dockerCmdWithError("run", "-e", "=foo", "busybox", "true") 4300 c.Assert(err, checker.NotNil) 4301 c.Assert(out, checker.Contains, expectedOutput) 4302 } 4303 4304 // #28658 4305 func (s *DockerSuite) TestSlowStdinClosing(c *check.C) { 4306 name := "testslowstdinclosing" 4307 repeat := 3 // regression happened 50% of the time 4308 for i := 0; i < repeat; i++ { 4309 cmd := icmd.Cmd{ 4310 Command: []string{dockerBinary, "run", "--rm", "--name", name, "-i", "busybox", "cat"}, 4311 Stdin: &delayedReader{}, 4312 } 4313 done := make(chan error, 1) 4314 go func() { 4315 err := icmd.RunCmd(cmd).Error 4316 done <- err 4317 }() 4318 4319 select { 4320 case <-time.After(15 * time.Second): 4321 c.Fatal("running container timed out") // cleanup in teardown 4322 case err := <-done: 4323 c.Assert(err, checker.IsNil) 4324 } 4325 } 4326 } 4327 4328 type delayedReader struct{} 4329 4330 func (s *delayedReader) Read([]byte) (int, error) { 4331 time.Sleep(500 * time.Millisecond) 4332 return 0, io.EOF 4333 } 4334 4335 // #28823 (originally #28639) 4336 func (s *DockerSuite) TestRunMountReadOnlyDevShm(c *check.C) { 4337 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 4338 emptyDir, err := ioutil.TempDir("", "test-read-only-dev-shm") 4339 c.Assert(err, check.IsNil) 4340 defer os.RemoveAll(emptyDir) 4341 out, _, err := dockerCmdWithError("run", "--rm", "--read-only", 4342 "-v", fmt.Sprintf("%s:/dev/shm:ro", emptyDir), 4343 "busybox", "touch", "/dev/shm/foo") 4344 c.Assert(err, checker.NotNil, check.Commentf(out)) 4345 c.Assert(out, checker.Contains, "Read-only file system") 4346 } 4347 4348 func (s *DockerSuite) TestRunMount(c *check.C) { 4349 testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace) 4350 4351 // mnt1, mnt2, and testCatFooBar are commonly used in multiple test cases 4352 tmpDir, err := ioutil.TempDir("", "mount") 4353 if err != nil { 4354 c.Fatal(err) 4355 } 4356 defer os.RemoveAll(tmpDir) 4357 mnt1, mnt2 := path.Join(tmpDir, "mnt1"), path.Join(tmpDir, "mnt2") 4358 if err := os.Mkdir(mnt1, 0755); err != nil { 4359 c.Fatal(err) 4360 } 4361 if err := os.Mkdir(mnt2, 0755); err != nil { 4362 c.Fatal(err) 4363 } 4364 if err := ioutil.WriteFile(path.Join(mnt1, "test1"), []byte("test1"), 0644); err != nil { 4365 c.Fatal(err) 4366 } 4367 if err := ioutil.WriteFile(path.Join(mnt2, "test2"), []byte("test2"), 0644); err != nil { 4368 c.Fatal(err) 4369 } 4370 testCatFooBar := func(cName string) error { 4371 out, _ := dockerCmd(c, "exec", cName, "cat", "/foo/test1") 4372 if out != "test1" { 4373 return fmt.Errorf("%s not mounted on /foo", mnt1) 4374 } 4375 out, _ = dockerCmd(c, "exec", cName, "cat", "/bar/test2") 4376 if out != "test2" { 4377 return fmt.Errorf("%s not mounted on /bar", mnt2) 4378 } 4379 return nil 4380 } 4381 4382 type testCase struct { 4383 equivalents [][]string 4384 valid bool 4385 // fn should be nil if valid==false 4386 fn func(cName string) error 4387 } 4388 cases := []testCase{ 4389 { 4390 equivalents: [][]string{ 4391 { 4392 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4393 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/bar", mnt2), 4394 }, 4395 { 4396 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4397 "--mount", fmt.Sprintf("type=bind,src=%s,target=/bar", mnt2), 4398 }, 4399 { 4400 "--volume", mnt1 + ":/foo", 4401 "--mount", fmt.Sprintf("type=bind,src=%s,target=/bar", mnt2), 4402 }, 4403 }, 4404 valid: true, 4405 fn: testCatFooBar, 4406 }, 4407 { 4408 equivalents: [][]string{ 4409 { 4410 "--mount", fmt.Sprintf("type=volume,src=%s,dst=/foo", mnt1), 4411 "--mount", fmt.Sprintf("type=volume,src=%s,dst=/bar", mnt2), 4412 }, 4413 { 4414 "--mount", fmt.Sprintf("type=volume,src=%s,dst=/foo", mnt1), 4415 "--mount", fmt.Sprintf("type=volume,src=%s,target=/bar", mnt2), 4416 }, 4417 }, 4418 valid: false, 4419 }, 4420 { 4421 equivalents: [][]string{ 4422 { 4423 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4424 "--mount", fmt.Sprintf("type=volume,src=%s,dst=/bar", mnt2), 4425 }, 4426 { 4427 "--volume", mnt1 + ":/foo", 4428 "--mount", fmt.Sprintf("type=volume,src=%s,target=/bar", mnt2), 4429 }, 4430 }, 4431 valid: false, 4432 fn: testCatFooBar, 4433 }, 4434 { 4435 equivalents: [][]string{ 4436 { 4437 "--read-only", 4438 "--mount", "type=volume,dst=/bar", 4439 }, 4440 }, 4441 valid: true, 4442 fn: func(cName string) error { 4443 _, _, err := dockerCmdWithError("exec", cName, "touch", "/bar/icanwritehere") 4444 return err 4445 }, 4446 }, 4447 { 4448 equivalents: [][]string{ 4449 { 4450 "--read-only", 4451 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4452 "--mount", "type=volume,dst=/bar", 4453 }, 4454 { 4455 "--read-only", 4456 "--volume", fmt.Sprintf("%s:/foo", mnt1), 4457 "--mount", "type=volume,dst=/bar", 4458 }, 4459 }, 4460 valid: true, 4461 fn: func(cName string) error { 4462 out, _ := dockerCmd(c, "exec", cName, "cat", "/foo/test1") 4463 if out != "test1" { 4464 return fmt.Errorf("%s not mounted on /foo", mnt1) 4465 } 4466 _, _, err := dockerCmdWithError("exec", cName, "touch", "/bar/icanwritehere") 4467 return err 4468 }, 4469 }, 4470 { 4471 equivalents: [][]string{ 4472 { 4473 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4474 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt2), 4475 }, 4476 { 4477 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4478 "--mount", fmt.Sprintf("type=bind,src=%s,target=/foo", mnt2), 4479 }, 4480 { 4481 "--volume", fmt.Sprintf("%s:/foo", mnt1), 4482 "--mount", fmt.Sprintf("type=bind,src=%s,target=/foo", mnt2), 4483 }, 4484 }, 4485 valid: false, 4486 }, 4487 { 4488 equivalents: [][]string{ 4489 { 4490 "--volume", fmt.Sprintf("%s:/foo", mnt1), 4491 "--mount", fmt.Sprintf("type=volume,src=%s,target=/foo", mnt2), 4492 }, 4493 }, 4494 valid: false, 4495 }, 4496 { 4497 equivalents: [][]string{ 4498 { 4499 "--mount", "type=volume,target=/foo", 4500 "--mount", "type=volume,target=/foo", 4501 }, 4502 }, 4503 valid: false, 4504 }, 4505 } 4506 4507 for i, testCase := range cases { 4508 for j, opts := range testCase.equivalents { 4509 cName := fmt.Sprintf("mount-%d-%d", i, j) 4510 _, _, err := dockerCmdWithError(append([]string{"run", "-i", "-d", "--name", cName}, 4511 append(opts, []string{"busybox", "top"}...)...)...) 4512 if testCase.valid { 4513 c.Assert(err, check.IsNil, 4514 check.Commentf("got error while creating a container with %v (%s)", opts, cName)) 4515 c.Assert(testCase.fn(cName), check.IsNil, 4516 check.Commentf("got error while executing test for %v (%s)", opts, cName)) 4517 dockerCmd(c, "rm", "-f", cName) 4518 } else { 4519 c.Assert(err, checker.NotNil, 4520 check.Commentf("got nil while creating a container with %v (%s)", opts, cName)) 4521 } 4522 } 4523 } 4524 } 4525 4526 // Test that passing a FQDN as hostname properly sets hostname, and 4527 // /etc/hostname. Test case for 29100 4528 func (s *DockerSuite) TestRunHostnameFQDN(c *check.C) { 4529 testRequires(c, DaemonIsLinux) 4530 4531 expectedOutput := "foobar.example.com\nfoobar.example.com\nfoobar\nexample.com\nfoobar.example.com" 4532 out, _ := dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hostname && hostname && hostname -s && hostname -d && hostname -f`) 4533 c.Assert(strings.TrimSpace(out), checker.Equals, expectedOutput) 4534 4535 out, _ = dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hosts`) 4536 expectedOutput = "foobar.example.com foobar" 4537 c.Assert(strings.TrimSpace(out), checker.Contains, expectedOutput) 4538 } 4539 4540 // Test case for 29129 4541 func (s *DockerSuite) TestRunHostnameInHostMode(c *check.C) { 4542 testRequires(c, DaemonIsLinux, NotUserNamespace) 4543 4544 expectedOutput := "foobar\nfoobar" 4545 out, _ := dockerCmd(c, "run", "--net=host", "--hostname=foobar", "busybox", "sh", "-c", `echo $HOSTNAME && hostname`) 4546 c.Assert(strings.TrimSpace(out), checker.Equals, expectedOutput) 4547 } 4548 4549 func (s *DockerSuite) TestRunAddDeviceCgroupRule(c *check.C) { 4550 testRequires(c, DaemonIsLinux) 4551 4552 deviceRule := "c 7:128 rwm" 4553 4554 out, _ := dockerCmd(c, "run", "--rm", "busybox", "cat", "/sys/fs/cgroup/devices/devices.list") 4555 if strings.Contains(out, deviceRule) { 4556 c.Fatalf("%s shouldn't been in the device.list", deviceRule) 4557 } 4558 4559 out, _ = dockerCmd(c, "run", "--rm", fmt.Sprintf("--device-cgroup-rule=%s", deviceRule), "busybox", "grep", deviceRule, "/sys/fs/cgroup/devices/devices.list") 4560 c.Assert(strings.TrimSpace(out), checker.Equals, deviceRule) 4561 } 4562 4563 // Verifies that running as local system is operating correctly on Windows 4564 func (s *DockerSuite) TestWindowsRunAsSystem(c *check.C) { 4565 testRequires(c, DaemonIsWindowsAtLeastBuild(15000)) 4566 out, _ := dockerCmd(c, "run", "--net=none", `--user=nt authority\system`, "--hostname=XYZZY", minimalBaseImage(), "cmd", "/c", `@echo %USERNAME%`) 4567 c.Assert(strings.TrimSpace(out), checker.Equals, "XYZZY$") 4568 }