commands_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. package docker
  2. import (
  3. "bufio"
  4. "fmt"
  5. "github.com/dotcloud/docker"
  6. "github.com/dotcloud/docker/engine"
  7. "github.com/dotcloud/docker/term"
  8. "github.com/dotcloud/docker/utils"
  9. "io"
  10. "io/ioutil"
  11. "os"
  12. "path"
  13. "regexp"
  14. "strings"
  15. "testing"
  16. "time"
  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 setTimeout(t *testing.T, msg string, d time.Duration, f func()) {
  33. c := make(chan bool)
  34. // Make sure we are not too long
  35. go func() {
  36. time.Sleep(d)
  37. c <- true
  38. }()
  39. go func() {
  40. f()
  41. c <- false
  42. }()
  43. if <-c && msg != "" {
  44. t.Fatal(msg)
  45. }
  46. }
  47. func assertPipe(input, output string, r io.Reader, w io.Writer, count int) error {
  48. for i := 0; i < count; i++ {
  49. if _, err := w.Write([]byte(input)); err != nil {
  50. return err
  51. }
  52. o, err := bufio.NewReader(r).ReadString('\n')
  53. if err != nil {
  54. return err
  55. }
  56. if strings.Trim(o, " \r\n") != output {
  57. return fmt.Errorf("Unexpected output. Expected [%s], received [%s]", output, o)
  58. }
  59. }
  60. return nil
  61. }
  62. // TestRunHostname checks that 'docker run -h' correctly sets a custom hostname
  63. func TestRunHostname(t *testing.T) {
  64. stdout, stdoutPipe := io.Pipe()
  65. cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  66. defer cleanup(globalEngine, t)
  67. c := make(chan struct{})
  68. go func() {
  69. defer close(c)
  70. if err := cli.CmdRun("-h", "foobar", unitTestImageID, "hostname"); err != nil {
  71. t.Fatal(err)
  72. }
  73. }()
  74. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  75. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  76. if err != nil {
  77. t.Fatal(err)
  78. }
  79. if cmdOutput != "foobar\n" {
  80. t.Fatalf("'hostname' should display '%s', not '%s'", "foobar\n", cmdOutput)
  81. }
  82. })
  83. container := globalRuntime.List()[0]
  84. setTimeout(t, "CmdRun timed out", 10*time.Second, func() {
  85. <-c
  86. go func() {
  87. cli.CmdWait(container.ID)
  88. }()
  89. if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil {
  90. t.Fatal(err)
  91. }
  92. })
  93. // Cleanup pipes
  94. if err := closeWrap(stdout, stdoutPipe); err != nil {
  95. t.Fatal(err)
  96. }
  97. }
  98. // TestRunWorkdir checks that 'docker run -w' correctly sets a custom working directory
  99. func TestRunWorkdir(t *testing.T) {
  100. stdout, stdoutPipe := io.Pipe()
  101. cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  102. defer cleanup(globalEngine, t)
  103. c := make(chan struct{})
  104. go func() {
  105. defer close(c)
  106. if err := cli.CmdRun("-w", "/foo/bar", unitTestImageID, "pwd"); err != nil {
  107. t.Fatal(err)
  108. }
  109. }()
  110. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  111. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  112. if err != nil {
  113. t.Fatal(err)
  114. }
  115. if cmdOutput != "/foo/bar\n" {
  116. t.Fatalf("'pwd' should display '%s', not '%s'", "/foo/bar\n", cmdOutput)
  117. }
  118. })
  119. container := globalRuntime.List()[0]
  120. setTimeout(t, "CmdRun timed out", 10*time.Second, func() {
  121. <-c
  122. go func() {
  123. cli.CmdWait(container.ID)
  124. }()
  125. if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil {
  126. t.Fatal(err)
  127. }
  128. })
  129. // Cleanup pipes
  130. if err := closeWrap(stdout, stdoutPipe); err != nil {
  131. t.Fatal(err)
  132. }
  133. }
  134. // TestRunWorkdirExists checks that 'docker run -w' correctly sets a custom working directory, even if it exists
  135. func TestRunWorkdirExists(t *testing.T) {
  136. stdout, stdoutPipe := io.Pipe()
  137. cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  138. defer cleanup(globalEngine, t)
  139. c := make(chan struct{})
  140. go func() {
  141. defer close(c)
  142. if err := cli.CmdRun("-w", "/proc", unitTestImageID, "pwd"); err != nil {
  143. t.Fatal(err)
  144. }
  145. }()
  146. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  147. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  148. if err != nil {
  149. t.Fatal(err)
  150. }
  151. if cmdOutput != "/proc\n" {
  152. t.Fatalf("'pwd' should display '%s', not '%s'", "/proc\n", cmdOutput)
  153. }
  154. })
  155. container := globalRuntime.List()[0]
  156. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  157. <-c
  158. go func() {
  159. cli.CmdWait(container.ID)
  160. }()
  161. if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil {
  162. t.Fatal(err)
  163. }
  164. })
  165. // Cleanup pipes
  166. if err := closeWrap(stdout, stdoutPipe); err != nil {
  167. t.Fatal(err)
  168. }
  169. }
  170. func TestRunExit(t *testing.T) {
  171. stdin, stdinPipe := io.Pipe()
  172. stdout, stdoutPipe := io.Pipe()
  173. cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  174. defer cleanup(globalEngine, t)
  175. c1 := make(chan struct{})
  176. go func() {
  177. cli.CmdRun("-i", unitTestImageID, "/bin/cat")
  178. close(c1)
  179. }()
  180. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  181. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  182. t.Fatal(err)
  183. }
  184. })
  185. container := globalRuntime.List()[0]
  186. // Closing /bin/cat stdin, expect it to exit
  187. if err := stdin.Close(); err != nil {
  188. t.Fatal(err)
  189. }
  190. // as the process exited, CmdRun must finish and unblock. Wait for it
  191. setTimeout(t, "Waiting for CmdRun timed out", 10*time.Second, func() {
  192. <-c1
  193. go func() {
  194. cli.CmdWait(container.ID)
  195. }()
  196. if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil {
  197. t.Fatal(err)
  198. }
  199. })
  200. // Make sure that the client has been disconnected
  201. setTimeout(t, "The client should have been disconnected once the remote process exited.", 2*time.Second, func() {
  202. // Expecting pipe i/o error, just check that read does not block
  203. stdin.Read([]byte{})
  204. })
  205. // Cleanup pipes
  206. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  207. t.Fatal(err)
  208. }
  209. }
  210. // Expected behaviour: the process dies when the client disconnects
  211. func TestRunDisconnect(t *testing.T) {
  212. stdin, stdinPipe := io.Pipe()
  213. stdout, stdoutPipe := io.Pipe()
  214. cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  215. defer cleanup(globalEngine, t)
  216. c1 := make(chan struct{})
  217. go func() {
  218. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  219. // fact that CmdRun returns.
  220. cli.CmdRun("-i", unitTestImageID, "/bin/cat")
  221. close(c1)
  222. }()
  223. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  224. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  225. t.Fatal(err)
  226. }
  227. })
  228. // Close pipes (simulate disconnect)
  229. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  230. t.Fatal(err)
  231. }
  232. // as the pipes are close, we expect the process to die,
  233. // therefore CmdRun to unblock. Wait for CmdRun
  234. setTimeout(t, "Waiting for CmdRun timed out", 2*time.Second, func() {
  235. <-c1
  236. })
  237. // Client disconnect after run -i should cause stdin to be closed, which should
  238. // cause /bin/cat to exit.
  239. setTimeout(t, "Waiting for /bin/cat to exit timed out", 2*time.Second, func() {
  240. container := globalRuntime.List()[0]
  241. container.Wait()
  242. if container.State.IsRunning() {
  243. t.Fatalf("/bin/cat is still running after closing stdin")
  244. }
  245. })
  246. }
  247. // Expected behaviour: the process dies when the client disconnects
  248. func TestRunDisconnectTty(t *testing.T) {
  249. stdin, stdinPipe := io.Pipe()
  250. stdout, stdoutPipe := io.Pipe()
  251. cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  252. defer cleanup(globalEngine, t)
  253. c1 := make(chan struct{})
  254. go func() {
  255. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  256. // fact that CmdRun returns.
  257. if err := cli.CmdRun("-i", "-t", unitTestImageID, "/bin/cat"); err != nil {
  258. utils.Debugf("Error CmdRun: %s", err)
  259. }
  260. close(c1)
  261. }()
  262. setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() {
  263. for {
  264. // Client disconnect after run -i should keep stdin out in TTY mode
  265. l := globalRuntime.List()
  266. if len(l) == 1 && l[0].State.IsRunning() {
  267. break
  268. }
  269. time.Sleep(10 * time.Millisecond)
  270. }
  271. })
  272. // Client disconnect after run -i should keep stdin out in TTY mode
  273. container := globalRuntime.List()[0]
  274. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  275. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  276. t.Fatal(err)
  277. }
  278. })
  279. // Close pipes (simulate disconnect)
  280. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  281. t.Fatal(err)
  282. }
  283. // In tty mode, we expect the process to stay alive even after client's stdin closes.
  284. // Do not wait for run to finish
  285. // Give some time to monitor to do his thing
  286. container.WaitTimeout(500 * time.Millisecond)
  287. if !container.State.IsRunning() {
  288. t.Fatalf("/bin/cat should still be running after closing stdin (tty mode)")
  289. }
  290. }
  291. // TestAttachStdin checks attaching to stdin without stdout and stderr.
  292. // 'docker run -i -a stdin' should sends the client's stdin to the command,
  293. // then detach from it and print the container id.
  294. func TestRunAttachStdin(t *testing.T) {
  295. stdin, stdinPipe := io.Pipe()
  296. stdout, stdoutPipe := io.Pipe()
  297. cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  298. defer cleanup(globalEngine, t)
  299. ch := make(chan struct{})
  300. go func() {
  301. defer close(ch)
  302. cli.CmdRun("-i", "-a", "stdin", unitTestImageID, "sh", "-c", "echo hello && cat && sleep 5")
  303. }()
  304. // Send input to the command, close stdin
  305. setTimeout(t, "Write timed out", 10*time.Second, func() {
  306. if _, err := stdinPipe.Write([]byte("hi there\n")); err != nil {
  307. t.Fatal(err)
  308. }
  309. if err := stdinPipe.Close(); err != nil {
  310. t.Fatal(err)
  311. }
  312. })
  313. container := globalRuntime.List()[0]
  314. // Check output
  315. setTimeout(t, "Reading command output time out", 10*time.Second, func() {
  316. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  317. if err != nil {
  318. t.Fatal(err)
  319. }
  320. if cmdOutput != container.ID+"\n" {
  321. t.Fatalf("Wrong output: should be '%s', not '%s'\n", container.ID+"\n", cmdOutput)
  322. }
  323. })
  324. // wait for CmdRun to return
  325. setTimeout(t, "Waiting for CmdRun timed out", 5*time.Second, func() {
  326. <-ch
  327. })
  328. setTimeout(t, "Waiting for command to exit timed out", 10*time.Second, func() {
  329. container.Wait()
  330. })
  331. // Check logs
  332. if cmdLogs, err := container.ReadLog("json"); err != nil {
  333. t.Fatal(err)
  334. } else {
  335. if output, err := ioutil.ReadAll(cmdLogs); err != nil {
  336. t.Fatal(err)
  337. } else {
  338. expectedLogs := []string{"{\"log\":\"hello\\n\",\"stream\":\"stdout\"", "{\"log\":\"hi there\\n\",\"stream\":\"stdout\""}
  339. for _, expectedLog := range expectedLogs {
  340. if !strings.Contains(string(output), expectedLog) {
  341. t.Fatalf("Unexpected logs: should contains '%s', it is not '%s'\n", expectedLog, output)
  342. }
  343. }
  344. }
  345. }
  346. }
  347. // TestRunDetach checks attaching and detaching with the escape sequence.
  348. func TestRunDetach(t *testing.T) {
  349. stdin, stdinPipe := io.Pipe()
  350. stdout, stdoutPipe := io.Pipe()
  351. cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  352. defer cleanup(globalEngine, t)
  353. ch := make(chan struct{})
  354. go func() {
  355. defer close(ch)
  356. cli.CmdRun("-i", "-t", unitTestImageID, "cat")
  357. }()
  358. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  359. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  360. t.Fatal(err)
  361. }
  362. })
  363. container := globalRuntime.List()[0]
  364. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  365. stdinPipe.Write([]byte{16, 17})
  366. if err := stdinPipe.Close(); err != nil {
  367. t.Fatal(err)
  368. }
  369. })
  370. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  371. // wait for CmdRun to return
  372. setTimeout(t, "Waiting for CmdRun timed out", 15*time.Second, func() {
  373. <-ch
  374. })
  375. time.Sleep(500 * time.Millisecond)
  376. if !container.State.IsRunning() {
  377. t.Fatal("The detached container should be still running")
  378. }
  379. setTimeout(t, "Waiting for container to die timed out", 20*time.Second, func() {
  380. container.Kill()
  381. })
  382. }
  383. // TestAttachDetach checks that attach in tty mode can be detached using the long container ID
  384. func TestAttachDetach(t *testing.T) {
  385. stdin, stdinPipe := io.Pipe()
  386. stdout, stdoutPipe := io.Pipe()
  387. cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  388. defer cleanup(globalEngine, t)
  389. ch := make(chan struct{})
  390. go func() {
  391. defer close(ch)
  392. if err := cli.CmdRun("-i", "-t", "-d", unitTestImageID, "cat"); err != nil {
  393. t.Fatal(err)
  394. }
  395. }()
  396. var container *docker.Container
  397. setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() {
  398. for {
  399. l := globalRuntime.List()
  400. if len(l) == 1 && l[0].State.IsRunning() {
  401. container = l[0]
  402. break
  403. }
  404. time.Sleep(10 * time.Millisecond)
  405. }
  406. })
  407. setTimeout(t, "Reading container's id timed out", 10*time.Second, func() {
  408. buf := make([]byte, 1024)
  409. n, err := stdout.Read(buf)
  410. if err != nil {
  411. t.Fatal(err)
  412. }
  413. if strings.Trim(string(buf[:n]), " \r\n") != container.ID {
  414. t.Fatalf("Wrong ID received. Expect %s, received %s", container.ID, buf[:n])
  415. }
  416. })
  417. setTimeout(t, "Starting container timed out", 10*time.Second, func() {
  418. <-ch
  419. })
  420. pty, err := container.GetPtyMaster()
  421. if err != nil {
  422. t.Fatal(err)
  423. }
  424. state, err := term.MakeRaw(pty.Fd())
  425. if err != nil {
  426. t.Fatal(err)
  427. }
  428. defer term.RestoreTerminal(pty.Fd(), state)
  429. stdin, stdinPipe = io.Pipe()
  430. stdout, stdoutPipe = io.Pipe()
  431. cli = docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  432. ch = make(chan struct{})
  433. go func() {
  434. defer close(ch)
  435. if err := cli.CmdAttach(container.ID); err != nil {
  436. if err != io.ErrClosedPipe {
  437. t.Fatal(err)
  438. }
  439. }
  440. }()
  441. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  442. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  443. if err != io.ErrClosedPipe {
  444. t.Fatal(err)
  445. }
  446. }
  447. })
  448. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  449. stdinPipe.Write([]byte{16, 17})
  450. if err := stdinPipe.Close(); err != nil {
  451. t.Fatal(err)
  452. }
  453. })
  454. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  455. // wait for CmdRun to return
  456. setTimeout(t, "Waiting for CmdAttach timed out", 15*time.Second, func() {
  457. <-ch
  458. })
  459. time.Sleep(500 * time.Millisecond)
  460. if !container.State.IsRunning() {
  461. t.Fatal("The detached container should be still running")
  462. }
  463. setTimeout(t, "Waiting for container to die timedout", 5*time.Second, func() {
  464. container.Kill()
  465. })
  466. }
  467. // TestAttachDetachTruncatedID checks that attach in tty mode can be detached
  468. func TestAttachDetachTruncatedID(t *testing.T) {
  469. stdin, stdinPipe := io.Pipe()
  470. stdout, stdoutPipe := io.Pipe()
  471. cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  472. defer cleanup(globalEngine, t)
  473. go stdout.Read(make([]byte, 1024))
  474. setTimeout(t, "Starting container timed out", 2*time.Second, func() {
  475. if err := cli.CmdRun("-i", "-t", "-d", unitTestImageID, "cat"); err != nil {
  476. t.Fatal(err)
  477. }
  478. })
  479. container := globalRuntime.List()[0]
  480. stdin, stdinPipe = io.Pipe()
  481. stdout, stdoutPipe = io.Pipe()
  482. cli = docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  483. ch := make(chan struct{})
  484. go func() {
  485. defer close(ch)
  486. if err := cli.CmdAttach(utils.TruncateID(container.ID)); err != nil {
  487. if err != io.ErrClosedPipe {
  488. t.Fatal(err)
  489. }
  490. }
  491. }()
  492. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  493. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  494. if err != io.ErrClosedPipe {
  495. t.Fatal(err)
  496. }
  497. }
  498. })
  499. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  500. stdinPipe.Write([]byte{16, 17})
  501. if err := stdinPipe.Close(); err != nil {
  502. t.Fatal(err)
  503. }
  504. })
  505. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  506. // wait for CmdRun to return
  507. setTimeout(t, "Waiting for CmdAttach timed out", 15*time.Second, func() {
  508. <-ch
  509. })
  510. time.Sleep(500 * time.Millisecond)
  511. if !container.State.IsRunning() {
  512. t.Fatal("The detached container should be still running")
  513. }
  514. setTimeout(t, "Waiting for container to die timedout", 5*time.Second, func() {
  515. container.Kill()
  516. })
  517. }
  518. // Expected behaviour, the process stays alive when the client disconnects
  519. func TestAttachDisconnect(t *testing.T) {
  520. stdin, stdinPipe := io.Pipe()
  521. stdout, stdoutPipe := io.Pipe()
  522. cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  523. defer cleanup(globalEngine, t)
  524. go func() {
  525. // Start a process in daemon mode
  526. if err := cli.CmdRun("-d", "-i", unitTestImageID, "/bin/cat"); err != nil {
  527. utils.Debugf("Error CmdRun: %s", err)
  528. }
  529. }()
  530. setTimeout(t, "Waiting for CmdRun timed out", 10*time.Second, func() {
  531. if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil {
  532. t.Fatal(err)
  533. }
  534. })
  535. setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() {
  536. for {
  537. l := globalRuntime.List()
  538. if len(l) == 1 && l[0].State.IsRunning() {
  539. break
  540. }
  541. time.Sleep(10 * time.Millisecond)
  542. }
  543. })
  544. container := globalRuntime.List()[0]
  545. // Attach to it
  546. c1 := make(chan struct{})
  547. go func() {
  548. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  549. // fact that CmdAttach returns.
  550. cli.CmdAttach(container.ID)
  551. close(c1)
  552. }()
  553. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  554. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  555. t.Fatal(err)
  556. }
  557. })
  558. // Close pipes (client disconnects)
  559. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  560. t.Fatal(err)
  561. }
  562. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  563. setTimeout(t, "Waiting for CmdAttach timed out", 2*time.Second, func() {
  564. <-c1
  565. })
  566. // We closed stdin, expect /bin/cat to still be running
  567. // Wait a little bit to make sure container.monitor() did his thing
  568. err := container.WaitTimeout(500 * time.Millisecond)
  569. if err == nil || !container.State.IsRunning() {
  570. t.Fatalf("/bin/cat is not running after closing stdin")
  571. }
  572. // Try to avoid the timeout in destroy. Best effort, don't check error
  573. cStdin, _ := container.StdinPipe()
  574. cStdin.Close()
  575. container.Wait()
  576. }
  577. // Expected behaviour: container gets deleted automatically after exit
  578. func TestRunAutoRemove(t *testing.T) {
  579. t.Skip("Fixme. Skipping test for now, race condition")
  580. stdout, stdoutPipe := io.Pipe()
  581. cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  582. defer cleanup(globalEngine, t)
  583. c := make(chan struct{})
  584. go func() {
  585. defer close(c)
  586. if err := cli.CmdRun("-rm", unitTestImageID, "hostname"); err != nil {
  587. t.Fatal(err)
  588. }
  589. }()
  590. var temporaryContainerID string
  591. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  592. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  593. if err != nil {
  594. t.Fatal(err)
  595. }
  596. temporaryContainerID = cmdOutput
  597. if err := closeWrap(stdout, stdoutPipe); err != nil {
  598. t.Fatal(err)
  599. }
  600. })
  601. setTimeout(t, "CmdRun timed out", 10*time.Second, func() {
  602. <-c
  603. })
  604. time.Sleep(500 * time.Millisecond)
  605. if len(globalRuntime.List()) > 0 {
  606. t.Fatalf("failed to remove container automatically: container %s still exists", temporaryContainerID)
  607. }
  608. }
  609. func TestCmdLogs(t *testing.T) {
  610. cli := docker.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr)
  611. defer cleanup(globalEngine, t)
  612. if err := cli.CmdRun(unitTestImageID, "sh", "-c", "ls -l"); err != nil {
  613. t.Fatal(err)
  614. }
  615. if err := cli.CmdRun("-t", unitTestImageID, "sh", "-c", "ls -l"); err != nil {
  616. t.Fatal(err)
  617. }
  618. if err := cli.CmdLogs(globalRuntime.List()[0].ID); err != nil {
  619. t.Fatal(err)
  620. }
  621. }
  622. // Expected behaviour: using / as a bind mount source should throw an error
  623. func TestRunErrorBindMountRootSource(t *testing.T) {
  624. cli := docker.NewDockerCli(nil, nil, ioutil.Discard, testDaemonProto, testDaemonAddr)
  625. defer cleanup(globalEngine, t)
  626. c := make(chan struct{})
  627. go func() {
  628. defer close(c)
  629. if err := cli.CmdRun("-v", "/:/tmp", unitTestImageID, "echo 'should fail'"); err == nil {
  630. t.Fatal("should have failed to run when using / as a source for the bind mount")
  631. }
  632. }()
  633. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  634. <-c
  635. })
  636. }
  637. // Expected behaviour: error out when attempting to bind mount non-existing source paths
  638. func TestRunErrorBindNonExistingSource(t *testing.T) {
  639. cli := docker.NewDockerCli(nil, nil, ioutil.Discard, testDaemonProto, testDaemonAddr)
  640. defer cleanup(globalEngine, t)
  641. c := make(chan struct{})
  642. go func() {
  643. defer close(c)
  644. if err := cli.CmdRun("-v", "/i/dont/exist:/tmp", unitTestImageID, "echo 'should fail'"); err == nil {
  645. t.Fatal("should have failed to run when using /i/dont/exist as a source for the bind mount")
  646. }
  647. }()
  648. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  649. <-c
  650. })
  651. }
  652. func TestImagesViz(t *testing.T) {
  653. stdout, stdoutPipe := io.Pipe()
  654. cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  655. defer cleanup(globalEngine, t)
  656. image := buildTestImages(t, globalEngine)
  657. c := make(chan struct{})
  658. go func() {
  659. defer close(c)
  660. if err := cli.CmdImages("-viz"); err != nil {
  661. t.Fatal(err)
  662. }
  663. stdoutPipe.Close()
  664. }()
  665. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  666. cmdOutputBytes, err := ioutil.ReadAll(bufio.NewReader(stdout))
  667. if err != nil {
  668. t.Fatal(err)
  669. }
  670. cmdOutput := string(cmdOutputBytes)
  671. regexpStrings := []string{
  672. "digraph docker {",
  673. fmt.Sprintf("base -> \"%s\" \\[style=invis]", unitTestImageIDShort),
  674. fmt.Sprintf("label=\"%s\\\\n%s:latest\"", unitTestImageIDShort, unitTestImageName),
  675. fmt.Sprintf("label=\"%s\\\\n%s:%s\"", utils.TruncateID(image.ID), "test", "latest"),
  676. "base \\[style=invisible]",
  677. }
  678. compiledRegexps := []*regexp.Regexp{}
  679. for _, regexpString := range regexpStrings {
  680. regexp, err := regexp.Compile(regexpString)
  681. if err != nil {
  682. fmt.Println("Error in regex string: ", err)
  683. return
  684. }
  685. compiledRegexps = append(compiledRegexps, regexp)
  686. }
  687. for _, regexp := range compiledRegexps {
  688. if !regexp.MatchString(cmdOutput) {
  689. t.Fatalf("images -viz content '%s' did not match regexp '%s'", cmdOutput, regexp)
  690. }
  691. }
  692. })
  693. }
  694. func TestImagesTree(t *testing.T) {
  695. stdout, stdoutPipe := io.Pipe()
  696. cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  697. defer cleanup(globalEngine, t)
  698. image := buildTestImages(t, globalEngine)
  699. c := make(chan struct{})
  700. go func() {
  701. defer close(c)
  702. if err := cli.CmdImages("-tree"); err != nil {
  703. t.Fatal(err)
  704. }
  705. stdoutPipe.Close()
  706. }()
  707. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  708. cmdOutputBytes, err := ioutil.ReadAll(bufio.NewReader(stdout))
  709. if err != nil {
  710. t.Fatal(err)
  711. }
  712. cmdOutput := string(cmdOutputBytes)
  713. regexpStrings := []string{
  714. fmt.Sprintf("└─%s Size: (\\d+.\\d+ MB) \\(virtual \\d+.\\d+ MB\\) Tags: %s:latest", unitTestImageIDShort, unitTestImageName),
  715. "(?m) └─[0-9a-f]+.*",
  716. "(?m) └─[0-9a-f]+.*",
  717. "(?m) └─[0-9a-f]+.*",
  718. fmt.Sprintf("(?m)^ └─%s Size: \\d+.\\d+ MB \\(virtual \\d+.\\d+ MB\\) Tags: test:latest", utils.TruncateID(image.ID)),
  719. }
  720. compiledRegexps := []*regexp.Regexp{}
  721. for _, regexpString := range regexpStrings {
  722. regexp, err := regexp.Compile(regexpString)
  723. if err != nil {
  724. fmt.Println("Error in regex string: ", err)
  725. return
  726. }
  727. compiledRegexps = append(compiledRegexps, regexp)
  728. }
  729. for _, regexp := range compiledRegexps {
  730. if !regexp.MatchString(cmdOutput) {
  731. t.Fatalf("images -tree content '%s' did not match regexp '%s'", cmdOutput, regexp)
  732. }
  733. }
  734. })
  735. }
  736. func buildTestImages(t *testing.T, eng *engine.Engine) *docker.Image {
  737. var testBuilder = testContextTemplate{
  738. `
  739. from {IMAGE}
  740. run sh -c 'echo root:testpass > /tmp/passwd'
  741. run mkdir -p /var/run/sshd
  742. run [ "$(cat /tmp/passwd)" = "root:testpass" ]
  743. run [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]
  744. `,
  745. nil,
  746. nil,
  747. }
  748. image := buildImage(testBuilder, t, eng, true)
  749. err := mkServerFromEngine(eng, t).ContainerTag(image.ID, "test", "latest", false)
  750. if err != nil {
  751. t.Fatal(err)
  752. }
  753. return image
  754. }
  755. // #2098 - Docker cidFiles only contain short version of the containerId
  756. //sudo docker run -cidfile /tmp/docker_test.cid ubuntu echo "test"
  757. // TestRunCidFile tests that run -cidfile returns the longid
  758. func TestRunCidFile(t *testing.T) {
  759. stdout, stdoutPipe := io.Pipe()
  760. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  761. if err != nil {
  762. t.Fatal(err)
  763. }
  764. tmpCidFile := path.Join(tmpDir, "cid")
  765. cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
  766. defer cleanup(globalEngine, t)
  767. c := make(chan struct{})
  768. go func() {
  769. defer close(c)
  770. if err := cli.CmdRun("-cidfile", tmpCidFile, unitTestImageID, "ls"); err != nil {
  771. t.Fatal(err)
  772. }
  773. }()
  774. defer os.RemoveAll(tmpDir)
  775. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  776. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  777. if err != nil {
  778. t.Fatal(err)
  779. }
  780. if len(cmdOutput) < 1 {
  781. t.Fatalf("'ls' should return something , not '%s'", cmdOutput)
  782. }
  783. //read the tmpCidFile
  784. buffer, err := ioutil.ReadFile(tmpCidFile)
  785. if err != nil {
  786. t.Fatal(err)
  787. }
  788. id := string(buffer)
  789. if len(id) != len("2bf44ea18873287bd9ace8a4cb536a7cbe134bed67e805fdf2f58a57f69b320c") {
  790. t.Fatalf("-cidfile should be a long id, not '%s'", id)
  791. }
  792. //test that its a valid cid? (though the container is gone..)
  793. //remove the file and dir.
  794. })
  795. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  796. <-c
  797. })
  798. }