docker_cli_exec_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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(c, "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(c, "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 for input so we can do some checking
  266. cmd := exec.Command(dockerBinary, "exec", "-i", id, "sh", "-c", "read a")
  267. execStdin, _ := cmd.StdinPipe()
  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 closing its stdin, and wait for it to end
  294. execStdin.Close()
  295. cmd.Wait()
  296. // All execs for the container should be gone now
  297. out, err = inspectField(id, "ExecIDs")
  298. if err != nil {
  299. c.Fatalf("failed to inspect container: %s, %v", out, err)
  300. }
  301. out = strings.TrimSuffix(out, "\n")
  302. if out != "[]" && out != "<no value>" {
  303. c.Fatalf("ExecIDs should be empty, got: %s", out)
  304. }
  305. // But we should still be able to query the execID
  306. sc, body, err := sockRequest("GET", "/exec/"+execID+"/json", nil)
  307. if sc != http.StatusOK {
  308. c.Fatalf("received status != 200 OK: %d\n%s", sc, body)
  309. }
  310. }
  311. func (s *DockerSuite) TestLinksPingLinkedContainersOnRename(c *check.C) {
  312. var out string
  313. out, _ = dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
  314. idA := strings.TrimSpace(out)
  315. if idA == "" {
  316. c.Fatal(out, "id should not be nil")
  317. }
  318. out, _ = dockerCmd(c, "run", "-d", "--link", "container1:alias1", "--name", "container2", "busybox", "top")
  319. idB := strings.TrimSpace(out)
  320. if idB == "" {
  321. c.Fatal(out, "id should not be nil")
  322. }
  323. dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1")
  324. dockerCmd(c, "rename", "container1", "container_new")
  325. dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1")
  326. }
  327. func (s *DockerSuite) TestRunExecDir(c *check.C) {
  328. testRequires(c, SameHostDaemon)
  329. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  330. id := strings.TrimSpace(out)
  331. execDir := filepath.Join(execDriverPath, id)
  332. stateFile := filepath.Join(execDir, "state.json")
  333. {
  334. fi, err := os.Stat(execDir)
  335. if err != nil {
  336. c.Fatal(err)
  337. }
  338. if !fi.IsDir() {
  339. c.Fatalf("%q must be a directory", execDir)
  340. }
  341. fi, err = os.Stat(stateFile)
  342. if err != nil {
  343. c.Fatal(err)
  344. }
  345. }
  346. dockerCmd(c, "stop", id)
  347. {
  348. _, err := os.Stat(execDir)
  349. if err == nil {
  350. c.Fatal(err)
  351. }
  352. if err == nil {
  353. c.Fatalf("Exec directory %q exists for removed container!", execDir)
  354. }
  355. if !os.IsNotExist(err) {
  356. c.Fatalf("Error should be about non-existing, got %s", err)
  357. }
  358. }
  359. dockerCmd(c, "start", id)
  360. {
  361. fi, err := os.Stat(execDir)
  362. if err != nil {
  363. c.Fatal(err)
  364. }
  365. if !fi.IsDir() {
  366. c.Fatalf("%q must be a directory", execDir)
  367. }
  368. fi, err = os.Stat(stateFile)
  369. if err != nil {
  370. c.Fatal(err)
  371. }
  372. }
  373. dockerCmd(c, "rm", "-f", id)
  374. {
  375. _, err := os.Stat(execDir)
  376. if err == nil {
  377. c.Fatal(err)
  378. }
  379. if err == nil {
  380. c.Fatalf("Exec directory %q is exists for removed container!", execDir)
  381. }
  382. if !os.IsNotExist(err) {
  383. c.Fatalf("Error should be about non-existing, got %s", err)
  384. }
  385. }
  386. }
  387. func (s *DockerSuite) TestRunMutableNetworkFiles(c *check.C) {
  388. testRequires(c, SameHostDaemon)
  389. for _, fn := range []string{"resolv.conf", "hosts"} {
  390. deleteAllContainers()
  391. content, err := runCommandAndReadContainerFile(fn, exec.Command(dockerBinary, "run", "-d", "--name", "c1", "busybox", "sh", "-c", fmt.Sprintf("echo success >/etc/%s && top", fn)))
  392. if err != nil {
  393. c.Fatal(err)
  394. }
  395. if strings.TrimSpace(string(content)) != "success" {
  396. c.Fatal("Content was not what was modified in the container", string(content))
  397. }
  398. out, _ := dockerCmd(c, "run", "-d", "--name", "c2", "busybox", "top")
  399. contID := strings.TrimSpace(out)
  400. netFilePath := containerStorageFile(contID, fn)
  401. f, err := os.OpenFile(netFilePath, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644)
  402. if err != nil {
  403. c.Fatal(err)
  404. }
  405. if _, err := f.Seek(0, 0); err != nil {
  406. f.Close()
  407. c.Fatal(err)
  408. }
  409. if err := f.Truncate(0); err != nil {
  410. f.Close()
  411. c.Fatal(err)
  412. }
  413. if _, err := f.Write([]byte("success2\n")); err != nil {
  414. f.Close()
  415. c.Fatal(err)
  416. }
  417. f.Close()
  418. res, _ := dockerCmd(c, "exec", contID, "cat", "/etc/"+fn)
  419. if res != "success2\n" {
  420. c.Fatalf("Expected content of %s: %q, got: %q", fn, "success2\n", res)
  421. }
  422. }
  423. }
  424. func (s *DockerSuite) TestExecWithUser(c *check.C) {
  425. dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top")
  426. out, _ := dockerCmd(c, "exec", "-u", "1", "parent", "id")
  427. if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
  428. c.Fatalf("exec with user by id expected daemon user got %s", out)
  429. }
  430. out, _ = dockerCmd(c, "exec", "-u", "root", "parent", "id")
  431. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  432. c.Fatalf("exec with user by root expected root user got %s", out)
  433. }
  434. }
  435. func (s *DockerSuite) TestExecWithImageUser(c *check.C) {
  436. name := "testbuilduser"
  437. _, err := buildImage(name,
  438. `FROM busybox
  439. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  440. USER dockerio`,
  441. true)
  442. if err != nil {
  443. c.Fatalf("Could not build image %s: %v", name, err)
  444. }
  445. dockerCmd(c, "run", "-d", "--name", "dockerioexec", name, "top")
  446. out, _ := dockerCmd(c, "exec", "dockerioexec", "whoami")
  447. if !strings.Contains(out, "dockerio") {
  448. c.Fatalf("exec with user by id expected dockerio user got %s", out)
  449. }
  450. }