commands_test.go 11 KB

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