commands_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. "github.com/kr/pty"
  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].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. key, err := libtrust.GenerateECP256PrivateKey()
  108. if err != nil {
  109. t.Fatal(err)
  110. }
  111. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  112. defer cleanup(globalEngine, t)
  113. c1 := make(chan struct{})
  114. go func() {
  115. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  116. // fact that CmdRun returns.
  117. cli.CmdRun("-i", unitTestImageID, "/bin/cat")
  118. close(c1)
  119. }()
  120. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  121. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  122. t.Fatal(err)
  123. }
  124. })
  125. // Close pipes (simulate disconnect)
  126. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  127. t.Fatal(err)
  128. }
  129. // as the pipes are close, we expect the process to die,
  130. // therefore CmdRun to unblock. Wait for CmdRun
  131. setTimeout(t, "Waiting for CmdRun timed out", 2*time.Second, func() {
  132. <-c1
  133. })
  134. // Client disconnect after run -i should cause stdin to be closed, which should
  135. // cause /bin/cat to exit.
  136. setTimeout(t, "Waiting for /bin/cat to exit timed out", 2*time.Second, func() {
  137. container := globalDaemon.List()[0]
  138. container.WaitStop(-1 * time.Second)
  139. if container.IsRunning() {
  140. t.Fatalf("/bin/cat is still running after closing stdin")
  141. }
  142. })
  143. }
  144. // TestRunDetach checks attaching and detaching with the escape sequence.
  145. func TestRunDetach(t *testing.T) {
  146. stdout, stdoutPipe := io.Pipe()
  147. cpty, tty, err := pty.Open()
  148. if err != nil {
  149. t.Fatal(err)
  150. }
  151. key, err := libtrust.GenerateECP256PrivateKey()
  152. if err != nil {
  153. t.Fatal(err)
  154. }
  155. cli := client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  156. defer cleanup(globalEngine, t)
  157. ch := make(chan struct{})
  158. go func() {
  159. defer close(ch)
  160. cli.CmdRun("-i", "-t", unitTestImageID, "cat")
  161. }()
  162. container := waitContainerStart(t, 10*time.Second)
  163. state := setRaw(t, container)
  164. defer unsetRaw(t, container, state)
  165. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  166. if err := assertPipe("hello\n", "hello", stdout, cpty, 150); err != nil {
  167. t.Fatal(err)
  168. }
  169. })
  170. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  171. cpty.Write([]byte{16})
  172. time.Sleep(100 * time.Millisecond)
  173. cpty.Write([]byte{17})
  174. })
  175. // wait for CmdRun to return
  176. setTimeout(t, "Waiting for CmdRun timed out", 15*time.Second, func() {
  177. <-ch
  178. })
  179. closeWrap(cpty, stdout, stdoutPipe)
  180. time.Sleep(500 * time.Millisecond)
  181. if !container.IsRunning() {
  182. t.Fatal("The detached container should be still running")
  183. }
  184. setTimeout(t, "Waiting for container to die timed out", 20*time.Second, func() {
  185. container.Kill()
  186. })
  187. }
  188. // TestAttachDetach checks that attach in tty mode can be detached using the long container ID
  189. func TestAttachDetach(t *testing.T) {
  190. stdout, stdoutPipe := io.Pipe()
  191. cpty, tty, err := pty.Open()
  192. if err != nil {
  193. t.Fatal(err)
  194. }
  195. key, err := libtrust.GenerateECP256PrivateKey()
  196. if err != nil {
  197. t.Fatal(err)
  198. }
  199. cli := client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  200. defer cleanup(globalEngine, t)
  201. ch := make(chan struct{})
  202. go func() {
  203. defer close(ch)
  204. if err := cli.CmdRun("-i", "-t", "-d", unitTestImageID, "cat"); err != nil {
  205. t.Fatal(err)
  206. }
  207. }()
  208. container := waitContainerStart(t, 10*time.Second)
  209. setTimeout(t, "Reading container's id timed out", 10*time.Second, func() {
  210. buf := make([]byte, 1024)
  211. n, err := stdout.Read(buf)
  212. if err != nil {
  213. t.Fatal(err)
  214. }
  215. if strings.Trim(string(buf[:n]), " \r\n") != container.ID {
  216. t.Fatalf("Wrong ID received. Expect %s, received %s", container.ID, buf[:n])
  217. }
  218. })
  219. setTimeout(t, "Starting container timed out", 10*time.Second, func() {
  220. <-ch
  221. })
  222. state := setRaw(t, container)
  223. defer unsetRaw(t, container, state)
  224. stdout, stdoutPipe = io.Pipe()
  225. cpty, tty, err = pty.Open()
  226. if err != nil {
  227. t.Fatal(err)
  228. }
  229. cli = client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  230. ch = make(chan struct{})
  231. go func() {
  232. defer close(ch)
  233. if err := cli.CmdAttach(container.ID); err != nil {
  234. if err != io.ErrClosedPipe {
  235. t.Fatal(err)
  236. }
  237. }
  238. }()
  239. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  240. if err := assertPipe("hello\n", "hello", stdout, cpty, 150); err != nil {
  241. if err != io.ErrClosedPipe {
  242. t.Fatal(err)
  243. }
  244. }
  245. })
  246. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  247. cpty.Write([]byte{16})
  248. time.Sleep(100 * time.Millisecond)
  249. cpty.Write([]byte{17})
  250. })
  251. // wait for CmdRun to return
  252. setTimeout(t, "Waiting for CmdAttach timed out", 15*time.Second, func() {
  253. <-ch
  254. })
  255. closeWrap(cpty, stdout, stdoutPipe)
  256. time.Sleep(500 * time.Millisecond)
  257. if !container.IsRunning() {
  258. t.Fatal("The detached container should be still running")
  259. }
  260. setTimeout(t, "Waiting for container to die timedout", 5*time.Second, func() {
  261. container.Kill()
  262. })
  263. }
  264. // TestAttachDetachTruncatedID checks that attach in tty mode can be detached
  265. func TestAttachDetachTruncatedID(t *testing.T) {
  266. stdout, stdoutPipe := io.Pipe()
  267. cpty, tty, err := pty.Open()
  268. if err != nil {
  269. t.Fatal(err)
  270. }
  271. key, err := libtrust.GenerateECP256PrivateKey()
  272. if err != nil {
  273. t.Fatal(err)
  274. }
  275. cli := client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  276. defer cleanup(globalEngine, t)
  277. // Discard the CmdRun output
  278. go stdout.Read(make([]byte, 1024))
  279. setTimeout(t, "Starting container timed out", 2*time.Second, func() {
  280. if err := cli.CmdRun("-i", "-t", "-d", unitTestImageID, "cat"); err != nil {
  281. t.Fatal(err)
  282. }
  283. })
  284. container := waitContainerStart(t, 10*time.Second)
  285. state := setRaw(t, container)
  286. defer unsetRaw(t, container, state)
  287. stdout, stdoutPipe = io.Pipe()
  288. cpty, tty, err = pty.Open()
  289. if err != nil {
  290. t.Fatal(err)
  291. }
  292. cli = client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  293. ch := make(chan struct{})
  294. go func() {
  295. defer close(ch)
  296. if err := cli.CmdAttach(utils.TruncateID(container.ID)); err != nil {
  297. if err != io.ErrClosedPipe {
  298. t.Fatal(err)
  299. }
  300. }
  301. }()
  302. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  303. if err := assertPipe("hello\n", "hello", stdout, cpty, 150); err != nil {
  304. if err != io.ErrClosedPipe {
  305. t.Fatal(err)
  306. }
  307. }
  308. })
  309. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  310. cpty.Write([]byte{16})
  311. time.Sleep(100 * time.Millisecond)
  312. cpty.Write([]byte{17})
  313. })
  314. // wait for CmdRun to return
  315. setTimeout(t, "Waiting for CmdAttach timed out", 15*time.Second, func() {
  316. <-ch
  317. })
  318. closeWrap(cpty, stdout, stdoutPipe)
  319. time.Sleep(500 * time.Millisecond)
  320. if !container.IsRunning() {
  321. t.Fatal("The detached container should be still running")
  322. }
  323. setTimeout(t, "Waiting for container to die timedout", 5*time.Second, func() {
  324. container.Kill()
  325. })
  326. }
  327. // Expected behaviour, the process stays alive when the client disconnects
  328. func TestAttachDisconnect(t *testing.T) {
  329. stdout, stdoutPipe := io.Pipe()
  330. cpty, tty, err := pty.Open()
  331. if err != nil {
  332. t.Fatal(err)
  333. }
  334. key, err := libtrust.GenerateECP256PrivateKey()
  335. if err != nil {
  336. t.Fatal(err)
  337. }
  338. cli := client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, key, 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].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, cpty, 150); err != nil {
  371. t.Fatal(err)
  372. }
  373. })
  374. // Close pipes (client disconnects)
  375. if err := closeWrap(cpty, 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.WaitStop(500 * time.Millisecond)
  385. if err == nil || !container.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.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. key, err := libtrust.GenerateECP256PrivateKey()
  398. if err != nil {
  399. t.Fatal(err)
  400. }
  401. cli := client.NewDockerCli(nil, stdoutPipe, ioutil.Discard, key, testDaemonProto, testDaemonAddr, nil)
  402. defer cleanup(globalEngine, t)
  403. c := make(chan struct{})
  404. go func() {
  405. defer close(c)
  406. if err := cli.CmdRun("--rm", unitTestImageID, "hostname"); err != nil {
  407. t.Fatal(err)
  408. }
  409. }()
  410. var temporaryContainerID string
  411. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  412. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  413. if err != nil {
  414. t.Fatal(err)
  415. }
  416. temporaryContainerID = cmdOutput
  417. if err := closeWrap(stdout, stdoutPipe); err != nil {
  418. t.Fatal(err)
  419. }
  420. })
  421. setTimeout(t, "CmdRun timed out", 10*time.Second, func() {
  422. <-c
  423. })
  424. time.Sleep(500 * time.Millisecond)
  425. if len(globalDaemon.List()) > 0 {
  426. t.Fatalf("failed to remove container automatically: container %s still exists", temporaryContainerID)
  427. }
  428. }