commands_test.go 14 KB

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