commands_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. package docker
  2. import (
  3. "bufio"
  4. "fmt"
  5. "github.com/dotcloud/docker/utils"
  6. "io"
  7. "io/ioutil"
  8. "strings"
  9. "testing"
  10. "time"
  11. )
  12. func closeWrap(args ...io.Closer) error {
  13. e := false
  14. ret := fmt.Errorf("Error closing elements")
  15. for _, c := range args {
  16. if err := c.Close(); err != nil {
  17. e = true
  18. ret = fmt.Errorf("%s\n%s", ret, err)
  19. }
  20. }
  21. if e {
  22. return ret
  23. }
  24. return nil
  25. }
  26. func setTimeout(t *testing.T, msg string, d time.Duration, f func()) {
  27. c := make(chan bool)
  28. // Make sure we are not too long
  29. go func() {
  30. time.Sleep(d)
  31. c <- true
  32. }()
  33. go func() {
  34. f()
  35. c <- false
  36. }()
  37. if <-c {
  38. t.Fatal(msg)
  39. }
  40. }
  41. func assertPipe(input, output string, r io.Reader, w io.Writer, count int) error {
  42. for i := 0; i < count; i++ {
  43. if _, err := w.Write([]byte(input)); err != nil {
  44. return err
  45. }
  46. o, err := bufio.NewReader(r).ReadString('\n')
  47. if err != nil {
  48. return err
  49. }
  50. if strings.Trim(o, " \r\n") != output {
  51. return fmt.Errorf("Unexpected output. Expected [%s], received [%s]", output, o)
  52. }
  53. }
  54. return nil
  55. }
  56. /*TODO
  57. func cmdImages(srv *Server, args ...string) (string, error) {
  58. stdout, stdoutPipe := io.Pipe()
  59. go func() {
  60. if err := srv.CmdImages(nil, stdoutPipe, args...); err != nil {
  61. return
  62. }
  63. // force the pipe closed, so that the code below gets an EOF
  64. stdoutPipe.Close()
  65. }()
  66. output, err := ioutil.ReadAll(stdout)
  67. if err != nil {
  68. return "", err
  69. }
  70. // Cleanup pipes
  71. return string(output), closeWrap(stdout, stdoutPipe)
  72. }
  73. // TestImages checks that 'docker images' displays information correctly
  74. func TestImages(t *testing.T) {
  75. runtime, err := newTestRuntime()
  76. if err != nil {
  77. t.Fatal(err)
  78. }
  79. defer nuke(runtime)
  80. srv := &Server{runtime: runtime}
  81. output, err := cmdImages(srv)
  82. if !strings.Contains(output, "REPOSITORY") {
  83. t.Fatal("'images' should have a header")
  84. }
  85. if !strings.Contains(output, "docker-ut") {
  86. t.Fatal("'images' should show the docker-ut image")
  87. }
  88. if !strings.Contains(output, "e9aa60c60128") {
  89. t.Fatal("'images' should show the docker-ut image id")
  90. }
  91. output, err = cmdImages(srv, "-q")
  92. if strings.Contains(output, "REPOSITORY") {
  93. t.Fatal("'images -q' should not have a header")
  94. }
  95. if strings.Contains(output, "docker-ut") {
  96. t.Fatal("'images' should not show the docker-ut image name")
  97. }
  98. if !strings.Contains(output, "e9aa60c60128") {
  99. t.Fatal("'images' should show the docker-ut image id")
  100. }
  101. output, err = cmdImages(srv, "-viz")
  102. if !strings.HasPrefix(output, "digraph docker {") {
  103. t.Fatal("'images -v' should start with the dot header")
  104. }
  105. if !strings.HasSuffix(output, "}\n") {
  106. t.Fatal("'images -v' should end with a '}'")
  107. }
  108. if !strings.Contains(output, "base -> \"e9aa60c60128\" [style=invis]") {
  109. t.Fatal("'images -v' should have the docker-ut image id node")
  110. }
  111. // todo: add checks for -a
  112. }
  113. */
  114. // TestRunHostname checks that 'docker run -h' correctly sets a custom hostname
  115. func TestRunHostname(t *testing.T) {
  116. stdout, stdoutPipe := io.Pipe()
  117. cli := NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  118. defer cleanup(globalRuntime)
  119. c := make(chan struct{})
  120. go func() {
  121. defer close(c)
  122. if err := cli.CmdRun("-h", "foobar", unitTestImageID, "hostname"); err != nil {
  123. t.Fatal(err)
  124. }
  125. }()
  126. utils.Debugf("--")
  127. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  128. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  129. if err != nil {
  130. t.Fatal(err)
  131. }
  132. if cmdOutput != "foobar\n" {
  133. t.Fatalf("'hostname' should display '%s', not '%s'", "foobar\n", cmdOutput)
  134. }
  135. })
  136. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  137. <-c
  138. })
  139. }
  140. /*
  141. func TestRunExit(t *testing.T) {
  142. runtime, err := newTestRuntime()
  143. if err != nil {
  144. t.Fatal(err)
  145. }
  146. defer nuke(runtime)
  147. srv := &Server{runtime: runtime}
  148. stdin, stdinPipe := io.Pipe()
  149. stdout, stdoutPipe := io.Pipe()
  150. c1 := make(chan struct{})
  151. go func() {
  152. srv.CmdRun(stdin, rcli.NewDockerLocalConn(stdoutPipe), "-i", GetTestImage(runtime).Id, "/bin/cat")
  153. close(c1)
  154. }()
  155. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  156. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 15); err != nil {
  157. t.Fatal(err)
  158. }
  159. })
  160. container := runtime.List()[0]
  161. // Closing /bin/cat stdin, expect it to exit
  162. p, err := container.StdinPipe()
  163. if err != nil {
  164. t.Fatal(err)
  165. }
  166. if err := p.Close(); err != nil {
  167. t.Fatal(err)
  168. }
  169. // as the process exited, CmdRun must finish and unblock. Wait for it
  170. setTimeout(t, "Waiting for CmdRun timed out", 2*time.Second, func() {
  171. <-c1
  172. cmdWait(srv, container)
  173. })
  174. // Make sure that the client has been disconnected
  175. setTimeout(t, "The client should have been disconnected once the remote process exited.", 2*time.Second, func() {
  176. // Expecting pipe i/o error, just check that read does not block
  177. stdin.Read([]byte{})
  178. })
  179. // Cleanup pipes
  180. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  181. t.Fatal(err)
  182. }
  183. }
  184. // Expected behaviour: the process dies when the client disconnects
  185. func TestRunDisconnect(t *testing.T) {
  186. runtime, err := newTestRuntime()
  187. if err != nil {
  188. t.Fatal(err)
  189. }
  190. defer nuke(runtime)
  191. srv := &Server{runtime: runtime}
  192. stdin, stdinPipe := io.Pipe()
  193. stdout, stdoutPipe := io.Pipe()
  194. c1 := make(chan struct{})
  195. go func() {
  196. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  197. // fact that CmdRun returns.
  198. srv.CmdRun(stdin, rcli.NewDockerLocalConn(stdoutPipe), "-i", GetTestImage(runtime).Id, "/bin/cat")
  199. close(c1)
  200. }()
  201. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  202. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 15); err != nil {
  203. t.Fatal(err)
  204. }
  205. })
  206. // Close pipes (simulate disconnect)
  207. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  208. t.Fatal(err)
  209. }
  210. // as the pipes are close, we expect the process to die,
  211. // therefore CmdRun to unblock. Wait for CmdRun
  212. setTimeout(t, "Waiting for CmdRun timed out", 2*time.Second, func() {
  213. <-c1
  214. })
  215. // Client disconnect after run -i should cause stdin to be closed, which should
  216. // cause /bin/cat to exit.
  217. setTimeout(t, "Waiting for /bin/cat to exit timed out", 2*time.Second, func() {
  218. container := runtime.List()[0]
  219. container.Wait()
  220. if container.State.Running {
  221. t.Fatalf("/bin/cat is still running after closing stdin")
  222. }
  223. })
  224. }
  225. // Expected behaviour: the process dies when the client disconnects
  226. func TestRunDisconnectTty(t *testing.T) {
  227. runtime, err := newTestRuntime()
  228. if err != nil {
  229. t.Fatal(err)
  230. }
  231. defer nuke(runtime)
  232. srv := &Server{runtime: runtime}
  233. stdin, stdinPipe := io.Pipe()
  234. stdout, stdoutPipe := io.Pipe()
  235. c1 := make(chan struct{})
  236. go func() {
  237. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  238. // fact that CmdRun returns.
  239. srv.CmdRun(stdin, rcli.NewDockerLocalConn(stdoutPipe), "-i", "-t", GetTestImage(runtime).Id, "/bin/cat")
  240. close(c1)
  241. }()
  242. setTimeout(t, "Waiting for the container to be started timed out", 2*time.Second, func() {
  243. for {
  244. // Client disconnect after run -i should keep stdin out in TTY mode
  245. l := runtime.List()
  246. if len(l) == 1 && l[0].State.Running {
  247. break
  248. }
  249. time.Sleep(10 * time.Millisecond)
  250. }
  251. })
  252. // Client disconnect after run -i should keep stdin out in TTY mode
  253. container := runtime.List()[0]
  254. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  255. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 15); err != nil {
  256. t.Fatal(err)
  257. }
  258. })
  259. // Close pipes (simulate disconnect)
  260. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  261. t.Fatal(err)
  262. }
  263. // In tty mode, we expect the process to stay alive even after client's stdin closes.
  264. // Do not wait for run to finish
  265. // Give some time to monitor to do his thing
  266. container.WaitTimeout(500 * time.Millisecond)
  267. if !container.State.Running {
  268. t.Fatalf("/bin/cat should still be running after closing stdin (tty mode)")
  269. }
  270. }
  271. */
  272. // TestAttachStdin checks attaching to stdin without stdout and stderr.
  273. // 'docker run -i -a stdin' should sends the client's stdin to the command,
  274. // then detach from it and print the container id.
  275. func TestRunAttachStdin(t *testing.T) {
  276. stdin, stdinPipe := io.Pipe()
  277. stdout, stdoutPipe := io.Pipe()
  278. cli := NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  279. defer cleanup(globalRuntime)
  280. ch := make(chan struct{})
  281. go func() {
  282. defer close(ch)
  283. cli.CmdRun("-i", "-a", "stdin", unitTestImageID, "sh", "-c", "echo hello && cat")
  284. }()
  285. // Send input to the command, close stdin
  286. setTimeout(t, "Write timed out", 10*time.Second, func() {
  287. if _, err := stdinPipe.Write([]byte("hi there\n")); err != nil {
  288. t.Fatal(err)
  289. }
  290. if err := stdinPipe.Close(); err != nil {
  291. t.Fatal(err)
  292. }
  293. })
  294. container := globalRuntime.List()[0]
  295. // Check output
  296. setTimeout(t, "Reading command output time out", 10*time.Second, func() {
  297. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  298. if err != nil {
  299. t.Fatal(err)
  300. }
  301. if cmdOutput != container.ShortID()+"\n" {
  302. t.Fatalf("Wrong output: should be '%s', not '%s'\n", container.ShortID()+"\n", cmdOutput)
  303. }
  304. })
  305. // wait for CmdRun to return
  306. setTimeout(t, "Waiting for CmdRun timed out", 5*time.Second, func() {
  307. // Unblock hijack end
  308. stdout.Read([]byte{})
  309. <-ch
  310. })
  311. setTimeout(t, "Waiting for command to exit timed out", 5*time.Second, func() {
  312. container.Wait()
  313. })
  314. // Check logs
  315. if cmdLogs, err := container.ReadLog("stdout"); err != nil {
  316. t.Fatal(err)
  317. } else {
  318. if output, err := ioutil.ReadAll(cmdLogs); err != nil {
  319. t.Fatal(err)
  320. } else {
  321. expectedLog := "hello\nhi there\n"
  322. if string(output) != expectedLog {
  323. t.Fatalf("Unexpected logs: should be '%s', not '%s'\n", expectedLog, output)
  324. }
  325. }
  326. }
  327. }
  328. /*
  329. // Expected behaviour, the process stays alive when the client disconnects
  330. func TestAttachDisconnect(t *testing.T) {
  331. runtime, err := newTestRuntime()
  332. if err != nil {
  333. t.Fatal(err)
  334. }
  335. defer nuke(runtime)
  336. srv := &Server{runtime: runtime}
  337. container, err := NewBuilder(runtime).Create(
  338. &Config{
  339. Image: GetTestImage(runtime).Id,
  340. CpuShares: 1000,
  341. Memory: 33554432,
  342. Cmd: []string{"/bin/cat"},
  343. OpenStdin: true,
  344. },
  345. )
  346. if err != nil {
  347. t.Fatal(err)
  348. }
  349. defer runtime.Destroy(container)
  350. // Start the process
  351. if err := container.Start(); err != nil {
  352. t.Fatal(err)
  353. }
  354. stdin, stdinPipe := io.Pipe()
  355. stdout, stdoutPipe := io.Pipe()
  356. // Attach to it
  357. c1 := make(chan struct{})
  358. go func() {
  359. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  360. // fact that CmdAttach returns.
  361. srv.CmdAttach(stdin, rcli.NewDockerLocalConn(stdoutPipe), container.Id)
  362. close(c1)
  363. }()
  364. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  365. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 15); err != nil {
  366. t.Fatal(err)
  367. }
  368. })
  369. // Close pipes (client disconnects)
  370. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  371. t.Fatal(err)
  372. }
  373. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  374. setTimeout(t, "Waiting for CmdAttach timed out", 2*time.Second, func() {
  375. <-c1
  376. })
  377. // We closed stdin, expect /bin/cat to still be running
  378. // Wait a little bit to make sure container.monitor() did his thing
  379. err = container.WaitTimeout(500 * time.Millisecond)
  380. if err == nil || !container.State.Running {
  381. t.Fatalf("/bin/cat is not running after closing stdin")
  382. }
  383. // Try to avoid the timeoout in destroy. Best effort, don't check error
  384. cStdin, _ := container.StdinPipe()
  385. cStdin.Close()
  386. container.Wait()
  387. }
  388. */