commands_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. package docker
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "strings"
  8. "testing"
  9. "time"
  10. log "github.com/Sirupsen/logrus"
  11. "github.com/docker/docker/api/client"
  12. "github.com/docker/docker/daemon"
  13. "github.com/docker/docker/pkg/term"
  14. "github.com/docker/docker/utils"
  15. "github.com/docker/libtrust"
  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].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. key, err := libtrust.GenerateECP256PrivateKey()
  107. if err != nil {
  108. t.Fatal(err)
  109. }
  110. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  111. defer cleanup(globalEngine, t)
  112. c1 := make(chan struct{})
  113. go func() {
  114. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  115. // fact that CmdRun returns.
  116. cli.CmdRun("-i", unitTestImageID, "/bin/cat")
  117. close(c1)
  118. }()
  119. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  120. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  121. t.Fatal(err)
  122. }
  123. })
  124. // Close pipes (simulate disconnect)
  125. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  126. t.Fatal(err)
  127. }
  128. // as the pipes are close, we expect the process to die,
  129. // therefore CmdRun to unblock. Wait for CmdRun
  130. setTimeout(t, "Waiting for CmdRun timed out", 2*time.Second, func() {
  131. <-c1
  132. })
  133. // Client disconnect after run -i should cause stdin to be closed, which should
  134. // cause /bin/cat to exit.
  135. setTimeout(t, "Waiting for /bin/cat to exit timed out", 2*time.Second, func() {
  136. container := globalDaemon.List()[0]
  137. container.WaitStop(-1 * time.Second)
  138. if container.IsRunning() {
  139. t.Fatalf("/bin/cat is still running after closing stdin")
  140. }
  141. })
  142. }
  143. // Expected behaviour: the process stay alive when the client disconnects
  144. // but the client detaches.
  145. func TestRunDisconnectTty(t *testing.T) {
  146. stdin, stdinPipe := io.Pipe()
  147. stdout, stdoutPipe := io.Pipe()
  148. key, err := libtrust.GenerateECP256PrivateKey()
  149. if err != nil {
  150. t.Fatal(err)
  151. }
  152. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  153. defer cleanup(globalEngine, t)
  154. c1 := make(chan struct{})
  155. go func() {
  156. defer close(c1)
  157. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  158. // fact that CmdRun returns.
  159. if err := cli.CmdRun("-i", "-t", unitTestImageID, "/bin/cat"); err != nil {
  160. log.Debugf("Error CmdRun: %s", err)
  161. }
  162. }()
  163. container := waitContainerStart(t, 10*time.Second)
  164. state := setRaw(t, container)
  165. defer unsetRaw(t, container, state)
  166. // Client disconnect after run -i should keep stdin out in TTY mode
  167. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  168. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  169. t.Fatal(err)
  170. }
  171. })
  172. // Close pipes (simulate disconnect)
  173. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  174. t.Fatal(err)
  175. }
  176. // wait for CmdRun to return
  177. setTimeout(t, "Waiting for CmdRun timed out", 5*time.Second, func() {
  178. <-c1
  179. })
  180. // In tty mode, we expect the process to stay alive even after client's stdin closes.
  181. // Give some time to monitor to do his thing
  182. container.WaitStop(500 * time.Millisecond)
  183. if !container.IsRunning() {
  184. t.Fatalf("/bin/cat should still be running after closing stdin (tty mode)")
  185. }
  186. }
  187. // TestRunDetach checks attaching and detaching with the escape sequence.
  188. func TestRunDetach(t *testing.T) {
  189. stdin, stdinPipe := io.Pipe()
  190. stdout, stdoutPipe := io.Pipe()
  191. key, err := libtrust.GenerateECP256PrivateKey()
  192. if err != nil {
  193. t.Fatal(err)
  194. }
  195. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  196. defer cleanup(globalEngine, t)
  197. ch := make(chan struct{})
  198. go func() {
  199. defer close(ch)
  200. cli.CmdRun("-i", "-t", unitTestImageID, "cat")
  201. }()
  202. container := waitContainerStart(t, 10*time.Second)
  203. state := setRaw(t, container)
  204. defer unsetRaw(t, container, state)
  205. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  206. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  207. t.Fatal(err)
  208. }
  209. })
  210. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  211. stdinPipe.Write([]byte{16})
  212. time.Sleep(100 * time.Millisecond)
  213. stdinPipe.Write([]byte{17})
  214. })
  215. // wait for CmdRun to return
  216. setTimeout(t, "Waiting for CmdRun timed out", 15*time.Second, func() {
  217. <-ch
  218. })
  219. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  220. time.Sleep(500 * time.Millisecond)
  221. if !container.IsRunning() {
  222. t.Fatal("The detached container should be still running")
  223. }
  224. setTimeout(t, "Waiting for container to die timed out", 20*time.Second, func() {
  225. container.Kill()
  226. })
  227. }
  228. // TestAttachDetach checks that attach in tty mode can be detached using the long container ID
  229. func TestAttachDetach(t *testing.T) {
  230. stdin, stdinPipe := io.Pipe()
  231. stdout, stdoutPipe := io.Pipe()
  232. key, err := libtrust.GenerateECP256PrivateKey()
  233. if err != nil {
  234. t.Fatal(err)
  235. }
  236. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  237. defer cleanup(globalEngine, t)
  238. ch := make(chan struct{})
  239. go func() {
  240. defer close(ch)
  241. if err := cli.CmdRun("-i", "-t", "-d", unitTestImageID, "cat"); err != nil {
  242. t.Fatal(err)
  243. }
  244. }()
  245. container := waitContainerStart(t, 10*time.Second)
  246. setTimeout(t, "Reading container's id timed out", 10*time.Second, func() {
  247. buf := make([]byte, 1024)
  248. n, err := stdout.Read(buf)
  249. if err != nil {
  250. t.Fatal(err)
  251. }
  252. if strings.Trim(string(buf[:n]), " \r\n") != container.ID {
  253. t.Fatalf("Wrong ID received. Expect %s, received %s", container.ID, buf[:n])
  254. }
  255. })
  256. setTimeout(t, "Starting container timed out", 10*time.Second, func() {
  257. <-ch
  258. })
  259. state := setRaw(t, container)
  260. defer unsetRaw(t, container, state)
  261. stdin, stdinPipe = io.Pipe()
  262. stdout, stdoutPipe = io.Pipe()
  263. cli = client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  264. ch = make(chan struct{})
  265. go func() {
  266. defer close(ch)
  267. if err := cli.CmdAttach(container.ID); err != nil {
  268. if err != io.ErrClosedPipe {
  269. t.Fatal(err)
  270. }
  271. }
  272. }()
  273. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  274. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  275. if err != io.ErrClosedPipe {
  276. t.Fatal(err)
  277. }
  278. }
  279. })
  280. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  281. stdinPipe.Write([]byte{16})
  282. time.Sleep(100 * time.Millisecond)
  283. stdinPipe.Write([]byte{17})
  284. })
  285. // wait for CmdRun to return
  286. setTimeout(t, "Waiting for CmdAttach timed out", 15*time.Second, func() {
  287. <-ch
  288. })
  289. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  290. time.Sleep(500 * time.Millisecond)
  291. if !container.IsRunning() {
  292. t.Fatal("The detached container should be still running")
  293. }
  294. setTimeout(t, "Waiting for container to die timedout", 5*time.Second, func() {
  295. container.Kill()
  296. })
  297. }
  298. // TestAttachDetachTruncatedID checks that attach in tty mode can be detached
  299. func TestAttachDetachTruncatedID(t *testing.T) {
  300. stdin, stdinPipe := io.Pipe()
  301. stdout, stdoutPipe := io.Pipe()
  302. key, err := libtrust.GenerateECP256PrivateKey()
  303. if err != nil {
  304. t.Fatal(err)
  305. }
  306. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  307. defer cleanup(globalEngine, t)
  308. // Discard the CmdRun output
  309. go stdout.Read(make([]byte, 1024))
  310. setTimeout(t, "Starting container timed out", 2*time.Second, func() {
  311. if err := cli.CmdRun("-i", "-t", "-d", unitTestImageID, "cat"); err != nil {
  312. t.Fatal(err)
  313. }
  314. })
  315. container := waitContainerStart(t, 10*time.Second)
  316. state := setRaw(t, container)
  317. defer unsetRaw(t, container, state)
  318. stdin, stdinPipe = io.Pipe()
  319. stdout, stdoutPipe = io.Pipe()
  320. cli = client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  321. ch := make(chan struct{})
  322. go func() {
  323. defer close(ch)
  324. if err := cli.CmdAttach(utils.TruncateID(container.ID)); err != nil {
  325. if err != io.ErrClosedPipe {
  326. t.Fatal(err)
  327. }
  328. }
  329. }()
  330. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  331. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  332. if err != io.ErrClosedPipe {
  333. t.Fatal(err)
  334. }
  335. }
  336. })
  337. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  338. stdinPipe.Write([]byte{16})
  339. time.Sleep(100 * time.Millisecond)
  340. stdinPipe.Write([]byte{17})
  341. })
  342. // wait for CmdRun to return
  343. setTimeout(t, "Waiting for CmdAttach timed out", 15*time.Second, func() {
  344. <-ch
  345. })
  346. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  347. time.Sleep(500 * time.Millisecond)
  348. if !container.IsRunning() {
  349. t.Fatal("The detached container should be still running")
  350. }
  351. setTimeout(t, "Waiting for container to die timedout", 5*time.Second, func() {
  352. container.Kill()
  353. })
  354. }
  355. // Expected behaviour, the process stays alive when the client disconnects
  356. func TestAttachDisconnect(t *testing.T) {
  357. stdin, stdinPipe := io.Pipe()
  358. stdout, stdoutPipe := io.Pipe()
  359. key, err := libtrust.GenerateECP256PrivateKey()
  360. if err != nil {
  361. t.Fatal(err)
  362. }
  363. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  364. defer cleanup(globalEngine, t)
  365. go func() {
  366. // Start a process in daemon mode
  367. if err := cli.CmdRun("-d", "-i", unitTestImageID, "/bin/cat"); err != nil {
  368. log.Debugf("Error CmdRun: %s", err)
  369. }
  370. }()
  371. setTimeout(t, "Waiting for CmdRun timed out", 10*time.Second, func() {
  372. if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil {
  373. t.Fatal(err)
  374. }
  375. })
  376. setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() {
  377. for {
  378. l := globalDaemon.List()
  379. if len(l) == 1 && l[0].IsRunning() {
  380. break
  381. }
  382. time.Sleep(10 * time.Millisecond)
  383. }
  384. })
  385. container := globalDaemon.List()[0]
  386. // Attach to it
  387. c1 := make(chan struct{})
  388. go func() {
  389. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  390. // fact that CmdAttach returns.
  391. cli.CmdAttach(container.ID)
  392. close(c1)
  393. }()
  394. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  395. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  396. t.Fatal(err)
  397. }
  398. })
  399. // Close pipes (client disconnects)
  400. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  401. t.Fatal(err)
  402. }
  403. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  404. setTimeout(t, "Waiting for CmdAttach timed out", 2*time.Second, func() {
  405. <-c1
  406. })
  407. // We closed stdin, expect /bin/cat to still be running
  408. // Wait a little bit to make sure container.monitor() did his thing
  409. _, err = container.WaitStop(500 * time.Millisecond)
  410. if err == nil || !container.IsRunning() {
  411. t.Fatalf("/bin/cat is not running after closing stdin")
  412. }
  413. // Try to avoid the timeout in destroy. Best effort, don't check error
  414. cStdin, _ := container.StdinPipe()
  415. cStdin.Close()
  416. container.WaitStop(-1 * time.Second)
  417. }
  418. // Expected behaviour: container gets deleted automatically after exit
  419. func TestRunAutoRemove(t *testing.T) {
  420. t.Skip("Fixme. Skipping test for now, race condition")
  421. stdout, stdoutPipe := io.Pipe()
  422. key, err := libtrust.GenerateECP256PrivateKey()
  423. if err != nil {
  424. t.Fatal(err)
  425. }
  426. cli := client.NewDockerCli(nil, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  427. defer cleanup(globalEngine, t)
  428. c := make(chan struct{})
  429. go func() {
  430. defer close(c)
  431. if err := cli.CmdRun("--rm", unitTestImageID, "hostname"); err != nil {
  432. t.Fatal(err)
  433. }
  434. }()
  435. var temporaryContainerID string
  436. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  437. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  438. if err != nil {
  439. t.Fatal(err)
  440. }
  441. temporaryContainerID = cmdOutput
  442. if err := closeWrap(stdout, stdoutPipe); err != nil {
  443. t.Fatal(err)
  444. }
  445. })
  446. setTimeout(t, "CmdRun timed out", 10*time.Second, func() {
  447. <-c
  448. })
  449. time.Sleep(500 * time.Millisecond)
  450. if len(globalDaemon.List()) > 0 {
  451. t.Fatalf("failed to remove container automatically: container %s still exists", temporaryContainerID)
  452. }
  453. }
  454. // Expected behaviour: error out when attempting to bind mount non-existing source paths
  455. func TestRunErrorBindNonExistingSource(t *testing.T) {
  456. key, err := libtrust.GenerateECP256PrivateKey()
  457. if err != nil {
  458. t.Fatal(err)
  459. }
  460. cli := client.NewDockerCli(nil, nil, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  461. defer cleanup(globalEngine, t)
  462. c := make(chan struct{})
  463. go func() {
  464. defer close(c)
  465. // This check is made at runtime, can't be "unit tested"
  466. if err := cli.CmdRun("-v", "/i/dont/exist:/tmp", unitTestImageID, "echo 'should fail'"); err == nil {
  467. t.Fatal("should have failed to run when using /i/dont/exist as a source for the bind mount")
  468. }
  469. }()
  470. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  471. <-c
  472. })
  473. }