github.com/hustcat/docker@v1.3.3-0.20160314103604-901c67a8eeab/integration-cli/docker_cli_exec_test.go (about) 1 // +build !test_no_exec 2 3 package main 4 5 import ( 6 "bufio" 7 "fmt" 8 "net/http" 9 "os" 10 "os/exec" 11 "path/filepath" 12 "reflect" 13 "sort" 14 "strings" 15 "sync" 16 "time" 17 18 "github.com/docker/docker/pkg/integration/checker" 19 "github.com/go-check/check" 20 ) 21 22 func (s *DockerSuite) TestExec(c *check.C) { 23 testRequires(c, DaemonIsLinux) 24 out, _ := dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top") 25 c.Assert(waitRun(strings.TrimSpace(out)), check.IsNil) 26 27 out, _ = dockerCmd(c, "exec", "testing", "cat", "/tmp/file") 28 out = strings.Trim(out, "\r\n") 29 c.Assert(out, checker.Equals, "test") 30 31 } 32 33 func (s *DockerSuite) TestExecInteractive(c *check.C) { 34 testRequires(c, DaemonIsLinux) 35 dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top") 36 37 execCmd := exec.Command(dockerBinary, "exec", "-i", "testing", "sh") 38 stdin, err := execCmd.StdinPipe() 39 c.Assert(err, checker.IsNil) 40 stdout, err := execCmd.StdoutPipe() 41 c.Assert(err, checker.IsNil) 42 43 err = execCmd.Start() 44 c.Assert(err, checker.IsNil) 45 _, err = stdin.Write([]byte("cat /tmp/file\n")) 46 c.Assert(err, checker.IsNil) 47 48 r := bufio.NewReader(stdout) 49 line, err := r.ReadString('\n') 50 c.Assert(err, checker.IsNil) 51 line = strings.TrimSpace(line) 52 c.Assert(line, checker.Equals, "test") 53 err = stdin.Close() 54 c.Assert(err, checker.IsNil) 55 errChan := make(chan error) 56 go func() { 57 errChan <- execCmd.Wait() 58 close(errChan) 59 }() 60 select { 61 case err := <-errChan: 62 c.Assert(err, checker.IsNil) 63 case <-time.After(1 * time.Second): 64 c.Fatal("docker exec failed to exit on stdin close") 65 } 66 67 } 68 69 func (s *DockerSuite) TestExecAfterContainerRestart(c *check.C) { 70 testRequires(c, DaemonIsLinux) 71 out, _ := runSleepingContainer(c) 72 cleanedContainerID := strings.TrimSpace(out) 73 c.Assert(waitRun(cleanedContainerID), check.IsNil) 74 dockerCmd(c, "restart", cleanedContainerID) 75 c.Assert(waitRun(cleanedContainerID), check.IsNil) 76 77 out, _ = dockerCmd(c, "exec", cleanedContainerID, "echo", "hello") 78 outStr := strings.TrimSpace(out) 79 c.Assert(outStr, checker.Equals, "hello") 80 } 81 82 func (s *DockerDaemonSuite) TestExecAfterDaemonRestart(c *check.C) { 83 // TODO Windows CI: Requires a little work to get this ported. 84 testRequires(c, DaemonIsLinux) 85 testRequires(c, SameHostDaemon) 86 87 err := s.d.StartWithBusybox() 88 c.Assert(err, checker.IsNil) 89 90 out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top") 91 c.Assert(err, checker.IsNil, check.Commentf("Could not run top: %s", out)) 92 93 err = s.d.Restart() 94 c.Assert(err, checker.IsNil, check.Commentf("Could not restart daemon")) 95 96 out, err = s.d.Cmd("start", "top") 97 c.Assert(err, checker.IsNil, check.Commentf("Could not start top after daemon restart: %s", out)) 98 99 out, err = s.d.Cmd("exec", "top", "echo", "hello") 100 c.Assert(err, checker.IsNil, check.Commentf("Could not exec on container top: %s", out)) 101 102 outStr := strings.TrimSpace(string(out)) 103 c.Assert(outStr, checker.Equals, "hello") 104 } 105 106 // Regression test for #9155, #9044 107 func (s *DockerSuite) TestExecEnv(c *check.C) { 108 // TODO Windows CI: This one is interesting and may just end up being a feature 109 // difference between Windows and Linux. On Windows, the environment is passed 110 // into the process that is launched, not into the machine environment. Hence 111 // a subsequent exec will not have LALA set/ 112 testRequires(c, DaemonIsLinux) 113 runSleepingContainer(c, "-e", "LALA=value1", "-e", "LALA=value2", "-d", "--name", "testing") 114 c.Assert(waitRun("testing"), check.IsNil) 115 116 out, _ := dockerCmd(c, "exec", "testing", "env") 117 c.Assert(out, checker.Not(checker.Contains), "LALA=value1") 118 c.Assert(out, checker.Contains, "LALA=value2") 119 c.Assert(out, checker.Contains, "HOME=/root") 120 } 121 122 func (s *DockerSuite) TestExecExitStatus(c *check.C) { 123 runSleepingContainer(c, "-d", "--name", "top") 124 125 // Test normal (non-detached) case first 126 cmd := exec.Command(dockerBinary, "exec", "top", "sh", "-c", "exit 23") 127 ec, _ := runCommand(cmd) 128 c.Assert(ec, checker.Equals, 23) 129 } 130 131 func (s *DockerSuite) TestExecPausedContainer(c *check.C) { 132 // Windows does not support pause 133 testRequires(c, DaemonIsLinux) 134 defer unpauseAllContainers() 135 136 out, _ := dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top") 137 ContainerID := strings.TrimSpace(out) 138 139 dockerCmd(c, "pause", "testing") 140 out, _, err := dockerCmdWithError("exec", "-i", "-t", ContainerID, "echo", "hello") 141 c.Assert(err, checker.NotNil, check.Commentf("container should fail to exec new conmmand if it is paused")) 142 143 expected := ContainerID + " is paused, unpause the container before exec" 144 c.Assert(out, checker.Contains, expected, check.Commentf("container should not exec new command if it is paused")) 145 } 146 147 // regression test for #9476 148 func (s *DockerSuite) TestExecTTYCloseStdin(c *check.C) { 149 // TODO Windows CI: This requires some work to port to Windows. 150 testRequires(c, DaemonIsLinux) 151 dockerCmd(c, "run", "-d", "-it", "--name", "exec_tty_stdin", "busybox") 152 153 cmd := exec.Command(dockerBinary, "exec", "-i", "exec_tty_stdin", "cat") 154 stdinRw, err := cmd.StdinPipe() 155 c.Assert(err, checker.IsNil) 156 157 stdinRw.Write([]byte("test")) 158 stdinRw.Close() 159 160 out, _, err := runCommandWithOutput(cmd) 161 c.Assert(err, checker.IsNil, check.Commentf(out)) 162 163 out, _ = dockerCmd(c, "top", "exec_tty_stdin") 164 outArr := strings.Split(out, "\n") 165 c.Assert(len(outArr), checker.LessOrEqualThan, 3, check.Commentf("exec process left running")) 166 c.Assert(out, checker.Not(checker.Contains), "nsenter-exec") 167 } 168 169 func (s *DockerSuite) TestExecTTYWithoutStdin(c *check.C) { 170 // TODO Windows CI: This requires some work to port to Windows. 171 testRequires(c, DaemonIsLinux) 172 out, _ := dockerCmd(c, "run", "-d", "-ti", "busybox") 173 id := strings.TrimSpace(out) 174 c.Assert(waitRun(id), checker.IsNil) 175 176 errChan := make(chan error) 177 go func() { 178 defer close(errChan) 179 180 cmd := exec.Command(dockerBinary, "exec", "-ti", id, "true") 181 if _, err := cmd.StdinPipe(); err != nil { 182 errChan <- err 183 return 184 } 185 186 expected := "cannot enable tty mode" 187 if out, _, err := runCommandWithOutput(cmd); err == nil { 188 errChan <- fmt.Errorf("exec should have failed") 189 return 190 } else if !strings.Contains(out, expected) { 191 errChan <- fmt.Errorf("exec failed with error %q: expected %q", out, expected) 192 return 193 } 194 }() 195 196 select { 197 case err := <-errChan: 198 c.Assert(err, check.IsNil) 199 case <-time.After(3 * time.Second): 200 c.Fatal("exec is running but should have failed") 201 } 202 } 203 204 func (s *DockerSuite) TestExecParseError(c *check.C) { 205 // TODO Windows CI: Requires some extra work. Consider copying the 206 // runSleepingContainer helper to have an exec version. 207 testRequires(c, DaemonIsLinux) 208 dockerCmd(c, "run", "-d", "--name", "top", "busybox", "top") 209 210 // Test normal (non-detached) case first 211 cmd := exec.Command(dockerBinary, "exec", "top") 212 _, stderr, _, err := runCommandWithStdoutStderr(cmd) 213 c.Assert(err, checker.NotNil) 214 c.Assert(stderr, checker.Contains, "See '"+dockerBinary+" exec --help'") 215 } 216 217 func (s *DockerSuite) TestExecStopNotHanging(c *check.C) { 218 // TODO Windows CI: Requires some extra work. Consider copying the 219 // runSleepingContainer helper to have an exec version. 220 testRequires(c, DaemonIsLinux) 221 dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top") 222 223 err := exec.Command(dockerBinary, "exec", "testing", "top").Start() 224 c.Assert(err, checker.IsNil) 225 226 type dstop struct { 227 out []byte 228 err error 229 } 230 231 ch := make(chan dstop) 232 go func() { 233 out, err := exec.Command(dockerBinary, "stop", "testing").CombinedOutput() 234 ch <- dstop{out, err} 235 close(ch) 236 }() 237 select { 238 case <-time.After(3 * time.Second): 239 c.Fatal("Container stop timed out") 240 case s := <-ch: 241 c.Assert(s.err, check.IsNil) 242 } 243 } 244 245 func (s *DockerSuite) TestExecCgroup(c *check.C) { 246 // Not applicable on Windows - using Linux specific functionality 247 testRequires(c, NotUserNamespace) 248 testRequires(c, DaemonIsLinux) 249 dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top") 250 251 out, _ := dockerCmd(c, "exec", "testing", "cat", "/proc/1/cgroup") 252 containerCgroups := sort.StringSlice(strings.Split(out, "\n")) 253 254 var wg sync.WaitGroup 255 var mu sync.Mutex 256 execCgroups := []sort.StringSlice{} 257 errChan := make(chan error) 258 // exec a few times concurrently to get consistent failure 259 for i := 0; i < 5; i++ { 260 wg.Add(1) 261 go func() { 262 out, _, err := dockerCmdWithError("exec", "testing", "cat", "/proc/self/cgroup") 263 if err != nil { 264 errChan <- err 265 return 266 } 267 cg := sort.StringSlice(strings.Split(out, "\n")) 268 269 mu.Lock() 270 execCgroups = append(execCgroups, cg) 271 mu.Unlock() 272 wg.Done() 273 }() 274 } 275 wg.Wait() 276 close(errChan) 277 278 for err := range errChan { 279 c.Assert(err, checker.IsNil) 280 } 281 282 for _, cg := range execCgroups { 283 if !reflect.DeepEqual(cg, containerCgroups) { 284 fmt.Println("exec cgroups:") 285 for _, name := range cg { 286 fmt.Printf(" %s\n", name) 287 } 288 289 fmt.Println("container cgroups:") 290 for _, name := range containerCgroups { 291 fmt.Printf(" %s\n", name) 292 } 293 c.Fatal("cgroups mismatched") 294 } 295 } 296 } 297 298 func (s *DockerSuite) TestExecInspectID(c *check.C) { 299 out, _ := runSleepingContainer(c, "-d") 300 id := strings.TrimSuffix(out, "\n") 301 302 out = inspectField(c, id, "ExecIDs") 303 c.Assert(out, checker.Equals, "[]", check.Commentf("ExecIDs should be empty, got: %s", out)) 304 305 // Start an exec, have it block waiting so we can do some checking 306 cmd := exec.Command(dockerBinary, "exec", id, "sh", "-c", 307 "while ! test -e /execid1; do sleep 1; done") 308 309 err := cmd.Start() 310 c.Assert(err, checker.IsNil, check.Commentf("failed to start the exec cmd")) 311 312 // Give the exec 10 chances/seconds to start then give up and stop the test 313 tries := 10 314 for i := 0; i < tries; i++ { 315 // Since its still running we should see exec as part of the container 316 out = strings.TrimSpace(inspectField(c, id, "ExecIDs")) 317 318 if out != "[]" && out != "<no value>" { 319 break 320 } 321 c.Assert(i+1, checker.Not(checker.Equals), tries, check.Commentf("ExecIDs still empty after 10 second")) 322 time.Sleep(1 * time.Second) 323 } 324 325 // Save execID for later 326 execID, err := inspectFilter(id, "index .ExecIDs 0") 327 c.Assert(err, checker.IsNil, check.Commentf("failed to get the exec id")) 328 329 // End the exec by creating the missing file 330 err = exec.Command(dockerBinary, "exec", id, 331 "sh", "-c", "touch /execid1").Run() 332 333 c.Assert(err, checker.IsNil, check.Commentf("failed to run the 2nd exec cmd")) 334 335 // Wait for 1st exec to complete 336 cmd.Wait() 337 338 // Give the exec 10 chances/seconds to stop then give up and stop the test 339 for i := 0; i < tries; i++ { 340 // Since its still running we should see exec as part of the container 341 out = strings.TrimSpace(inspectField(c, id, "ExecIDs")) 342 343 if out == "[]" { 344 break 345 } 346 c.Assert(i+1, checker.Not(checker.Equals), tries, check.Commentf("ExecIDs still not empty after 10 second")) 347 time.Sleep(1 * time.Second) 348 } 349 350 // But we should still be able to query the execID 351 sc, body, err := sockRequest("GET", "/exec/"+execID+"/json", nil) 352 c.Assert(sc, checker.Equals, http.StatusOK, check.Commentf("received status != 200 OK: %d\n%s", sc, body)) 353 354 // Now delete the container and then an 'inspect' on the exec should 355 // result in a 404 (not 'container not running') 356 out, ec := dockerCmd(c, "rm", "-f", id) 357 c.Assert(ec, checker.Equals, 0, check.Commentf("error removing container: %s", out)) 358 sc, body, err = sockRequest("GET", "/exec/"+execID+"/json", nil) 359 c.Assert(sc, checker.Equals, http.StatusNotFound, check.Commentf("received status != 404: %d\n%s", sc, body)) 360 } 361 362 func (s *DockerSuite) TestLinksPingLinkedContainersOnRename(c *check.C) { 363 // Problematic on Windows as Windows does not support links 364 testRequires(c, DaemonIsLinux) 365 var out string 366 out, _ = dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") 367 idA := strings.TrimSpace(out) 368 c.Assert(idA, checker.Not(checker.Equals), "", check.Commentf("%s, id should not be nil", out)) 369 out, _ = dockerCmd(c, "run", "-d", "--link", "container1:alias1", "--name", "container2", "busybox", "top") 370 idB := strings.TrimSpace(out) 371 c.Assert(idB, checker.Not(checker.Equals), "", check.Commentf("%s, id should not be nil", out)) 372 373 dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1") 374 dockerCmd(c, "rename", "container1", "container_new") 375 dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1") 376 } 377 378 func (s *DockerSuite) TestExecDir(c *check.C) { 379 // TODO Windows CI. This requires some work to port as it uses execDriverPath 380 // which is currently (and incorrectly) hard coded as a string assuming 381 // the daemon is running Linux :( 382 testRequires(c, SameHostDaemon, DaemonIsLinux) 383 384 out, _ := runSleepingContainer(c, "-d") 385 id := strings.TrimSpace(out) 386 387 execDir := filepath.Join(execDriverPath, id) 388 stateFile := filepath.Join(execDir, "state.json") 389 390 { 391 fi, err := os.Stat(execDir) 392 c.Assert(err, checker.IsNil) 393 if !fi.IsDir() { 394 c.Fatalf("%q must be a directory", execDir) 395 } 396 fi, err = os.Stat(stateFile) 397 c.Assert(err, checker.IsNil) 398 } 399 400 dockerCmd(c, "stop", id) 401 { 402 _, err := os.Stat(execDir) 403 c.Assert(err, checker.NotNil) 404 c.Assert(err, checker.NotNil, check.Commentf("Exec directory %q exists for removed container!", execDir)) 405 if !os.IsNotExist(err) { 406 c.Fatalf("Error should be about non-existing, got %s", err) 407 } 408 } 409 dockerCmd(c, "start", id) 410 { 411 fi, err := os.Stat(execDir) 412 c.Assert(err, checker.IsNil) 413 if !fi.IsDir() { 414 c.Fatalf("%q must be a directory", execDir) 415 } 416 fi, err = os.Stat(stateFile) 417 c.Assert(err, checker.IsNil) 418 } 419 dockerCmd(c, "rm", "-f", id) 420 { 421 _, err := os.Stat(execDir) 422 c.Assert(err, checker.NotNil, check.Commentf("Exec directory %q exists for removed container!", execDir)) 423 if !os.IsNotExist(err) { 424 c.Fatalf("Error should be about non-existing, got %s", err) 425 } 426 } 427 } 428 429 func (s *DockerSuite) TestRunMutableNetworkFiles(c *check.C) { 430 // Not applicable on Windows to Windows CI. 431 testRequires(c, SameHostDaemon, DaemonIsLinux) 432 for _, fn := range []string{"resolv.conf", "hosts"} { 433 deleteAllContainers() 434 435 content, err := runCommandAndReadContainerFile(fn, exec.Command(dockerBinary, "run", "-d", "--name", "c1", "busybox", "sh", "-c", fmt.Sprintf("echo success >/etc/%s && top", fn))) 436 c.Assert(err, checker.IsNil) 437 438 c.Assert(strings.TrimSpace(string(content)), checker.Equals, "success", check.Commentf("Content was not what was modified in the container", string(content))) 439 440 out, _ := dockerCmd(c, "run", "-d", "--name", "c2", "busybox", "top") 441 contID := strings.TrimSpace(out) 442 netFilePath := containerStorageFile(contID, fn) 443 444 f, err := os.OpenFile(netFilePath, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644) 445 c.Assert(err, checker.IsNil) 446 447 if _, err := f.Seek(0, 0); err != nil { 448 f.Close() 449 c.Fatal(err) 450 } 451 452 if err := f.Truncate(0); err != nil { 453 f.Close() 454 c.Fatal(err) 455 } 456 457 if _, err := f.Write([]byte("success2\n")); err != nil { 458 f.Close() 459 c.Fatal(err) 460 } 461 f.Close() 462 463 res, _ := dockerCmd(c, "exec", contID, "cat", "/etc/"+fn) 464 c.Assert(res, checker.Equals, "success2\n") 465 } 466 } 467 468 func (s *DockerSuite) TestExecWithUser(c *check.C) { 469 // TODO Windows CI: This may be fixable in the future once Windows 470 // supports users 471 testRequires(c, DaemonIsLinux) 472 dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") 473 474 out, _ := dockerCmd(c, "exec", "-u", "1", "parent", "id") 475 c.Assert(out, checker.Contains, "uid=1(daemon) gid=1(daemon)") 476 477 out, _ = dockerCmd(c, "exec", "-u", "root", "parent", "id") 478 c.Assert(out, checker.Contains, "uid=0(root) gid=0(root)", check.Commentf("exec with user by id expected daemon user got %s", out)) 479 } 480 481 func (s *DockerSuite) TestExecWithPrivileged(c *check.C) { 482 // Not applicable on Windows 483 testRequires(c, DaemonIsLinux, NotUserNamespace) 484 // Start main loop which attempts mknod repeatedly 485 dockerCmd(c, "run", "-d", "--name", "parent", "--cap-drop=ALL", "busybox", "sh", "-c", `while (true); do if [ -e /exec_priv ]; then cat /exec_priv && mknod /tmp/sda b 8 0 && echo "Success"; else echo "Privileged exec has not run yet"; fi; usleep 10000; done`) 486 487 // Check exec mknod doesn't work 488 cmd := exec.Command(dockerBinary, "exec", "parent", "sh", "-c", "mknod /tmp/sdb b 8 16") 489 out, _, err := runCommandWithOutput(cmd) 490 c.Assert(err, checker.NotNil, check.Commentf("exec mknod in --cap-drop=ALL container without --privileged should fail")) 491 c.Assert(out, checker.Contains, "Operation not permitted", check.Commentf("exec mknod in --cap-drop=ALL container without --privileged should fail")) 492 493 // Check exec mknod does work with --privileged 494 cmd = exec.Command(dockerBinary, "exec", "--privileged", "parent", "sh", "-c", `echo "Running exec --privileged" > /exec_priv && mknod /tmp/sdb b 8 16 && usleep 50000 && echo "Finished exec --privileged" > /exec_priv && echo ok`) 495 out, _, err = runCommandWithOutput(cmd) 496 c.Assert(err, checker.IsNil) 497 498 actual := strings.TrimSpace(out) 499 c.Assert(actual, checker.Equals, "ok", check.Commentf("exec mknod in --cap-drop=ALL container with --privileged failed, output: %q", out)) 500 501 // Check subsequent unprivileged exec cannot mknod 502 cmd = exec.Command(dockerBinary, "exec", "parent", "sh", "-c", "mknod /tmp/sdc b 8 32") 503 out, _, err = runCommandWithOutput(cmd) 504 c.Assert(err, checker.NotNil, check.Commentf("repeating exec mknod in --cap-drop=ALL container after --privileged without --privileged should fail")) 505 c.Assert(out, checker.Contains, "Operation not permitted", check.Commentf("repeating exec mknod in --cap-drop=ALL container after --privileged without --privileged should fail")) 506 507 // Confirm at no point was mknod allowed 508 logCmd := exec.Command(dockerBinary, "logs", "parent") 509 out, _, err = runCommandWithOutput(logCmd) 510 c.Assert(err, checker.IsNil) 511 c.Assert(out, checker.Not(checker.Contains), "Success") 512 513 } 514 515 func (s *DockerSuite) TestExecWithImageUser(c *check.C) { 516 // Not applicable on Windows 517 testRequires(c, DaemonIsLinux) 518 name := "testbuilduser" 519 _, err := buildImage(name, 520 `FROM busybox 521 RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd 522 USER dockerio`, 523 true) 524 c.Assert(err, checker.IsNil) 525 526 dockerCmd(c, "run", "-d", "--name", "dockerioexec", name, "top") 527 528 out, _ := dockerCmd(c, "exec", "dockerioexec", "whoami") 529 c.Assert(out, checker.Contains, "dockerio", check.Commentf("exec with user by id expected dockerio user got %s", out)) 530 } 531 532 func (s *DockerSuite) TestExecOnReadonlyContainer(c *check.C) { 533 // Windows does not support read-only 534 // --read-only + userns has remount issues 535 testRequires(c, DaemonIsLinux, NotUserNamespace) 536 dockerCmd(c, "run", "-d", "--read-only", "--name", "parent", "busybox", "top") 537 dockerCmd(c, "exec", "parent", "true") 538 } 539 540 // #15750 541 func (s *DockerSuite) TestExecStartFails(c *check.C) { 542 // TODO Windows CI. This test should be portable. Figure out why it fails 543 // currently. 544 testRequires(c, DaemonIsLinux) 545 name := "exec-15750" 546 runSleepingContainer(c, "-d", "--name", name) 547 c.Assert(waitRun(name), checker.IsNil) 548 549 out, _, err := dockerCmdWithError("exec", name, "no-such-cmd") 550 c.Assert(err, checker.NotNil, check.Commentf(out)) 551 c.Assert(out, checker.Contains, "executable file not found") 552 }