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