commands_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. package docker
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "path"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/docker/docker/api/client"
  13. "github.com/docker/docker/daemon"
  14. "github.com/docker/docker/pkg/term"
  15. "github.com/docker/docker/utils"
  16. )
  17. func closeWrap(args ...io.Closer) error {
  18. e := false
  19. ret := fmt.Errorf("Error closing elements")
  20. for _, c := range args {
  21. if err := c.Close(); err != nil {
  22. e = true
  23. ret = fmt.Errorf("%s\n%s", ret, err)
  24. }
  25. }
  26. if e {
  27. return ret
  28. }
  29. return nil
  30. }
  31. func setRaw(t *testing.T, c *daemon.Container) *term.State {
  32. pty, err := c.GetPtyMaster()
  33. if err != nil {
  34. t.Fatal(err)
  35. }
  36. state, err := term.MakeRaw(pty.Fd())
  37. if err != nil {
  38. t.Fatal(err)
  39. }
  40. return state
  41. }
  42. func unsetRaw(t *testing.T, c *daemon.Container, state *term.State) {
  43. pty, err := c.GetPtyMaster()
  44. if err != nil {
  45. t.Fatal(err)
  46. }
  47. term.RestoreTerminal(pty.Fd(), state)
  48. }
  49. func waitContainerStart(t *testing.T, timeout time.Duration) *daemon.Container {
  50. var container *daemon.Container
  51. setTimeout(t, "Waiting for the container to be started timed out", timeout, func() {
  52. for {
  53. l := globalDaemon.List()
  54. if len(l) == 1 && l[0].State.IsRunning() {
  55. container = l[0]
  56. break
  57. }
  58. time.Sleep(10 * time.Millisecond)
  59. }
  60. })
  61. if container == nil {
  62. t.Fatal("An error occured while waiting for the container to start")
  63. }
  64. return container
  65. }
  66. func setTimeout(t *testing.T, msg string, d time.Duration, f func()) {
  67. c := make(chan bool)
  68. // Make sure we are not too long
  69. go func() {
  70. time.Sleep(d)
  71. c <- true
  72. }()
  73. go func() {
  74. f()
  75. c <- false
  76. }()
  77. if <-c && msg != "" {
  78. t.Fatal(msg)
  79. }
  80. }
  81. func expectPipe(expected string, r io.Reader) error {
  82. o, err := bufio.NewReader(r).ReadString('\n')
  83. if err != nil {
  84. return err
  85. }
  86. if strings.Trim(o, " \r\n") != expected {
  87. return fmt.Errorf("Unexpected output. Expected [%s], received [%s]", expected, o)
  88. }
  89. return nil
  90. }
  91. func assertPipe(input, output string, r io.Reader, w io.Writer, count int) error {
  92. for i := 0; i < count; i++ {
  93. if _, err := w.Write([]byte(input)); err != nil {
  94. return err
  95. }
  96. if err := expectPipe(output, r); err != nil {
  97. return err
  98. }
  99. }
  100. return nil
  101. }
  102. // Expected behaviour: the process dies when the client disconnects
  103. func TestRunDisconnect(t *testing.T) {
  104. stdin, stdinPipe := io.Pipe()
  105. stdout, stdoutPipe := io.Pipe()
  106. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  107. defer cleanup(globalEngine, t)
  108. c1 := make(chan struct{})
  109. go func() {
  110. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  111. // fact that CmdRun returns.
  112. cli.CmdRun("-i", unitTestImageID, "/bin/cat")
  113. close(c1)
  114. }()
  115. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  116. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  117. t.Fatal(err)
  118. }
  119. })
  120. // Close pipes (simulate disconnect)
  121. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  122. t.Fatal(err)
  123. }
  124. // as the pipes are close, we expect the process to die,
  125. // therefore CmdRun to unblock. Wait for CmdRun
  126. setTimeout(t, "Waiting for CmdRun timed out", 2*time.Second, func() {
  127. <-c1
  128. })
  129. // Client disconnect after run -i should cause stdin to be closed, which should
  130. // cause /bin/cat to exit.
  131. setTimeout(t, "Waiting for /bin/cat to exit timed out", 2*time.Second, func() {
  132. container := globalDaemon.List()[0]
  133. container.State.WaitStop(-1 * time.Second)
  134. if container.State.IsRunning() {
  135. t.Fatalf("/bin/cat is still running after closing stdin")
  136. }
  137. })
  138. }
  139. // Expected behaviour: the process stay alive when the client disconnects
  140. // but the client detaches.
  141. func TestRunDisconnectTty(t *testing.T) {
  142. stdin, stdinPipe := io.Pipe()
  143. stdout, stdoutPipe := io.Pipe()
  144. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  145. defer cleanup(globalEngine, t)
  146. c1 := make(chan struct{})
  147. go func() {
  148. defer close(c1)
  149. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  150. // fact that CmdRun returns.
  151. if err := cli.CmdRun("-i", "-t", unitTestImageID, "/bin/cat"); err != nil {
  152. utils.Debugf("Error CmdRun: %s", err)
  153. }
  154. }()
  155. container := waitContainerStart(t, 10*time.Second)
  156. state := setRaw(t, container)
  157. defer unsetRaw(t, container, state)
  158. // Client disconnect after run -i should keep stdin out in TTY mode
  159. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  160. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  161. t.Fatal(err)
  162. }
  163. })
  164. // Close pipes (simulate disconnect)
  165. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  166. t.Fatal(err)
  167. }
  168. // wait for CmdRun to return
  169. setTimeout(t, "Waiting for CmdRun timed out", 5*time.Second, func() {
  170. <-c1
  171. })
  172. // In tty mode, we expect the process to stay alive even after client's stdin closes.
  173. // Give some time to monitor to do his thing
  174. container.State.WaitStop(500 * time.Millisecond)
  175. if !container.State.IsRunning() {
  176. t.Fatalf("/bin/cat should still be running after closing stdin (tty mode)")
  177. }
  178. }
  179. // TestRunDetach checks attaching and detaching with the escape sequence.
  180. func TestRunDetach(t *testing.T) {
  181. stdin, stdinPipe := io.Pipe()
  182. stdout, stdoutPipe := io.Pipe()
  183. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  184. defer cleanup(globalEngine, t)
  185. ch := make(chan struct{})
  186. go func() {
  187. defer close(ch)
  188. cli.CmdRun("-i", "-t", unitTestImageID, "cat")
  189. }()
  190. container := waitContainerStart(t, 10*time.Second)
  191. state := setRaw(t, container)
  192. defer unsetRaw(t, container, state)
  193. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  194. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  195. t.Fatal(err)
  196. }
  197. })
  198. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  199. stdinPipe.Write([]byte{16})
  200. time.Sleep(100 * time.Millisecond)
  201. stdinPipe.Write([]byte{17})
  202. })
  203. // wait for CmdRun to return
  204. setTimeout(t, "Waiting for CmdRun timed out", 15*time.Second, func() {
  205. <-ch
  206. })
  207. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  208. time.Sleep(500 * time.Millisecond)
  209. if !container.State.IsRunning() {
  210. t.Fatal("The detached container should be still running")
  211. }
  212. setTimeout(t, "Waiting for container to die timed out", 20*time.Second, func() {
  213. container.Kill()
  214. })
  215. }
  216. // TestAttachDetach checks that attach in tty mode can be detached using the long container ID
  217. func TestAttachDetach(t *testing.T) {
  218. stdin, stdinPipe := io.Pipe()
  219. stdout, stdoutPipe := io.Pipe()
  220. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  221. defer cleanup(globalEngine, t)
  222. ch := make(chan struct{})
  223. go func() {
  224. defer close(ch)
  225. if err := cli.CmdRun("-i", "-t", "-d", unitTestImageID, "cat"); err != nil {
  226. t.Fatal(err)
  227. }
  228. }()
  229. container := waitContainerStart(t, 10*time.Second)
  230. setTimeout(t, "Reading container's id timed out", 10*time.Second, func() {
  231. buf := make([]byte, 1024)
  232. n, err := stdout.Read(buf)
  233. if err != nil {
  234. t.Fatal(err)
  235. }
  236. if strings.Trim(string(buf[:n]), " \r\n") != container.ID {
  237. t.Fatalf("Wrong ID received. Expect %s, received %s", container.ID, buf[:n])
  238. }
  239. })
  240. setTimeout(t, "Starting container timed out", 10*time.Second, func() {
  241. <-ch
  242. })
  243. state := setRaw(t, container)
  244. defer unsetRaw(t, container, state)
  245. stdin, stdinPipe = io.Pipe()
  246. stdout, stdoutPipe = io.Pipe()
  247. cli = client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  248. ch = make(chan struct{})
  249. go func() {
  250. defer close(ch)
  251. if err := cli.CmdAttach(container.ID); err != nil {
  252. if err != io.ErrClosedPipe {
  253. t.Fatal(err)
  254. }
  255. }
  256. }()
  257. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  258. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  259. if err != io.ErrClosedPipe {
  260. t.Fatal(err)
  261. }
  262. }
  263. })
  264. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  265. stdinPipe.Write([]byte{16})
  266. time.Sleep(100 * time.Millisecond)
  267. stdinPipe.Write([]byte{17})
  268. })
  269. // wait for CmdRun to return
  270. setTimeout(t, "Waiting for CmdAttach timed out", 15*time.Second, func() {
  271. <-ch
  272. })
  273. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  274. time.Sleep(500 * time.Millisecond)
  275. if !container.State.IsRunning() {
  276. t.Fatal("The detached container should be still running")
  277. }
  278. setTimeout(t, "Waiting for container to die timedout", 5*time.Second, func() {
  279. container.Kill()
  280. })
  281. }
  282. // TestAttachDetachTruncatedID checks that attach in tty mode can be detached
  283. func TestAttachDetachTruncatedID(t *testing.T) {
  284. stdin, stdinPipe := io.Pipe()
  285. stdout, stdoutPipe := io.Pipe()
  286. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  287. defer cleanup(globalEngine, t)
  288. // Discard the CmdRun output
  289. go stdout.Read(make([]byte, 1024))
  290. setTimeout(t, "Starting container timed out", 2*time.Second, func() {
  291. if err := cli.CmdRun("-i", "-t", "-d", unitTestImageID, "cat"); err != nil {
  292. t.Fatal(err)
  293. }
  294. })
  295. container := waitContainerStart(t, 10*time.Second)
  296. state := setRaw(t, container)
  297. defer unsetRaw(t, container, state)
  298. stdin, stdinPipe = io.Pipe()
  299. stdout, stdoutPipe = io.Pipe()
  300. cli = client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  301. ch := make(chan struct{})
  302. go func() {
  303. defer close(ch)
  304. if err := cli.CmdAttach(utils.TruncateID(container.ID)); err != nil {
  305. if err != io.ErrClosedPipe {
  306. t.Fatal(err)
  307. }
  308. }
  309. }()
  310. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  311. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  312. if err != io.ErrClosedPipe {
  313. t.Fatal(err)
  314. }
  315. }
  316. })
  317. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  318. stdinPipe.Write([]byte{16})
  319. time.Sleep(100 * time.Millisecond)
  320. stdinPipe.Write([]byte{17})
  321. })
  322. // wait for CmdRun to return
  323. setTimeout(t, "Waiting for CmdAttach timed out", 15*time.Second, func() {
  324. <-ch
  325. })
  326. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  327. time.Sleep(500 * time.Millisecond)
  328. if !container.State.IsRunning() {
  329. t.Fatal("The detached container should be still running")
  330. }
  331. setTimeout(t, "Waiting for container to die timedout", 5*time.Second, func() {
  332. container.Kill()
  333. })
  334. }
  335. // Expected behaviour, the process stays alive when the client disconnects
  336. func TestAttachDisconnect(t *testing.T) {
  337. stdin, stdinPipe := io.Pipe()
  338. stdout, stdoutPipe := io.Pipe()
  339. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  340. defer cleanup(globalEngine, t)
  341. go func() {
  342. // Start a process in daemon mode
  343. if err := cli.CmdRun("-d", "-i", unitTestImageID, "/bin/cat"); err != nil {
  344. utils.Debugf("Error CmdRun: %s", err)
  345. }
  346. }()
  347. setTimeout(t, "Waiting for CmdRun timed out", 10*time.Second, func() {
  348. if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil {
  349. t.Fatal(err)
  350. }
  351. })
  352. setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() {
  353. for {
  354. l := globalDaemon.List()
  355. if len(l) == 1 && l[0].State.IsRunning() {
  356. break
  357. }
  358. time.Sleep(10 * time.Millisecond)
  359. }
  360. })
  361. container := globalDaemon.List()[0]
  362. // Attach to it
  363. c1 := make(chan struct{})
  364. go func() {
  365. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  366. // fact that CmdAttach returns.
  367. cli.CmdAttach(container.ID)
  368. close(c1)
  369. }()
  370. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  371. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  372. t.Fatal(err)
  373. }
  374. })
  375. // Close pipes (client disconnects)
  376. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  377. t.Fatal(err)
  378. }
  379. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  380. setTimeout(t, "Waiting for CmdAttach timed out", 2*time.Second, func() {
  381. <-c1
  382. })
  383. // We closed stdin, expect /bin/cat to still be running
  384. // Wait a little bit to make sure container.monitor() did his thing
  385. _, err := container.State.WaitStop(500 * time.Millisecond)
  386. if err == nil || !container.State.IsRunning() {
  387. t.Fatalf("/bin/cat is not running after closing stdin")
  388. }
  389. // Try to avoid the timeout in destroy. Best effort, don't check error
  390. cStdin, _ := container.StdinPipe()
  391. cStdin.Close()
  392. container.State.WaitStop(-1 * time.Second)
  393. }
  394. // Expected behaviour: container gets deleted automatically after exit
  395. func TestRunAutoRemove(t *testing.T) {
  396. t.Skip("Fixme. Skipping test for now, race condition")
  397. stdout, stdoutPipe := io.Pipe()
  398. cli := client.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  399. defer cleanup(globalEngine, t)
  400. c := make(chan struct{})
  401. go func() {
  402. defer close(c)
  403. if err := cli.CmdRun("--rm", unitTestImageID, "hostname"); err != nil {
  404. t.Fatal(err)
  405. }
  406. }()
  407. var temporaryContainerID string
  408. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  409. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  410. if err != nil {
  411. t.Fatal(err)
  412. }
  413. temporaryContainerID = cmdOutput
  414. if err := closeWrap(stdout, stdoutPipe); err != nil {
  415. t.Fatal(err)
  416. }
  417. })
  418. setTimeout(t, "CmdRun timed out", 10*time.Second, func() {
  419. <-c
  420. })
  421. time.Sleep(500 * time.Millisecond)
  422. if len(globalDaemon.List()) > 0 {
  423. t.Fatalf("failed to remove container automatically: container %s still exists", temporaryContainerID)
  424. }
  425. }
  426. // Expected behaviour: error out when attempting to bind mount non-existing source paths
  427. func TestRunErrorBindNonExistingSource(t *testing.T) {
  428. cli := client.NewDockerCli(nil, nil, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  429. defer cleanup(globalEngine, t)
  430. c := make(chan struct{})
  431. go func() {
  432. defer close(c)
  433. // This check is made at runtime, can't be "unit tested"
  434. if err := cli.CmdRun("-v", "/i/dont/exist:/tmp", unitTestImageID, "echo 'should fail'"); err == nil {
  435. t.Fatal("should have failed to run when using /i/dont/exist as a source for the bind mount")
  436. }
  437. }()
  438. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  439. <-c
  440. })
  441. }
  442. // #2098 - Docker cidFiles only contain short version of the containerId
  443. //sudo docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"
  444. // TestRunCidFile tests that run --cidfile returns the longid
  445. func TestRunCidFileCheckIDLength(t *testing.T) {
  446. stdout, stdoutPipe := io.Pipe()
  447. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  448. if err != nil {
  449. t.Fatal(err)
  450. }
  451. tmpCidFile := path.Join(tmpDir, "cid")
  452. cli := client.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  453. defer cleanup(globalEngine, t)
  454. c := make(chan struct{})
  455. go func() {
  456. defer close(c)
  457. if err := cli.CmdRun("--cidfile", tmpCidFile, unitTestImageID, "ls"); err != nil {
  458. t.Fatal(err)
  459. }
  460. }()
  461. defer os.RemoveAll(tmpDir)
  462. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  463. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  464. if err != nil {
  465. t.Fatal(err)
  466. }
  467. if len(cmdOutput) < 1 {
  468. t.Fatalf("'ls' should return something , not '%s'", cmdOutput)
  469. }
  470. //read the tmpCidFile
  471. buffer, err := ioutil.ReadFile(tmpCidFile)
  472. if err != nil {
  473. t.Fatal(err)
  474. }
  475. id := string(buffer)
  476. if len(id) != len("2bf44ea18873287bd9ace8a4cb536a7cbe134bed67e805fdf2f58a57f69b320c") {
  477. t.Fatalf("--cidfile should be a long id, not '%s'", id)
  478. }
  479. //test that its a valid cid? (though the container is gone..)
  480. //remove the file and dir.
  481. })
  482. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  483. <-c
  484. })
  485. }
  486. // Ensure that CIDFile gets deleted if it's empty
  487. // Perform this test by making `docker run` fail
  488. func TestRunCidFileCleanupIfEmpty(t *testing.T) {
  489. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  490. if err != nil {
  491. t.Fatal(err)
  492. }
  493. tmpCidFile := path.Join(tmpDir, "cid")
  494. cli := client.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  495. defer cleanup(globalEngine, t)
  496. c := make(chan struct{})
  497. go func() {
  498. defer close(c)
  499. if err := cli.CmdRun("--cidfile", tmpCidFile, unitTestImageID); err == nil {
  500. t.Fatal("running without a command should haveve failed")
  501. }
  502. if _, err := os.Stat(tmpCidFile); err == nil {
  503. t.Fatalf("empty CIDFile '%s' should've been deleted", tmpCidFile)
  504. }
  505. }()
  506. defer os.RemoveAll(tmpDir)
  507. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  508. <-c
  509. })
  510. }