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