docker_cli_logs_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "os/exec"
  6. "regexp"
  7. "strings"
  8. "time"
  9. "github.com/docker/docker/integration-cli/checker"
  10. "github.com/docker/docker/integration-cli/cli"
  11. "github.com/docker/docker/pkg/jsonlog"
  12. "github.com/docker/docker/pkg/testutil"
  13. icmd "github.com/docker/docker/pkg/testutil/cmd"
  14. "github.com/go-check/check"
  15. )
  16. // This used to work, it test a log of PageSize-1 (gh#4851)
  17. func (s *DockerSuite) TestLogsContainerSmallerThanPage(c *check.C) {
  18. testLogsContainerPagination(c, 32767)
  19. }
  20. // Regression test: When going over the PageSize, it used to panic (gh#4851)
  21. func (s *DockerSuite) TestLogsContainerBiggerThanPage(c *check.C) {
  22. testLogsContainerPagination(c, 32768)
  23. }
  24. // Regression test: When going much over the PageSize, it used to block (gh#4851)
  25. func (s *DockerSuite) TestLogsContainerMuchBiggerThanPage(c *check.C) {
  26. testLogsContainerPagination(c, 33000)
  27. }
  28. func testLogsContainerPagination(c *check.C, testLen int) {
  29. out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo -n = >> a.a; done; echo >> a.a; cat a.a", testLen))
  30. id := strings.TrimSpace(out)
  31. dockerCmd(c, "wait", id)
  32. out, _ = dockerCmd(c, "logs", id)
  33. c.Assert(out, checker.HasLen, testLen+1)
  34. }
  35. func (s *DockerSuite) TestLogsTimestamps(c *check.C) {
  36. testLen := 100
  37. out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo = >> a.a; done; cat a.a", testLen))
  38. id := strings.TrimSpace(out)
  39. dockerCmd(c, "wait", id)
  40. out, _ = dockerCmd(c, "logs", "-t", id)
  41. lines := strings.Split(out, "\n")
  42. c.Assert(lines, checker.HasLen, testLen+1)
  43. ts := regexp.MustCompile(`^.* `)
  44. for _, l := range lines {
  45. if l != "" {
  46. _, err := time.Parse(jsonlog.RFC3339NanoFixed+" ", ts.FindString(l))
  47. c.Assert(err, checker.IsNil, check.Commentf("Failed to parse timestamp from %v", l))
  48. // ensure we have padded 0's
  49. c.Assert(l[29], checker.Equals, uint8('Z'))
  50. }
  51. }
  52. }
  53. func (s *DockerSuite) TestLogsSeparateStderr(c *check.C) {
  54. msg := "stderr_log"
  55. out := cli.DockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("echo %s 1>&2", msg)).Combined()
  56. id := strings.TrimSpace(out)
  57. cli.DockerCmd(c, "wait", id)
  58. cli.DockerCmd(c, "logs", id).Assert(c, icmd.Expected{
  59. Out: "",
  60. Err: msg,
  61. })
  62. }
  63. func (s *DockerSuite) TestLogsStderrInStdout(c *check.C) {
  64. // TODO Windows: Needs investigation why this fails. Obtained string includes
  65. // a bunch of ANSI escape sequences before the "stderr_log" message.
  66. testRequires(c, DaemonIsLinux)
  67. msg := "stderr_log"
  68. out := cli.DockerCmd(c, "run", "-d", "-t", "busybox", "sh", "-c", fmt.Sprintf("echo %s 1>&2", msg)).Combined()
  69. id := strings.TrimSpace(out)
  70. cli.DockerCmd(c, "wait", id)
  71. cli.DockerCmd(c, "logs", id).Assert(c, icmd.Expected{
  72. Out: msg,
  73. Err: "",
  74. })
  75. }
  76. func (s *DockerSuite) TestLogsTail(c *check.C) {
  77. testLen := 100
  78. out := cli.DockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo =; done;", testLen)).Combined()
  79. id := strings.TrimSpace(out)
  80. cli.DockerCmd(c, "wait", id)
  81. out = cli.DockerCmd(c, "logs", "--tail", "0", id).Combined()
  82. lines := strings.Split(out, "\n")
  83. c.Assert(lines, checker.HasLen, 1)
  84. out = cli.DockerCmd(c, "logs", "--tail", "5", id).Combined()
  85. lines = strings.Split(out, "\n")
  86. c.Assert(lines, checker.HasLen, 6)
  87. out = cli.DockerCmd(c, "logs", "--tail", "99", id).Combined()
  88. lines = strings.Split(out, "\n")
  89. c.Assert(lines, checker.HasLen, 100)
  90. out = cli.DockerCmd(c, "logs", "--tail", "all", id).Combined()
  91. lines = strings.Split(out, "\n")
  92. c.Assert(lines, checker.HasLen, testLen+1)
  93. out = cli.DockerCmd(c, "logs", "--tail", "-1", id).Combined()
  94. lines = strings.Split(out, "\n")
  95. c.Assert(lines, checker.HasLen, testLen+1)
  96. out = cli.DockerCmd(c, "logs", "--tail", "random", id).Combined()
  97. lines = strings.Split(out, "\n")
  98. c.Assert(lines, checker.HasLen, testLen+1)
  99. }
  100. func (s *DockerSuite) TestLogsFollowStopped(c *check.C) {
  101. dockerCmd(c, "run", "--name=test", "busybox", "echo", "hello")
  102. id := getIDByName(c, "test")
  103. logsCmd := exec.Command(dockerBinary, "logs", "-f", id)
  104. c.Assert(logsCmd.Start(), checker.IsNil)
  105. errChan := make(chan error)
  106. go func() {
  107. errChan <- logsCmd.Wait()
  108. close(errChan)
  109. }()
  110. select {
  111. case err := <-errChan:
  112. c.Assert(err, checker.IsNil)
  113. case <-time.After(30 * time.Second):
  114. c.Fatal("Following logs is hanged")
  115. }
  116. }
  117. func (s *DockerSuite) TestLogsSince(c *check.C) {
  118. name := "testlogssince"
  119. dockerCmd(c, "run", "--name="+name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do sleep 2; echo log$i; done")
  120. out, _ := dockerCmd(c, "logs", "-t", name)
  121. log2Line := strings.Split(strings.Split(out, "\n")[1], " ")
  122. t, err := time.Parse(time.RFC3339Nano, log2Line[0]) // the timestamp log2 is written
  123. c.Assert(err, checker.IsNil)
  124. since := t.Unix() + 1 // add 1s so log1 & log2 doesn't show up
  125. out, _ = dockerCmd(c, "logs", "-t", fmt.Sprintf("--since=%v", since), name)
  126. // Skip 2 seconds
  127. unexpected := []string{"log1", "log2"}
  128. for _, v := range unexpected {
  129. c.Assert(out, checker.Not(checker.Contains), v, check.Commentf("unexpected log message returned, since=%v", since))
  130. }
  131. // Test to make sure a bad since format is caught by the client
  132. out, _, _ = dockerCmdWithError("logs", "-t", "--since=2006-01-02T15:04:0Z", name)
  133. c.Assert(out, checker.Contains, "cannot parse \"0Z\" as \"05\"", check.Commentf("bad since format passed to server"))
  134. // Test with default value specified and parameter omitted
  135. expected := []string{"log1", "log2", "log3"}
  136. for _, cmd := range [][]string{
  137. {"logs", "-t", name},
  138. {"logs", "-t", "--since=0", name},
  139. } {
  140. result := icmd.RunCommand(dockerBinary, cmd...)
  141. result.Assert(c, icmd.Success)
  142. for _, v := range expected {
  143. c.Assert(result.Combined(), checker.Contains, v)
  144. }
  145. }
  146. }
  147. func (s *DockerSuite) TestLogsSinceFutureFollow(c *check.C) {
  148. // TODO Windows TP5 - Figure out why this test is so flakey. Disabled for now.
  149. testRequires(c, DaemonIsLinux)
  150. name := "testlogssincefuturefollow"
  151. out, _ := dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", `for i in $(seq 1 5); do echo log$i; sleep 1; done`)
  152. // Extract one timestamp from the log file to give us a starting point for
  153. // our `--since` argument. Because the log producer runs in the background,
  154. // we need to check repeatedly for some output to be produced.
  155. var timestamp string
  156. for i := 0; i != 100 && timestamp == ""; i++ {
  157. if out, _ = dockerCmd(c, "logs", "-t", name); out == "" {
  158. time.Sleep(time.Millisecond * 100) // Retry
  159. } else {
  160. timestamp = strings.Split(strings.Split(out, "\n")[0], " ")[0]
  161. }
  162. }
  163. c.Assert(timestamp, checker.Not(checker.Equals), "")
  164. t, err := time.Parse(time.RFC3339Nano, timestamp)
  165. c.Assert(err, check.IsNil)
  166. since := t.Unix() + 2
  167. out, _ = dockerCmd(c, "logs", "-t", "-f", fmt.Sprintf("--since=%v", since), name)
  168. c.Assert(out, checker.Not(checker.HasLen), 0, check.Commentf("cannot read from empty log"))
  169. lines := strings.Split(strings.TrimSpace(out), "\n")
  170. for _, v := range lines {
  171. ts, err := time.Parse(time.RFC3339Nano, strings.Split(v, " ")[0])
  172. c.Assert(err, checker.IsNil, check.Commentf("cannot parse timestamp output from log: '%v'", v))
  173. c.Assert(ts.Unix() >= since, checker.Equals, true, check.Commentf("earlier log found. since=%v logdate=%v", since, ts))
  174. }
  175. }
  176. // Regression test for #8832
  177. func (s *DockerSuite) TestLogsFollowSlowStdoutConsumer(c *check.C) {
  178. // TODO Windows: Fix this test for TP5.
  179. testRequires(c, DaemonIsLinux)
  180. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", `usleep 600000;yes X | head -c 200000`)
  181. id := strings.TrimSpace(out)
  182. stopSlowRead := make(chan bool)
  183. go func() {
  184. exec.Command(dockerBinary, "wait", id).Run()
  185. stopSlowRead <- true
  186. }()
  187. logCmd := exec.Command(dockerBinary, "logs", "-f", id)
  188. stdout, err := logCmd.StdoutPipe()
  189. c.Assert(err, checker.IsNil)
  190. c.Assert(logCmd.Start(), checker.IsNil)
  191. // First read slowly
  192. bytes1, err := testutil.ConsumeWithSpeed(stdout, 10, 50*time.Millisecond, stopSlowRead)
  193. c.Assert(err, checker.IsNil)
  194. // After the container has finished we can continue reading fast
  195. bytes2, err := testutil.ConsumeWithSpeed(stdout, 32*1024, 0, nil)
  196. c.Assert(err, checker.IsNil)
  197. actual := bytes1 + bytes2
  198. expected := 200000
  199. c.Assert(actual, checker.Equals, expected)
  200. }
  201. func (s *DockerSuite) TestLogsFollowGoroutinesWithStdout(c *check.C) {
  202. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true; do echo hello; sleep 2; done")
  203. id := strings.TrimSpace(out)
  204. c.Assert(waitRun(id), checker.IsNil)
  205. nroutines, err := getGoroutineNumber()
  206. c.Assert(err, checker.IsNil)
  207. cmd := exec.Command(dockerBinary, "logs", "-f", id)
  208. r, w := io.Pipe()
  209. cmd.Stdout = w
  210. c.Assert(cmd.Start(), checker.IsNil)
  211. // Make sure pipe is written to
  212. chErr := make(chan error)
  213. go func() {
  214. b := make([]byte, 1)
  215. _, err := r.Read(b)
  216. chErr <- err
  217. }()
  218. c.Assert(<-chErr, checker.IsNil)
  219. c.Assert(cmd.Process.Kill(), checker.IsNil)
  220. r.Close()
  221. // NGoroutines is not updated right away, so we need to wait before failing
  222. c.Assert(waitForGoroutines(nroutines), checker.IsNil)
  223. }
  224. func (s *DockerSuite) TestLogsFollowGoroutinesNoOutput(c *check.C) {
  225. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true; do sleep 2; done")
  226. id := strings.TrimSpace(out)
  227. c.Assert(waitRun(id), checker.IsNil)
  228. nroutines, err := getGoroutineNumber()
  229. c.Assert(err, checker.IsNil)
  230. cmd := exec.Command(dockerBinary, "logs", "-f", id)
  231. c.Assert(cmd.Start(), checker.IsNil)
  232. time.Sleep(200 * time.Millisecond)
  233. c.Assert(cmd.Process.Kill(), checker.IsNil)
  234. // NGoroutines is not updated right away, so we need to wait before failing
  235. c.Assert(waitForGoroutines(nroutines), checker.IsNil)
  236. }
  237. func (s *DockerSuite) TestLogsCLIContainerNotFound(c *check.C) {
  238. name := "testlogsnocontainer"
  239. out, _, _ := dockerCmdWithError("logs", name)
  240. message := fmt.Sprintf("No such container: %s\n", name)
  241. c.Assert(out, checker.Contains, message)
  242. }
  243. func (s *DockerSuite) TestLogsWithDetails(c *check.C) {
  244. dockerCmd(c, "run", "--name=test", "--label", "foo=bar", "-e", "baz=qux", "--log-opt", "labels=foo", "--log-opt", "env=baz", "busybox", "echo", "hello")
  245. out, _ := dockerCmd(c, "logs", "--details", "--timestamps", "test")
  246. logFields := strings.Fields(strings.TrimSpace(out))
  247. c.Assert(len(logFields), checker.Equals, 3, check.Commentf(out))
  248. details := strings.Split(logFields[1], ",")
  249. c.Assert(details, checker.HasLen, 2)
  250. c.Assert(details[0], checker.Equals, "baz=qux")
  251. c.Assert(details[1], checker.Equals, "foo=bar")
  252. }