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