commands_test.go 16 KB

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