docker_cli_logs_test.go 11 KB

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