docker_cli_exec_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. // +build !test_no_exec
  2. package main
  3. import (
  4. "bufio"
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "reflect"
  11. "sort"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/go-check/check"
  16. )
  17. func (s *DockerSuite) TestExec(c *check.C) {
  18. dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top")
  19. out, _ := dockerCmd(c, "exec", "testing", "cat", "/tmp/file")
  20. out = strings.Trim(out, "\r\n")
  21. if out != "test" {
  22. c.Errorf("container exec should've printed test but printed %q", out)
  23. }
  24. }
  25. func (s *DockerSuite) TestExecInteractive(c *check.C) {
  26. dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top")
  27. execCmd := exec.Command(dockerBinary, "exec", "-i", "testing", "sh")
  28. stdin, err := execCmd.StdinPipe()
  29. if err != nil {
  30. c.Fatal(err)
  31. }
  32. stdout, err := execCmd.StdoutPipe()
  33. if err != nil {
  34. c.Fatal(err)
  35. }
  36. if err := execCmd.Start(); err != nil {
  37. c.Fatal(err)
  38. }
  39. if _, err := stdin.Write([]byte("cat /tmp/file\n")); err != nil {
  40. c.Fatal(err)
  41. }
  42. r := bufio.NewReader(stdout)
  43. line, err := r.ReadString('\n')
  44. if err != nil {
  45. c.Fatal(err)
  46. }
  47. line = strings.TrimSpace(line)
  48. if line != "test" {
  49. c.Fatalf("Output should be 'test', got '%q'", line)
  50. }
  51. if err := stdin.Close(); err != nil {
  52. c.Fatal(err)
  53. }
  54. errChan := make(chan error)
  55. go func() {
  56. errChan <- execCmd.Wait()
  57. close(errChan)
  58. }()
  59. select {
  60. case err := <-errChan:
  61. c.Assert(err, check.IsNil)
  62. case <-time.After(1 * time.Second):
  63. c.Fatal("docker exec failed to exit on stdin close")
  64. }
  65. }
  66. func (s *DockerSuite) TestExecAfterContainerRestart(c *check.C) {
  67. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  68. cleanedContainerID := strings.TrimSpace(out)
  69. dockerCmd(c, "restart", cleanedContainerID)
  70. out, _ = dockerCmd(c, "exec", cleanedContainerID, "echo", "hello")
  71. outStr := strings.TrimSpace(out)
  72. if outStr != "hello" {
  73. c.Errorf("container should've printed hello, instead printed %q", outStr)
  74. }
  75. }
  76. func (s *DockerDaemonSuite) TestExecAfterDaemonRestart(c *check.C) {
  77. testRequires(c, SameHostDaemon)
  78. if err := s.d.StartWithBusybox(); err != nil {
  79. c.Fatalf("Could not start daemon with busybox: %v", err)
  80. }
  81. if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil {
  82. c.Fatalf("Could not run top: err=%v\n%s", err, out)
  83. }
  84. if err := s.d.Restart(); err != nil {
  85. c.Fatalf("Could not restart daemon: %v", err)
  86. }
  87. if out, err := s.d.Cmd("start", "top"); err != nil {
  88. c.Fatalf("Could not start top after daemon restart: err=%v\n%s", err, out)
  89. }
  90. out, err := s.d.Cmd("exec", "top", "echo", "hello")
  91. if err != nil {
  92. c.Fatalf("Could not exec on container top: err=%v\n%s", err, out)
  93. }
  94. outStr := strings.TrimSpace(string(out))
  95. if outStr != "hello" {
  96. c.Errorf("container should've printed hello, instead printed %q", outStr)
  97. }
  98. }
  99. // Regression test for #9155, #9044
  100. func (s *DockerSuite) TestExecEnv(c *check.C) {
  101. dockerCmd(c, "run", "-e", "LALA=value1", "-e", "LALA=value2",
  102. "-d", "--name", "testing", "busybox", "top")
  103. out, _ := dockerCmd(c, "exec", "testing", "env")
  104. if strings.Contains(out, "LALA=value1") ||
  105. !strings.Contains(out, "LALA=value2") ||
  106. !strings.Contains(out, "HOME=/root") {
  107. c.Errorf("exec env(%q), expect %q, %q", out, "LALA=value2", "HOME=/root")
  108. }
  109. }
  110. func (s *DockerSuite) TestExecExitStatus(c *check.C) {
  111. dockerCmd(c, "run", "-d", "--name", "top", "busybox", "top")
  112. // Test normal (non-detached) case first
  113. cmd := exec.Command(dockerBinary, "exec", "top", "sh", "-c", "exit 23")
  114. ec, _ := runCommand(cmd)
  115. if ec != 23 {
  116. c.Fatalf("Should have had an ExitCode of 23, not: %d", ec)
  117. }
  118. }
  119. func (s *DockerSuite) TestExecPausedContainer(c *check.C) {
  120. defer unpauseAllContainers()
  121. out, _ := dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top")
  122. ContainerID := strings.TrimSpace(out)
  123. dockerCmd(c, "pause", "testing")
  124. out, _, err := dockerCmdWithError("exec", "-i", "-t", ContainerID, "echo", "hello")
  125. if err == nil {
  126. c.Fatal("container should fail to exec new command if it is paused")
  127. }
  128. expected := ContainerID + " is paused, unpause the container before exec"
  129. if !strings.Contains(out, expected) {
  130. c.Fatal("container should not exec new command if it is paused")
  131. }
  132. }
  133. // regression test for #9476
  134. func (s *DockerSuite) TestExecTtyCloseStdin(c *check.C) {
  135. dockerCmd(c, "run", "-d", "-it", "--name", "exec_tty_stdin", "busybox")
  136. cmd := exec.Command(dockerBinary, "exec", "-i", "exec_tty_stdin", "cat")
  137. stdinRw, err := cmd.StdinPipe()
  138. if err != nil {
  139. c.Fatal(err)
  140. }
  141. stdinRw.Write([]byte("test"))
  142. stdinRw.Close()
  143. if out, _, err := runCommandWithOutput(cmd); err != nil {
  144. c.Fatal(out, err)
  145. }
  146. out, _ := dockerCmd(c, "top", "exec_tty_stdin")
  147. outArr := strings.Split(out, "\n")
  148. if len(outArr) > 3 || strings.Contains(out, "nsenter-exec") {
  149. c.Fatalf("exec process left running\n\t %s", out)
  150. }
  151. }
  152. func (s *DockerSuite) TestExecTtyWithoutStdin(c *check.C) {
  153. out, _ := dockerCmd(c, "run", "-d", "-ti", "busybox")
  154. id := strings.TrimSpace(out)
  155. if err := waitRun(id); err != nil {
  156. c.Fatal(err)
  157. }
  158. errChan := make(chan error)
  159. go func() {
  160. defer close(errChan)
  161. cmd := exec.Command(dockerBinary, "exec", "-ti", id, "true")
  162. if _, err := cmd.StdinPipe(); err != nil {
  163. errChan <- err
  164. return
  165. }
  166. expected := "cannot enable tty mode"
  167. if out, _, err := runCommandWithOutput(cmd); err == nil {
  168. errChan <- fmt.Errorf("exec should have failed")
  169. return
  170. } else if !strings.Contains(out, expected) {
  171. errChan <- fmt.Errorf("exec failed with error %q: expected %q", out, expected)
  172. return
  173. }
  174. }()
  175. select {
  176. case err := <-errChan:
  177. c.Assert(err, check.IsNil)
  178. case <-time.After(3 * time.Second):
  179. c.Fatal("exec is running but should have failed")
  180. }
  181. }
  182. func (s *DockerSuite) TestExecParseError(c *check.C) {
  183. dockerCmd(c, "run", "-d", "--name", "top", "busybox", "top")
  184. // Test normal (non-detached) case first
  185. cmd := exec.Command(dockerBinary, "exec", "top")
  186. if _, stderr, code, err := runCommandWithStdoutStderr(cmd); err == nil || !strings.Contains(stderr, "See '"+dockerBinary+" exec --help'") || code == 0 {
  187. c.Fatalf("Should have thrown error & point to help: %s", stderr)
  188. }
  189. }
  190. func (s *DockerSuite) TestExecStopNotHanging(c *check.C) {
  191. dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top")
  192. if err := exec.Command(dockerBinary, "exec", "testing", "top").Start(); err != nil {
  193. c.Fatal(err)
  194. }
  195. type dstop struct {
  196. out []byte
  197. err error
  198. }
  199. ch := make(chan dstop)
  200. go func() {
  201. out, err := exec.Command(dockerBinary, "stop", "testing").CombinedOutput()
  202. ch <- dstop{out, err}
  203. close(ch)
  204. }()
  205. select {
  206. case <-time.After(3 * time.Second):
  207. c.Fatal("Container stop timed out")
  208. case s := <-ch:
  209. c.Assert(s.err, check.IsNil)
  210. }
  211. }
  212. func (s *DockerSuite) TestExecCgroup(c *check.C) {
  213. dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top")
  214. out, _ := dockerCmd(c, "exec", "testing", "cat", "/proc/1/cgroup")
  215. containerCgroups := sort.StringSlice(strings.Split(out, "\n"))
  216. var wg sync.WaitGroup
  217. var mu sync.Mutex
  218. execCgroups := []sort.StringSlice{}
  219. errChan := make(chan error)
  220. // exec a few times concurrently to get consistent failure
  221. for i := 0; i < 5; i++ {
  222. wg.Add(1)
  223. go func() {
  224. out, _, err := dockerCmdWithError("exec", "testing", "cat", "/proc/self/cgroup")
  225. if err != nil {
  226. errChan <- err
  227. return
  228. }
  229. cg := sort.StringSlice(strings.Split(out, "\n"))
  230. mu.Lock()
  231. execCgroups = append(execCgroups, cg)
  232. mu.Unlock()
  233. wg.Done()
  234. }()
  235. }
  236. wg.Wait()
  237. close(errChan)
  238. for err := range errChan {
  239. c.Assert(err, check.IsNil)
  240. }
  241. for _, cg := range execCgroups {
  242. if !reflect.DeepEqual(cg, containerCgroups) {
  243. fmt.Println("exec cgroups:")
  244. for _, name := range cg {
  245. fmt.Printf(" %s\n", name)
  246. }
  247. fmt.Println("container cgroups:")
  248. for _, name := range containerCgroups {
  249. fmt.Printf(" %s\n", name)
  250. }
  251. c.Fatal("cgroups mismatched")
  252. }
  253. }
  254. }
  255. func (s *DockerSuite) TestInspectExecID(c *check.C) {
  256. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  257. id := strings.TrimSuffix(out, "\n")
  258. out, err := inspectField(id, "ExecIDs")
  259. if err != nil {
  260. c.Fatalf("failed to inspect container: %s, %v", out, err)
  261. }
  262. if out != "[]" {
  263. c.Fatalf("ExecIDs should be empty, got: %s", out)
  264. }
  265. // Start an exec, have it block waiting so we can do some checking
  266. cmd := exec.Command(dockerBinary, "exec", id, "sh", "-c",
  267. "while ! test -e /tmp/execid1; do sleep 1; done")
  268. if err = cmd.Start(); err != nil {
  269. c.Fatalf("failed to start the exec cmd: %q", err)
  270. }
  271. // Give the exec 10 chances/seconds to start then give up and stop the test
  272. tries := 10
  273. for i := 0; i < tries; i++ {
  274. // Since its still running we should see exec as part of the container
  275. out, err = inspectField(id, "ExecIDs")
  276. if err != nil {
  277. c.Fatalf("failed to inspect container: %s, %v", out, err)
  278. }
  279. out = strings.TrimSuffix(out, "\n")
  280. if out != "[]" && out != "<no value>" {
  281. break
  282. }
  283. if i+1 == tries {
  284. c.Fatalf("ExecIDs should not be empty, got: %s", out)
  285. }
  286. time.Sleep(1 * time.Second)
  287. }
  288. // Save execID for later
  289. execID, err := inspectFilter(id, "index .ExecIDs 0")
  290. if err != nil {
  291. c.Fatalf("failed to get the exec id: %v", err)
  292. }
  293. // End the exec by creating the missing file
  294. err = exec.Command(dockerBinary, "exec", id,
  295. "sh", "-c", "touch /tmp/execid1").Run()
  296. if err != nil {
  297. c.Fatalf("failed to run the 2nd exec cmd: %q", err)
  298. }
  299. // Wait for 1st exec to complete
  300. cmd.Wait()
  301. // All execs for the container should be gone now
  302. out, err = inspectField(id, "ExecIDs")
  303. if err != nil {
  304. c.Fatalf("failed to inspect container: %s, %v", out, err)
  305. }
  306. out = strings.TrimSuffix(out, "\n")
  307. if out != "[]" && out != "<no value>" {
  308. c.Fatalf("ExecIDs should be empty, got: %s", out)
  309. }
  310. // But we should still be able to query the execID
  311. sc, body, err := sockRequest("GET", "/exec/"+execID+"/json", nil)
  312. if sc != http.StatusOK {
  313. c.Fatalf("received status != 200 OK: %d\n%s", sc, body)
  314. }
  315. // Now delete the container and then an 'inspect' on the exec should
  316. // result in a 404 (not 'container not running')
  317. out, ec := dockerCmd(c, "rm", "-f", id)
  318. if ec != 0 {
  319. c.Fatalf("error removing container: %s", out)
  320. }
  321. sc, body, err = sockRequest("GET", "/exec/"+execID+"/json", nil)
  322. if sc != http.StatusNotFound {
  323. c.Fatalf("received status != 404: %s\n%s", sc, body)
  324. }
  325. }
  326. func (s *DockerSuite) TestLinksPingLinkedContainersOnRename(c *check.C) {
  327. var out string
  328. out, _ = dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
  329. idA := strings.TrimSpace(out)
  330. if idA == "" {
  331. c.Fatal(out, "id should not be nil")
  332. }
  333. out, _ = dockerCmd(c, "run", "-d", "--link", "container1:alias1", "--name", "container2", "busybox", "top")
  334. idB := strings.TrimSpace(out)
  335. if idB == "" {
  336. c.Fatal(out, "id should not be nil")
  337. }
  338. dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1")
  339. dockerCmd(c, "rename", "container1", "container_new")
  340. dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1")
  341. }
  342. func (s *DockerSuite) TestRunExecDir(c *check.C) {
  343. testRequires(c, SameHostDaemon)
  344. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  345. id := strings.TrimSpace(out)
  346. execDir := filepath.Join(execDriverPath, id)
  347. stateFile := filepath.Join(execDir, "state.json")
  348. {
  349. fi, err := os.Stat(execDir)
  350. if err != nil {
  351. c.Fatal(err)
  352. }
  353. if !fi.IsDir() {
  354. c.Fatalf("%q must be a directory", execDir)
  355. }
  356. fi, err = os.Stat(stateFile)
  357. if err != nil {
  358. c.Fatal(err)
  359. }
  360. }
  361. dockerCmd(c, "stop", id)
  362. {
  363. _, err := os.Stat(execDir)
  364. if err == nil {
  365. c.Fatal(err)
  366. }
  367. if err == nil {
  368. c.Fatalf("Exec directory %q exists for removed container!", execDir)
  369. }
  370. if !os.IsNotExist(err) {
  371. c.Fatalf("Error should be about non-existing, got %s", err)
  372. }
  373. }
  374. dockerCmd(c, "start", id)
  375. {
  376. fi, err := os.Stat(execDir)
  377. if err != nil {
  378. c.Fatal(err)
  379. }
  380. if !fi.IsDir() {
  381. c.Fatalf("%q must be a directory", execDir)
  382. }
  383. fi, err = os.Stat(stateFile)
  384. if err != nil {
  385. c.Fatal(err)
  386. }
  387. }
  388. dockerCmd(c, "rm", "-f", id)
  389. {
  390. _, err := os.Stat(execDir)
  391. if err == nil {
  392. c.Fatal(err)
  393. }
  394. if err == nil {
  395. c.Fatalf("Exec directory %q is exists for removed container!", execDir)
  396. }
  397. if !os.IsNotExist(err) {
  398. c.Fatalf("Error should be about non-existing, got %s", err)
  399. }
  400. }
  401. }
  402. func (s *DockerSuite) TestRunMutableNetworkFiles(c *check.C) {
  403. testRequires(c, SameHostDaemon)
  404. for _, fn := range []string{"resolv.conf", "hosts"} {
  405. deleteAllContainers()
  406. content, err := runCommandAndReadContainerFile(fn, exec.Command(dockerBinary, "run", "-d", "--name", "c1", "busybox", "sh", "-c", fmt.Sprintf("echo success >/etc/%s && top", fn)))
  407. if err != nil {
  408. c.Fatal(err)
  409. }
  410. if strings.TrimSpace(string(content)) != "success" {
  411. c.Fatal("Content was not what was modified in the container", string(content))
  412. }
  413. out, _ := dockerCmd(c, "run", "-d", "--name", "c2", "busybox", "top")
  414. contID := strings.TrimSpace(out)
  415. netFilePath := containerStorageFile(contID, fn)
  416. f, err := os.OpenFile(netFilePath, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644)
  417. if err != nil {
  418. c.Fatal(err)
  419. }
  420. if _, err := f.Seek(0, 0); err != nil {
  421. f.Close()
  422. c.Fatal(err)
  423. }
  424. if err := f.Truncate(0); err != nil {
  425. f.Close()
  426. c.Fatal(err)
  427. }
  428. if _, err := f.Write([]byte("success2\n")); err != nil {
  429. f.Close()
  430. c.Fatal(err)
  431. }
  432. f.Close()
  433. res, _ := dockerCmd(c, "exec", contID, "cat", "/etc/"+fn)
  434. if res != "success2\n" {
  435. c.Fatalf("Expected content of %s: %q, got: %q", fn, "success2\n", res)
  436. }
  437. }
  438. }
  439. func (s *DockerSuite) TestExecWithUser(c *check.C) {
  440. dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top")
  441. out, _ := dockerCmd(c, "exec", "-u", "1", "parent", "id")
  442. if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
  443. c.Fatalf("exec with user by id expected daemon user got %s", out)
  444. }
  445. out, _ = dockerCmd(c, "exec", "-u", "root", "parent", "id")
  446. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  447. c.Fatalf("exec with user by root expected root user got %s", out)
  448. }
  449. }
  450. func (s *DockerSuite) TestExecWithImageUser(c *check.C) {
  451. name := "testbuilduser"
  452. _, err := buildImage(name,
  453. `FROM busybox
  454. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  455. USER dockerio`,
  456. true)
  457. if err != nil {
  458. c.Fatalf("Could not build image %s: %v", name, err)
  459. }
  460. dockerCmd(c, "run", "-d", "--name", "dockerioexec", name, "top")
  461. out, _ := dockerCmd(c, "exec", "dockerioexec", "whoami")
  462. if !strings.Contains(out, "dockerio") {
  463. c.Fatalf("exec with user by id expected dockerio user got %s", out)
  464. }
  465. }
  466. func (s *DockerSuite) TestExecOnReadonlyContainer(c *check.C) {
  467. dockerCmd(c, "run", "-d", "--read-only", "--name", "parent", "busybox", "top")
  468. if _, status := dockerCmd(c, "exec", "parent", "true"); status != 0 {
  469. c.Fatalf("exec into a read-only container failed with exit status %d", status)
  470. }
  471. }