commands_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. package docker
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "path"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/dotcloud/docker/api/client"
  13. "github.com/dotcloud/docker/daemon"
  14. "github.com/dotcloud/docker/engine"
  15. "github.com/dotcloud/docker/pkg/term"
  16. "github.com/dotcloud/docker/utils"
  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].State.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. // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  104. func TestRunWorkdirExistsAndIsFile(t *testing.T) {
  105. cli := client.NewDockerCli(nil, nil, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  106. defer cleanup(globalEngine, t)
  107. c := make(chan struct{})
  108. go func() {
  109. defer close(c)
  110. if err := cli.CmdRun("-w", "/bin/cat", unitTestImageID, "pwd"); err == nil {
  111. t.Fatal("should have failed to run when using /bin/cat as working dir.")
  112. }
  113. }()
  114. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  115. <-c
  116. })
  117. }
  118. func TestRunExit(t *testing.T) {
  119. stdin, stdinPipe := io.Pipe()
  120. stdout, stdoutPipe := io.Pipe()
  121. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  122. defer cleanup(globalEngine, t)
  123. c1 := make(chan struct{})
  124. go func() {
  125. cli.CmdRun("-i", unitTestImageID, "/bin/cat")
  126. close(c1)
  127. }()
  128. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  129. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  130. t.Fatal(err)
  131. }
  132. })
  133. container := globalDaemon.List()[0]
  134. // Closing /bin/cat stdin, expect it to exit
  135. if err := stdin.Close(); err != nil {
  136. t.Fatal(err)
  137. }
  138. // as the process exited, CmdRun must finish and unblock. Wait for it
  139. setTimeout(t, "Waiting for CmdRun timed out", 10*time.Second, func() {
  140. <-c1
  141. go func() {
  142. cli.CmdWait(container.ID)
  143. }()
  144. if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil {
  145. t.Fatal(err)
  146. }
  147. })
  148. // Make sure that the client has been disconnected
  149. setTimeout(t, "The client should have been disconnected once the remote process exited.", 2*time.Second, func() {
  150. // Expecting pipe i/o error, just check that read does not block
  151. stdin.Read([]byte{})
  152. })
  153. // Cleanup pipes
  154. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  155. t.Fatal(err)
  156. }
  157. }
  158. // Expected behaviour: the process dies when the client disconnects
  159. func TestRunDisconnect(t *testing.T) {
  160. stdin, stdinPipe := io.Pipe()
  161. stdout, stdoutPipe := io.Pipe()
  162. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  163. defer cleanup(globalEngine, t)
  164. c1 := make(chan struct{})
  165. go func() {
  166. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  167. // fact that CmdRun returns.
  168. cli.CmdRun("-i", unitTestImageID, "/bin/cat")
  169. close(c1)
  170. }()
  171. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  172. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  173. t.Fatal(err)
  174. }
  175. })
  176. // Close pipes (simulate disconnect)
  177. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  178. t.Fatal(err)
  179. }
  180. // as the pipes are close, we expect the process to die,
  181. // therefore CmdRun to unblock. Wait for CmdRun
  182. setTimeout(t, "Waiting for CmdRun timed out", 2*time.Second, func() {
  183. <-c1
  184. })
  185. // Client disconnect after run -i should cause stdin to be closed, which should
  186. // cause /bin/cat to exit.
  187. setTimeout(t, "Waiting for /bin/cat to exit timed out", 2*time.Second, func() {
  188. container := globalDaemon.List()[0]
  189. container.State.WaitStop(-1 * time.Second)
  190. if container.State.IsRunning() {
  191. t.Fatalf("/bin/cat is still running after closing stdin")
  192. }
  193. })
  194. }
  195. // Expected behaviour: the process stay alive when the client disconnects
  196. // but the client detaches.
  197. func TestRunDisconnectTty(t *testing.T) {
  198. stdin, stdinPipe := io.Pipe()
  199. stdout, stdoutPipe := io.Pipe()
  200. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  201. defer cleanup(globalEngine, t)
  202. c1 := make(chan struct{})
  203. go func() {
  204. defer close(c1)
  205. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  206. // fact that CmdRun returns.
  207. if err := cli.CmdRun("-i", "-t", unitTestImageID, "/bin/cat"); err != nil {
  208. utils.Debugf("Error CmdRun: %s", err)
  209. }
  210. }()
  211. container := waitContainerStart(t, 10*time.Second)
  212. state := setRaw(t, container)
  213. defer unsetRaw(t, container, state)
  214. // Client disconnect after run -i should keep stdin out in TTY mode
  215. setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
  216. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  217. t.Fatal(err)
  218. }
  219. })
  220. // Close pipes (simulate disconnect)
  221. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  222. t.Fatal(err)
  223. }
  224. // wait for CmdRun to return
  225. setTimeout(t, "Waiting for CmdRun timed out", 5*time.Second, func() {
  226. <-c1
  227. })
  228. // In tty mode, we expect the process to stay alive even after client's stdin closes.
  229. // Give some time to monitor to do his thing
  230. container.State.WaitStop(500 * time.Millisecond)
  231. if !container.State.IsRunning() {
  232. t.Fatalf("/bin/cat should still be running after closing stdin (tty mode)")
  233. }
  234. }
  235. // TestRunDetach checks attaching and detaching with the escape sequence.
  236. func TestRunDetach(t *testing.T) {
  237. stdin, stdinPipe := io.Pipe()
  238. stdout, stdoutPipe := io.Pipe()
  239. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  240. defer cleanup(globalEngine, t)
  241. ch := make(chan struct{})
  242. go func() {
  243. defer close(ch)
  244. cli.CmdRun("-i", "-t", unitTestImageID, "cat")
  245. }()
  246. container := waitContainerStart(t, 10*time.Second)
  247. state := setRaw(t, container)
  248. defer unsetRaw(t, container, state)
  249. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  250. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  251. t.Fatal(err)
  252. }
  253. })
  254. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  255. stdinPipe.Write([]byte{16})
  256. time.Sleep(100 * time.Millisecond)
  257. stdinPipe.Write([]byte{17})
  258. })
  259. // wait for CmdRun to return
  260. setTimeout(t, "Waiting for CmdRun timed out", 15*time.Second, func() {
  261. <-ch
  262. })
  263. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  264. time.Sleep(500 * time.Millisecond)
  265. if !container.State.IsRunning() {
  266. t.Fatal("The detached container should be still running")
  267. }
  268. setTimeout(t, "Waiting for container to die timed out", 20*time.Second, func() {
  269. container.Kill()
  270. })
  271. }
  272. // TestAttachDetach checks that attach in tty mode can be detached using the long container ID
  273. func TestAttachDetach(t *testing.T) {
  274. stdin, stdinPipe := io.Pipe()
  275. stdout, stdoutPipe := io.Pipe()
  276. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  277. defer cleanup(globalEngine, t)
  278. ch := make(chan struct{})
  279. go func() {
  280. defer close(ch)
  281. if err := cli.CmdRun("-i", "-t", "-d", unitTestImageID, "cat"); err != nil {
  282. t.Fatal(err)
  283. }
  284. }()
  285. container := waitContainerStart(t, 10*time.Second)
  286. setTimeout(t, "Reading container's id timed out", 10*time.Second, func() {
  287. buf := make([]byte, 1024)
  288. n, err := stdout.Read(buf)
  289. if err != nil {
  290. t.Fatal(err)
  291. }
  292. if strings.Trim(string(buf[:n]), " \r\n") != container.ID {
  293. t.Fatalf("Wrong ID received. Expect %s, received %s", container.ID, buf[:n])
  294. }
  295. })
  296. setTimeout(t, "Starting container timed out", 10*time.Second, func() {
  297. <-ch
  298. })
  299. state := setRaw(t, container)
  300. defer unsetRaw(t, container, state)
  301. stdin, stdinPipe = io.Pipe()
  302. stdout, stdoutPipe = io.Pipe()
  303. cli = client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  304. ch = make(chan struct{})
  305. go func() {
  306. defer close(ch)
  307. if err := cli.CmdAttach(container.ID); err != nil {
  308. if err != io.ErrClosedPipe {
  309. t.Fatal(err)
  310. }
  311. }
  312. }()
  313. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  314. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  315. if err != io.ErrClosedPipe {
  316. t.Fatal(err)
  317. }
  318. }
  319. })
  320. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  321. stdinPipe.Write([]byte{16})
  322. time.Sleep(100 * time.Millisecond)
  323. stdinPipe.Write([]byte{17})
  324. })
  325. // wait for CmdRun to return
  326. setTimeout(t, "Waiting for CmdAttach timed out", 15*time.Second, func() {
  327. <-ch
  328. })
  329. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  330. time.Sleep(500 * time.Millisecond)
  331. if !container.State.IsRunning() {
  332. t.Fatal("The detached container should be still running")
  333. }
  334. setTimeout(t, "Waiting for container to die timedout", 5*time.Second, func() {
  335. container.Kill()
  336. })
  337. }
  338. // TestAttachDetachTruncatedID checks that attach in tty mode can be detached
  339. func TestAttachDetachTruncatedID(t *testing.T) {
  340. stdin, stdinPipe := io.Pipe()
  341. stdout, stdoutPipe := io.Pipe()
  342. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  343. defer cleanup(globalEngine, t)
  344. // Discard the CmdRun output
  345. go stdout.Read(make([]byte, 1024))
  346. setTimeout(t, "Starting container timed out", 2*time.Second, func() {
  347. if err := cli.CmdRun("-i", "-t", "-d", unitTestImageID, "cat"); err != nil {
  348. t.Fatal(err)
  349. }
  350. })
  351. container := waitContainerStart(t, 10*time.Second)
  352. state := setRaw(t, container)
  353. defer unsetRaw(t, container, state)
  354. stdin, stdinPipe = io.Pipe()
  355. stdout, stdoutPipe = io.Pipe()
  356. cli = client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  357. ch := make(chan struct{})
  358. go func() {
  359. defer close(ch)
  360. if err := cli.CmdAttach(utils.TruncateID(container.ID)); err != nil {
  361. if err != io.ErrClosedPipe {
  362. t.Fatal(err)
  363. }
  364. }
  365. }()
  366. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  367. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  368. if err != io.ErrClosedPipe {
  369. t.Fatal(err)
  370. }
  371. }
  372. })
  373. setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
  374. stdinPipe.Write([]byte{16})
  375. time.Sleep(100 * time.Millisecond)
  376. stdinPipe.Write([]byte{17})
  377. })
  378. // wait for CmdRun to return
  379. setTimeout(t, "Waiting for CmdAttach timed out", 15*time.Second, func() {
  380. <-ch
  381. })
  382. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  383. time.Sleep(500 * time.Millisecond)
  384. if !container.State.IsRunning() {
  385. t.Fatal("The detached container should be still running")
  386. }
  387. setTimeout(t, "Waiting for container to die timedout", 5*time.Second, func() {
  388. container.Kill()
  389. })
  390. }
  391. // Expected behaviour, the process stays alive when the client disconnects
  392. func TestAttachDisconnect(t *testing.T) {
  393. stdin, stdinPipe := io.Pipe()
  394. stdout, stdoutPipe := io.Pipe()
  395. cli := client.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  396. defer cleanup(globalEngine, t)
  397. go func() {
  398. // Start a process in daemon mode
  399. if err := cli.CmdRun("-d", "-i", unitTestImageID, "/bin/cat"); err != nil {
  400. utils.Debugf("Error CmdRun: %s", err)
  401. }
  402. }()
  403. setTimeout(t, "Waiting for CmdRun timed out", 10*time.Second, func() {
  404. if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil {
  405. t.Fatal(err)
  406. }
  407. })
  408. setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() {
  409. for {
  410. l := globalDaemon.List()
  411. if len(l) == 1 && l[0].State.IsRunning() {
  412. break
  413. }
  414. time.Sleep(10 * time.Millisecond)
  415. }
  416. })
  417. container := globalDaemon.List()[0]
  418. // Attach to it
  419. c1 := make(chan struct{})
  420. go func() {
  421. // We're simulating a disconnect so the return value doesn't matter. What matters is the
  422. // fact that CmdAttach returns.
  423. cli.CmdAttach(container.ID)
  424. close(c1)
  425. }()
  426. setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
  427. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 150); err != nil {
  428. t.Fatal(err)
  429. }
  430. })
  431. // Close pipes (client disconnects)
  432. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  433. t.Fatal(err)
  434. }
  435. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  436. setTimeout(t, "Waiting for CmdAttach timed out", 2*time.Second, func() {
  437. <-c1
  438. })
  439. // We closed stdin, expect /bin/cat to still be running
  440. // Wait a little bit to make sure container.monitor() did his thing
  441. _, err := container.State.WaitStop(500 * time.Millisecond)
  442. if err == nil || !container.State.IsRunning() {
  443. t.Fatalf("/bin/cat is not running after closing stdin")
  444. }
  445. // Try to avoid the timeout in destroy. Best effort, don't check error
  446. cStdin, _ := container.StdinPipe()
  447. cStdin.Close()
  448. container.State.WaitStop(-1 * time.Second)
  449. }
  450. // Expected behaviour: container gets deleted automatically after exit
  451. func TestRunAutoRemove(t *testing.T) {
  452. t.Skip("Fixme. Skipping test for now, race condition")
  453. stdout, stdoutPipe := io.Pipe()
  454. cli := client.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  455. defer cleanup(globalEngine, t)
  456. c := make(chan struct{})
  457. go func() {
  458. defer close(c)
  459. if err := cli.CmdRun("--rm", unitTestImageID, "hostname"); err != nil {
  460. t.Fatal(err)
  461. }
  462. }()
  463. var temporaryContainerID string
  464. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  465. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  466. if err != nil {
  467. t.Fatal(err)
  468. }
  469. temporaryContainerID = cmdOutput
  470. if err := closeWrap(stdout, stdoutPipe); err != nil {
  471. t.Fatal(err)
  472. }
  473. })
  474. setTimeout(t, "CmdRun timed out", 10*time.Second, func() {
  475. <-c
  476. })
  477. time.Sleep(500 * time.Millisecond)
  478. if len(globalDaemon.List()) > 0 {
  479. t.Fatalf("failed to remove container automatically: container %s still exists", temporaryContainerID)
  480. }
  481. }
  482. // Expected behaviour: error out when attempting to bind mount non-existing source paths
  483. func TestRunErrorBindNonExistingSource(t *testing.T) {
  484. cli := client.NewDockerCli(nil, nil, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  485. defer cleanup(globalEngine, t)
  486. c := make(chan struct{})
  487. go func() {
  488. defer close(c)
  489. // This check is made at runtime, can't be "unit tested"
  490. if err := cli.CmdRun("-v", "/i/dont/exist:/tmp", unitTestImageID, "echo 'should fail'"); err == nil {
  491. t.Fatal("should have failed to run when using /i/dont/exist as a source for the bind mount")
  492. }
  493. }()
  494. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  495. <-c
  496. })
  497. }
  498. // #2098 - Docker cidFiles only contain short version of the containerId
  499. //sudo docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"
  500. // TestRunCidFile tests that run --cidfile returns the longid
  501. func TestRunCidFileCheckIDLength(t *testing.T) {
  502. stdout, stdoutPipe := io.Pipe()
  503. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  504. if err != nil {
  505. t.Fatal(err)
  506. }
  507. tmpCidFile := path.Join(tmpDir, "cid")
  508. cli := client.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  509. defer cleanup(globalEngine, t)
  510. c := make(chan struct{})
  511. go func() {
  512. defer close(c)
  513. if err := cli.CmdRun("--cidfile", tmpCidFile, unitTestImageID, "ls"); err != nil {
  514. t.Fatal(err)
  515. }
  516. }()
  517. defer os.RemoveAll(tmpDir)
  518. setTimeout(t, "Reading command output time out", 2*time.Second, func() {
  519. cmdOutput, err := bufio.NewReader(stdout).ReadString('\n')
  520. if err != nil {
  521. t.Fatal(err)
  522. }
  523. if len(cmdOutput) < 1 {
  524. t.Fatalf("'ls' should return something , not '%s'", cmdOutput)
  525. }
  526. //read the tmpCidFile
  527. buffer, err := ioutil.ReadFile(tmpCidFile)
  528. if err != nil {
  529. t.Fatal(err)
  530. }
  531. id := string(buffer)
  532. if len(id) != len("2bf44ea18873287bd9ace8a4cb536a7cbe134bed67e805fdf2f58a57f69b320c") {
  533. t.Fatalf("--cidfile should be a long id, not '%s'", id)
  534. }
  535. //test that its a valid cid? (though the container is gone..)
  536. //remove the file and dir.
  537. })
  538. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  539. <-c
  540. })
  541. }
  542. // Ensure that CIDFile gets deleted if it's empty
  543. // Perform this test by making `docker run` fail
  544. func TestRunCidFileCleanupIfEmpty(t *testing.T) {
  545. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  546. if err != nil {
  547. t.Fatal(err)
  548. }
  549. tmpCidFile := path.Join(tmpDir, "cid")
  550. cli := client.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  551. defer cleanup(globalEngine, t)
  552. c := make(chan struct{})
  553. go func() {
  554. defer close(c)
  555. if err := cli.CmdRun("--cidfile", tmpCidFile, unitTestImageID); err == nil {
  556. t.Fatal("running without a command should haveve failed")
  557. }
  558. if _, err := os.Stat(tmpCidFile); err == nil {
  559. t.Fatalf("empty CIDFile '%s' should've been deleted", tmpCidFile)
  560. }
  561. }()
  562. defer os.RemoveAll(tmpDir)
  563. setTimeout(t, "CmdRun timed out", 5*time.Second, func() {
  564. <-c
  565. })
  566. }
  567. func TestContainerOrphaning(t *testing.T) {
  568. // setup a temporary directory
  569. tmpDir, err := ioutil.TempDir("", "project")
  570. if err != nil {
  571. t.Fatal(err)
  572. }
  573. defer os.RemoveAll(tmpDir)
  574. // setup a CLI and server
  575. cli := client.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
  576. defer cleanup(globalEngine, t)
  577. srv := mkServerFromEngine(globalEngine, t)
  578. // closure to build something
  579. buildSomething := func(template string, image string) string {
  580. dockerfile := path.Join(tmpDir, "Dockerfile")
  581. replacer := strings.NewReplacer("{IMAGE}", unitTestImageID)
  582. contents := replacer.Replace(template)
  583. ioutil.WriteFile(dockerfile, []byte(contents), 0x777)
  584. if err := cli.CmdBuild("-t", image, tmpDir); err != nil {
  585. t.Fatal(err)
  586. }
  587. job := globalEngine.Job("image_get", image)
  588. info, _ := job.Stdout.AddEnv()
  589. if err := job.Run(); err != nil {
  590. t.Fatal(err)
  591. }
  592. return info.Get("Id")
  593. }
  594. // build an image
  595. imageName := "orphan-test"
  596. template1 := `
  597. from {IMAGE}
  598. cmd ["/bin/echo", "holla"]
  599. `
  600. img1 := buildSomething(template1, imageName)
  601. // create a container using the fist image
  602. if err := cli.CmdRun(imageName); err != nil {
  603. t.Fatal(err)
  604. }
  605. // build a new image that splits lineage
  606. template2 := `
  607. from {IMAGE}
  608. cmd ["/bin/echo", "holla"]
  609. expose 22
  610. `
  611. buildSomething(template2, imageName)
  612. // remove the second image by name
  613. resp := engine.NewTable("", 0)
  614. if err := srv.DeleteImage(imageName, resp, true, false, false); err == nil {
  615. t.Fatal("Expected error, got none")
  616. }
  617. // see if we deleted the first image (and orphaned the container)
  618. for _, i := range resp.Data {
  619. if img1 == i.Get("Deleted") {
  620. t.Fatal("Orphaned image with container")
  621. }
  622. }
  623. }