docker_cli_exec_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. defer func() {
  159. dockerCmd(c, "kill", id)
  160. }()
  161. errChan := make(chan error)
  162. go func() {
  163. defer close(errChan)
  164. cmd := exec.Command(dockerBinary, "exec", "-ti", id, "true")
  165. if _, err := cmd.StdinPipe(); err != nil {
  166. errChan <- err
  167. return
  168. }
  169. expected := "cannot enable tty mode"
  170. if out, _, err := runCommandWithOutput(cmd); err == nil {
  171. errChan <- fmt.Errorf("exec should have failed")
  172. return
  173. } else if !strings.Contains(out, expected) {
  174. errChan <- fmt.Errorf("exec failed with error %q: expected %q", out, expected)
  175. return
  176. }
  177. }()
  178. select {
  179. case err := <-errChan:
  180. c.Assert(err, check.IsNil)
  181. case <-time.After(3 * time.Second):
  182. c.Fatal("exec is running but should have failed")
  183. }
  184. }
  185. func (s *DockerSuite) TestExecParseError(c *check.C) {
  186. dockerCmd(c, "run", "-d", "--name", "top", "busybox", "top")
  187. // Test normal (non-detached) case first
  188. cmd := exec.Command(dockerBinary, "exec", "top")
  189. if _, stderr, code, err := runCommandWithStdoutStderr(cmd); err == nil || !strings.Contains(stderr, "See '"+dockerBinary+" exec --help'") || code == 0 {
  190. c.Fatalf("Should have thrown error & point to help: %s", stderr)
  191. }
  192. }
  193. func (s *DockerSuite) TestExecStopNotHanging(c *check.C) {
  194. dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top")
  195. if err := exec.Command(dockerBinary, "exec", "testing", "top").Start(); err != nil {
  196. c.Fatal(err)
  197. }
  198. type dstop struct {
  199. out []byte
  200. err error
  201. }
  202. ch := make(chan dstop)
  203. go func() {
  204. out, err := exec.Command(dockerBinary, "stop", "testing").CombinedOutput()
  205. ch <- dstop{out, err}
  206. close(ch)
  207. }()
  208. select {
  209. case <-time.After(3 * time.Second):
  210. c.Fatal("Container stop timed out")
  211. case s := <-ch:
  212. c.Assert(s.err, check.IsNil)
  213. }
  214. }
  215. func (s *DockerSuite) TestExecCgroup(c *check.C) {
  216. dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top")
  217. out, _ := dockerCmd(c, "exec", "testing", "cat", "/proc/1/cgroup")
  218. containerCgroups := sort.StringSlice(strings.Split(out, "\n"))
  219. var wg sync.WaitGroup
  220. var mu sync.Mutex
  221. execCgroups := []sort.StringSlice{}
  222. errChan := make(chan error)
  223. // exec a few times concurrently to get consistent failure
  224. for i := 0; i < 5; i++ {
  225. wg.Add(1)
  226. go func() {
  227. out, _, err := dockerCmdWithError(c, "exec", "testing", "cat", "/proc/self/cgroup")
  228. if err != nil {
  229. errChan <- err
  230. return
  231. }
  232. cg := sort.StringSlice(strings.Split(out, "\n"))
  233. mu.Lock()
  234. execCgroups = append(execCgroups, cg)
  235. mu.Unlock()
  236. wg.Done()
  237. }()
  238. }
  239. wg.Wait()
  240. close(errChan)
  241. for err := range errChan {
  242. c.Assert(err, check.IsNil)
  243. }
  244. for _, cg := range execCgroups {
  245. if !reflect.DeepEqual(cg, containerCgroups) {
  246. fmt.Println("exec cgroups:")
  247. for _, name := range cg {
  248. fmt.Printf(" %s\n", name)
  249. }
  250. fmt.Println("container cgroups:")
  251. for _, name := range containerCgroups {
  252. fmt.Printf(" %s\n", name)
  253. }
  254. c.Fatal("cgroups mismatched")
  255. }
  256. }
  257. }
  258. func (s *DockerSuite) TestInspectExecID(c *check.C) {
  259. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  260. id := strings.TrimSuffix(out, "\n")
  261. out, err := inspectField(id, "ExecIDs")
  262. if err != nil {
  263. c.Fatalf("failed to inspect container: %s, %v", out, err)
  264. }
  265. if out != "[]" {
  266. c.Fatalf("ExecIDs should be empty, got: %s", out)
  267. }
  268. // Start an exec, have it block waiting for input so we can do some checking
  269. cmd := exec.Command(dockerBinary, "exec", "-i", id, "sh", "-c", "read a")
  270. execStdin, _ := cmd.StdinPipe()
  271. if err = cmd.Start(); err != nil {
  272. c.Fatalf("failed to start the exec cmd: %q", err)
  273. }
  274. // Give the exec 10 chances/seconds to start then give up and stop the test
  275. tries := 10
  276. for i := 0; i < tries; i++ {
  277. // Since its still running we should see exec as part of the container
  278. out, err = inspectField(id, "ExecIDs")
  279. if err != nil {
  280. c.Fatalf("failed to inspect container: %s, %v", out, err)
  281. }
  282. out = strings.TrimSuffix(out, "\n")
  283. if out != "[]" && out != "<no value>" {
  284. break
  285. }
  286. if i+1 == tries {
  287. c.Fatalf("ExecIDs should not be empty, got: %s", out)
  288. }
  289. time.Sleep(1 * time.Second)
  290. }
  291. // Save execID for later
  292. execID, err := inspectFilter(id, "index .ExecIDs 0")
  293. if err != nil {
  294. c.Fatalf("failed to get the exec id: %v", err)
  295. }
  296. // End the exec by closing its stdin, and wait for it to end
  297. execStdin.Close()
  298. cmd.Wait()
  299. // All execs for the container should be gone now
  300. out, err = inspectField(id, "ExecIDs")
  301. if err != nil {
  302. c.Fatalf("failed to inspect container: %s, %v", out, err)
  303. }
  304. out = strings.TrimSuffix(out, "\n")
  305. if out != "[]" && out != "<no value>" {
  306. c.Fatalf("ExecIDs should be empty, got: %s", out)
  307. }
  308. // But we should still be able to query the execID
  309. sc, body, err := sockRequest("GET", "/exec/"+execID+"/json", nil)
  310. if sc != http.StatusOK {
  311. c.Fatalf("received status != 200 OK: %d\n%s", sc, body)
  312. }
  313. }
  314. func (s *DockerSuite) TestLinksPingLinkedContainersOnRename(c *check.C) {
  315. var out string
  316. out, _ = dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
  317. idA := strings.TrimSpace(out)
  318. if idA == "" {
  319. c.Fatal(out, "id should not be nil")
  320. }
  321. out, _ = dockerCmd(c, "run", "-d", "--link", "container1:alias1", "--name", "container2", "busybox", "top")
  322. idB := strings.TrimSpace(out)
  323. if idB == "" {
  324. c.Fatal(out, "id should not be nil")
  325. }
  326. dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1")
  327. dockerCmd(c, "rename", "container1", "container_new")
  328. dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1")
  329. }
  330. func (s *DockerSuite) TestRunExecDir(c *check.C) {
  331. testRequires(c, SameHostDaemon)
  332. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  333. id := strings.TrimSpace(out)
  334. execDir := filepath.Join(execDriverPath, id)
  335. stateFile := filepath.Join(execDir, "state.json")
  336. {
  337. fi, err := os.Stat(execDir)
  338. if err != nil {
  339. c.Fatal(err)
  340. }
  341. if !fi.IsDir() {
  342. c.Fatalf("%q must be a directory", execDir)
  343. }
  344. fi, err = os.Stat(stateFile)
  345. if err != nil {
  346. c.Fatal(err)
  347. }
  348. }
  349. dockerCmd(c, "stop", id)
  350. {
  351. _, err := os.Stat(execDir)
  352. if err == nil {
  353. c.Fatal(err)
  354. }
  355. if err == nil {
  356. c.Fatalf("Exec directory %q exists for removed container!", execDir)
  357. }
  358. if !os.IsNotExist(err) {
  359. c.Fatalf("Error should be about non-existing, got %s", err)
  360. }
  361. }
  362. dockerCmd(c, "start", id)
  363. {
  364. fi, err := os.Stat(execDir)
  365. if err != nil {
  366. c.Fatal(err)
  367. }
  368. if !fi.IsDir() {
  369. c.Fatalf("%q must be a directory", execDir)
  370. }
  371. fi, err = os.Stat(stateFile)
  372. if err != nil {
  373. c.Fatal(err)
  374. }
  375. }
  376. dockerCmd(c, "rm", "-f", id)
  377. {
  378. _, err := os.Stat(execDir)
  379. if err == nil {
  380. c.Fatal(err)
  381. }
  382. if err == nil {
  383. c.Fatalf("Exec directory %q is exists for removed container!", execDir)
  384. }
  385. if !os.IsNotExist(err) {
  386. c.Fatalf("Error should be about non-existing, got %s", err)
  387. }
  388. }
  389. }
  390. func (s *DockerSuite) TestRunMutableNetworkFiles(c *check.C) {
  391. testRequires(c, SameHostDaemon)
  392. for _, fn := range []string{"resolv.conf", "hosts"} {
  393. deleteAllContainers()
  394. content, err := runCommandAndReadContainerFile(fn, exec.Command(dockerBinary, "run", "-d", "--name", "c1", "busybox", "sh", "-c", fmt.Sprintf("echo success >/etc/%s && top", fn)))
  395. if err != nil {
  396. c.Fatal(err)
  397. }
  398. if strings.TrimSpace(string(content)) != "success" {
  399. c.Fatal("Content was not what was modified in the container", string(content))
  400. }
  401. out, _ := dockerCmd(c, "run", "-d", "--name", "c2", "busybox", "top")
  402. contID := strings.TrimSpace(out)
  403. netFilePath := containerStorageFile(contID, fn)
  404. f, err := os.OpenFile(netFilePath, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644)
  405. if err != nil {
  406. c.Fatal(err)
  407. }
  408. if _, err := f.Seek(0, 0); err != nil {
  409. f.Close()
  410. c.Fatal(err)
  411. }
  412. if err := f.Truncate(0); err != nil {
  413. f.Close()
  414. c.Fatal(err)
  415. }
  416. if _, err := f.Write([]byte("success2\n")); err != nil {
  417. f.Close()
  418. c.Fatal(err)
  419. }
  420. f.Close()
  421. res, _ := dockerCmd(c, "exec", contID, "cat", "/etc/"+fn)
  422. if res != "success2\n" {
  423. c.Fatalf("Expected content of %s: %q, got: %q", fn, "success2\n", res)
  424. }
  425. }
  426. }
  427. func (s *DockerSuite) TestExecWithUser(c *check.C) {
  428. dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top")
  429. out, _ := dockerCmd(c, "exec", "-u", "1", "parent", "id")
  430. if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
  431. c.Fatalf("exec with user by id expected daemon user got %s", out)
  432. }
  433. out, _ = dockerCmd(c, "exec", "-u", "root", "parent", "id")
  434. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  435. c.Fatalf("exec with user by root expected root user got %s", out)
  436. }
  437. }
  438. func (s *DockerSuite) TestExecWithImageUser(c *check.C) {
  439. name := "testbuilduser"
  440. _, err := buildImage(name,
  441. `FROM busybox
  442. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  443. USER dockerio`,
  444. true)
  445. if err != nil {
  446. c.Fatalf("Could not build image %s: %v", name, err)
  447. }
  448. dockerCmd(c, "run", "-d", "--name", "dockerioexec", name, "top")
  449. out, _ := dockerCmd(c, "exec", "dockerioexec", "whoami")
  450. if !strings.Contains(out, "dockerio") {
  451. c.Fatalf("exec with user by id expected dockerio user got %s", out)
  452. }
  453. }