commands_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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/stringid"
  14. "github.com/docker/docker/pkg/term"
  15. "github.com/kr/pty"
  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. // TestRunDetach checks attaching and detaching with the escape sequence.
  103. func TestRunDetach(t *testing.T) {
  104. stdout, stdoutPipe := io.Pipe()
  105. cpty, tty, err := pty.Open()
  106. if err != nil {
  107. t.Fatal(err)
  108. }
  109. cli := client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, "", testDaemonProto, testDaemonAddr, nil)
  110. defer cleanup(globalEngine, t)
  111. ch := make(chan struct{})
  112. go func() {
  113. defer close(ch)
  114. cli.CmdRun("-i", "-t", unitTestImageID, "cat")
  115. }()
  116. container := waitContainerStart(t, 10*time.Second)
  117. state := setRaw(t, container)
  118. defer unsetRaw(t, container, state)
  119. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  120. if err := assertPipe("hello\n", "hello", stdout, cpty, 150); err != nil {
  121. t.Fatal(err)
  122. }
  123. })
  124. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  125. cpty.Write([]byte{16})
  126. time.Sleep(100 * time.Millisecond)
  127. cpty.Write([]byte{17})
  128. })
  129. // wait for CmdRun to return
  130. setTimeout(t, "Waiting for CmdRun timed out", 15*time.Second, func() {
  131. <-ch
  132. })
  133. closeWrap(cpty, stdout, stdoutPipe)
  134. time.Sleep(500 * time.Millisecond)
  135. if !container.IsRunning() {
  136. t.Fatal("The detached container should be still running")
  137. }
  138. setTimeout(t, "Waiting for container to die timed out", 20*time.Second, func() {
  139. container.Kill()
  140. })
  141. }
  142. // TestAttachDetach checks that attach in tty mode can be detached using the long container ID
  143. func TestAttachDetach(t *testing.T) {
  144. stdout, stdoutPipe := io.Pipe()
  145. cpty, tty, err := pty.Open()
  146. if err != nil {
  147. t.Fatal(err)
  148. }
  149. cli := client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, "", testDaemonProto, testDaemonAddr, nil)
  150. defer cleanup(globalEngine, t)
  151. ch := make(chan struct{})
  152. go func() {
  153. defer close(ch)
  154. if err := cli.CmdRun("-i", "-t", "-d", unitTestImageID, "cat"); err != nil {
  155. t.Fatal(err)
  156. }
  157. }()
  158. container := waitContainerStart(t, 10*time.Second)
  159. setTimeout(t, "Reading container's id timed out", 10*time.Second, func() {
  160. buf := make([]byte, 1024)
  161. n, err := stdout.Read(buf)
  162. if err != nil {
  163. t.Fatal(err)
  164. }
  165. if strings.Trim(string(buf[:n]), " \r\n") != container.ID {
  166. t.Fatalf("Wrong ID received. Expect %s, received %s", container.ID, buf[:n])
  167. }
  168. })
  169. setTimeout(t, "Starting container timed out", 10*time.Second, func() {
  170. <-ch
  171. })
  172. state := setRaw(t, container)
  173. defer unsetRaw(t, container, state)
  174. stdout, stdoutPipe = io.Pipe()
  175. cpty, tty, err = pty.Open()
  176. if err != nil {
  177. t.Fatal(err)
  178. }
  179. cli = client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, "", testDaemonProto, testDaemonAddr, nil)
  180. ch = make(chan struct{})
  181. go func() {
  182. defer close(ch)
  183. if err := cli.CmdAttach(container.ID); err != nil {
  184. if err != io.ErrClosedPipe {
  185. t.Fatal(err)
  186. }
  187. }
  188. }()
  189. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  190. if err := assertPipe("hello\n", "hello", stdout, cpty, 150); err != nil {
  191. if err != io.ErrClosedPipe {
  192. t.Fatal(err)
  193. }
  194. }
  195. })
  196. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  197. cpty.Write([]byte{16})
  198. time.Sleep(100 * time.Millisecond)
  199. cpty.Write([]byte{17})
  200. })
  201. // wait for CmdRun to return
  202. setTimeout(t, "Waiting for CmdAttach timed out", 15*time.Second, func() {
  203. <-ch
  204. })
  205. closeWrap(cpty, stdout, stdoutPipe)
  206. time.Sleep(500 * time.Millisecond)
  207. if !container.IsRunning() {
  208. t.Fatal("The detached container should be still running")
  209. }
  210. setTimeout(t, "Waiting for container to die timedout", 5*time.Second, func() {
  211. container.Kill()
  212. })
  213. }
  214. // TestAttachDetachTruncatedID checks that attach in tty mode can be detached
  215. func TestAttachDetachTruncatedID(t *testing.T) {
  216. stdout, stdoutPipe := io.Pipe()
  217. cpty, tty, err := pty.Open()
  218. if err != nil {
  219. t.Fatal(err)
  220. }
  221. cli := client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, "", testDaemonProto, testDaemonAddr, nil)
  222. defer cleanup(globalEngine, t)
  223. // Discard the CmdRun output
  224. go stdout.Read(make([]byte, 1024))
  225. setTimeout(t, "Starting container timed out", 2*time.Second, func() {
  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. state := setRaw(t, container)
  232. defer unsetRaw(t, container, state)
  233. stdout, stdoutPipe = io.Pipe()
  234. cpty, tty, err = pty.Open()
  235. if err != nil {
  236. t.Fatal(err)
  237. }
  238. cli = client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, "", testDaemonProto, testDaemonAddr, nil)
  239. ch := make(chan struct{})
  240. go func() {
  241. defer close(ch)
  242. if err := cli.CmdAttach(stringid.TruncateID(container.ID)); err != nil {
  243. if err != io.ErrClosedPipe {
  244. t.Fatal(err)
  245. }
  246. }
  247. }()
  248. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  249. if err := assertPipe("hello\n", "hello", stdout, cpty, 150); err != nil {
  250. if err != io.ErrClosedPipe {
  251. t.Fatal(err)
  252. }
  253. }
  254. })
  255. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  256. cpty.Write([]byte{16})
  257. time.Sleep(100 * time.Millisecond)
  258. cpty.Write([]byte{17})
  259. })
  260. // wait for CmdRun to return
  261. setTimeout(t, "Waiting for CmdAttach timed out", 15*time.Second, func() {
  262. <-ch
  263. })
  264. closeWrap(cpty, stdout, stdoutPipe)
  265. time.Sleep(500 * time.Millisecond)
  266. if !container.IsRunning() {
  267. t.Fatal("The detached container should be still running")
  268. }
  269. setTimeout(t, "Waiting for container to die timedout", 5*time.Second, func() {
  270. container.Kill()
  271. })
  272. }
  273. // Expected behaviour, the process stays alive when the client disconnects
  274. func TestAttachDisconnect(t *testing.T) {
  275. stdout, stdoutPipe := io.Pipe()
  276. cpty, tty, err := pty.Open()
  277. if err != nil {
  278. t.Fatal(err)
  279. }
  280. cli := client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, "", testDaemonProto, testDaemonAddr, nil)
  281. defer cleanup(globalEngine, t)
  282. go func() {
  283. // Start a process in daemon mode
  284. if err := cli.CmdRun("-d", "-i", unitTestImageID, "/bin/cat"); err != nil {
  285. log.Debugf("Error CmdRun: %s", err)
  286. }
  287. }()
  288. setTimeout(t, "Waiting for CmdRun timed out", 10*time.Second, func() {
  289. if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil {
  290. t.Fatal(err)
  291. }
  292. })
  293. setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() {
  294. for {
  295. l := globalDaemon.List()
  296. if len(l) == 1 && l[0].IsRunning() {
  297. break
  298. }
  299. time.Sleep(10 * time.Millisecond)
  300. }
  301. })
  302. container := globalDaemon.List()[0]
  303. // Attach to it
  304. c1 := make(chan struct{})
  305. go func() {
  306. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  307. // fact that CmdAttach returns.
  308. cli.CmdAttach(container.ID)
  309. close(c1)
  310. }()
  311. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  312. if err := assertPipe("hello\n", "hello", stdout, cpty, 150); err != nil {
  313. t.Fatal(err)
  314. }
  315. })
  316. // Close pipes (client disconnects)
  317. if err := closeWrap(cpty, stdout, stdoutPipe); err != nil {
  318. t.Fatal(err)
  319. }
  320. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  321. setTimeout(t, "Waiting for CmdAttach timed out", 2*time.Second, func() {
  322. <-c1
  323. })
  324. // We closed stdin, expect /bin/cat to still be running
  325. // Wait a little bit to make sure container.monitor() did his thing
  326. _, err = container.WaitStop(500 * time.Millisecond)
  327. if err == nil || !container.IsRunning() {
  328. t.Fatalf("/bin/cat is not running after closing stdin")
  329. }
  330. // Try to avoid the timeout in destroy. Best effort, don't check error
  331. cStdin := container.StdinPipe()
  332. cStdin.Close()
  333. container.WaitStop(-1 * time.Second)
  334. }
  335. // Expected behaviour: container gets deleted automatically after exit
  336. func TestRunAutoRemove(t *testing.T) {
  337. t.Skip("Fixme. Skipping test for now, race condition")
  338. stdout, stdoutPipe := io.Pipe()
  339. cli := client.NewDockerCli(nil, stdoutPipe, ioutil.Discard, "", testDaemonProto, testDaemonAddr, nil)
  340. defer cleanup(globalEngine, t)
  341. c := make(chan struct{})
  342. go func() {
  343. defer close(c)
  344. if err := cli.CmdRun("--rm", unitTestImageID, "hostname"); err != nil {
  345. t.Fatal(err)
  346. }
  347. }()
  348. var temporaryContainerID string
  349. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  350. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  351. if err != nil {
  352. t.Fatal(err)
  353. }
  354. temporaryContainerID = cmdOutput
  355. if err := closeWrap(stdout, stdoutPipe); err != nil {
  356. t.Fatal(err)
  357. }
  358. })
  359. setTimeout(t, "CmdRun timed out", 10*time.Second, func() {
  360. <-c
  361. })
  362. time.Sleep(500 * time.Millisecond)
  363. if len(globalDaemon.List()) > 0 {
  364. t.Fatalf("failed to remove container automatically: container %s still exists", temporaryContainerID)
  365. }
  366. }