docker_api_logs_test.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/docker/docker/api/types/container"
  13. "github.com/docker/docker/client"
  14. "github.com/docker/docker/integration-cli/cli"
  15. "github.com/docker/docker/pkg/stdcopy"
  16. "github.com/docker/docker/testutil"
  17. "github.com/docker/docker/testutil/request"
  18. "gotest.tools/v3/assert"
  19. )
  20. func (s *DockerAPISuite) TestLogsAPIWithStdout(c *testing.T) {
  21. out := cli.DockerCmd(c, "run", "-d", "-t", "busybox", "/bin/sh", "-c", "while true; do echo hello; sleep 1; done").Stdout()
  22. id := strings.TrimSpace(out)
  23. cli.WaitRun(c, id)
  24. type logOut struct {
  25. out string
  26. err error
  27. }
  28. chLog := make(chan logOut, 1)
  29. res, body, err := request.Get(testutil.GetContext(c), fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&timestamps=1", id))
  30. assert.NilError(c, err)
  31. assert.Equal(c, res.StatusCode, http.StatusOK)
  32. go func() {
  33. defer body.Close()
  34. out, err := bufio.NewReader(body).ReadString('\n')
  35. if err != nil {
  36. chLog <- logOut{"", err}
  37. return
  38. }
  39. chLog <- logOut{strings.TrimSpace(out), err}
  40. }()
  41. select {
  42. case l := <-chLog:
  43. assert.NilError(c, l.err)
  44. if !strings.HasSuffix(l.out, "hello") {
  45. c.Fatalf("expected log output to container 'hello', but it does not")
  46. }
  47. case <-time.After(30 * time.Second):
  48. c.Fatal("timeout waiting for logs to exit")
  49. }
  50. }
  51. func (s *DockerAPISuite) TestLogsAPINoStdoutNorStderr(c *testing.T) {
  52. const name = "logs_test"
  53. cli.DockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
  54. apiClient, err := client.NewClientWithOpts(client.FromEnv)
  55. assert.NilError(c, err)
  56. defer apiClient.Close()
  57. _, err = apiClient.ContainerLogs(testutil.GetContext(c), name, container.LogsOptions{})
  58. assert.ErrorContains(c, err, "Bad parameters: you must choose at least one stream")
  59. }
  60. // Regression test for #12704
  61. func (s *DockerAPISuite) TestLogsAPIFollowEmptyOutput(c *testing.T) {
  62. const name = "logs_test"
  63. t0 := time.Now()
  64. cli.DockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "sleep", "10")
  65. _, body, err := request.Get(testutil.GetContext(c), fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name))
  66. t1 := time.Now()
  67. assert.NilError(c, err)
  68. body.Close()
  69. elapsed := t1.Sub(t0).Seconds()
  70. if elapsed > 20.0 {
  71. c.Fatalf("HTTP response was not immediate (elapsed %.1fs)", elapsed)
  72. }
  73. }
  74. func (s *DockerAPISuite) TestLogsAPIContainerNotFound(c *testing.T) {
  75. name := "nonExistentContainer"
  76. resp, _, err := request.Get(testutil.GetContext(c), fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name))
  77. assert.NilError(c, err)
  78. assert.Equal(c, resp.StatusCode, http.StatusNotFound)
  79. }
  80. func (s *DockerAPISuite) TestLogsAPIUntilFutureFollow(c *testing.T) {
  81. testRequires(c, DaemonIsLinux)
  82. const name = "logsuntilfuturefollow"
  83. cli.DockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", "while true; do date +%s; sleep 1; done")
  84. cli.WaitRun(c, name)
  85. untilSecs := 5
  86. untilDur, err := time.ParseDuration(fmt.Sprintf("%ds", untilSecs))
  87. assert.NilError(c, err)
  88. until := daemonTime(c).Add(untilDur)
  89. apiClient, err := client.NewClientWithOpts(client.FromEnv)
  90. if err != nil {
  91. c.Fatal(err)
  92. }
  93. reader, err := apiClient.ContainerLogs(testutil.GetContext(c), name, container.LogsOptions{
  94. Until: until.Format(time.RFC3339Nano),
  95. Follow: true,
  96. ShowStdout: true,
  97. Timestamps: true,
  98. })
  99. assert.NilError(c, err)
  100. type logOut struct {
  101. out string
  102. err error
  103. }
  104. chLog := make(chan logOut)
  105. stop := make(chan struct{})
  106. defer close(stop)
  107. go func() {
  108. bufReader := bufio.NewReader(reader)
  109. defer reader.Close()
  110. for i := 0; i < untilSecs; i++ {
  111. out, _, err := bufReader.ReadLine()
  112. if err != nil {
  113. if err == io.EOF {
  114. return
  115. }
  116. select {
  117. case <-stop:
  118. return
  119. case chLog <- logOut{"", err}:
  120. }
  121. return
  122. }
  123. select {
  124. case <-stop:
  125. return
  126. case chLog <- logOut{strings.TrimSpace(string(out)), err}:
  127. }
  128. }
  129. }()
  130. for i := 0; i < untilSecs; i++ {
  131. select {
  132. case l := <-chLog:
  133. assert.NilError(c, l.err)
  134. i, err := strconv.ParseInt(strings.Split(l.out, " ")[1], 10, 64)
  135. assert.NilError(c, err)
  136. assert.Assert(c, time.Unix(i, 0).UnixNano() <= until.UnixNano())
  137. case <-time.After(20 * time.Second):
  138. c.Fatal("timeout waiting for logs to exit")
  139. }
  140. }
  141. }
  142. func (s *DockerAPISuite) TestLogsAPIUntil(c *testing.T) {
  143. const name = "logsuntil"
  144. cli.DockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; sleep 1; done")
  145. apiClient, err := client.NewClientWithOpts(client.FromEnv)
  146. if err != nil {
  147. c.Fatal(err)
  148. }
  149. extractBody := func(c *testing.T, cfg container.LogsOptions) []string {
  150. reader, err := apiClient.ContainerLogs(testutil.GetContext(c), name, cfg)
  151. assert.NilError(c, err)
  152. actualStdout := new(bytes.Buffer)
  153. actualStderr := io.Discard
  154. _, err = stdcopy.StdCopy(actualStdout, actualStderr, reader)
  155. assert.NilError(c, err)
  156. return strings.Split(actualStdout.String(), "\n")
  157. }
  158. // Get timestamp of second log line
  159. allLogs := extractBody(c, container.LogsOptions{Timestamps: true, ShowStdout: true})
  160. assert.Assert(c, len(allLogs) >= 3)
  161. t, err := time.Parse(time.RFC3339Nano, strings.Split(allLogs[1], " ")[0])
  162. assert.NilError(c, err)
  163. until := t.Format(time.RFC3339Nano)
  164. // Get logs until the timestamp of second line, i.e. first two lines
  165. logs := extractBody(c, container.LogsOptions{Timestamps: true, ShowStdout: true, Until: until})
  166. // Ensure log lines after cut-off are excluded
  167. logsString := strings.Join(logs, "\n")
  168. assert.Assert(c, !strings.Contains(logsString, "log3"), "unexpected log message returned, until=%v", until)
  169. }
  170. func (s *DockerAPISuite) TestLogsAPIUntilDefaultValue(c *testing.T) {
  171. const name = "logsuntildefaultval"
  172. cli.DockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; done")
  173. apiClient, err := client.NewClientWithOpts(client.FromEnv)
  174. if err != nil {
  175. c.Fatal(err)
  176. }
  177. extractBody := func(c *testing.T, cfg container.LogsOptions) []string {
  178. reader, err := apiClient.ContainerLogs(testutil.GetContext(c), name, cfg)
  179. assert.NilError(c, err)
  180. actualStdout := new(bytes.Buffer)
  181. actualStderr := io.Discard
  182. _, err = stdcopy.StdCopy(actualStdout, actualStderr, reader)
  183. assert.NilError(c, err)
  184. return strings.Split(actualStdout.String(), "\n")
  185. }
  186. // Get timestamp of second log line
  187. allLogs := extractBody(c, container.LogsOptions{Timestamps: true, ShowStdout: true})
  188. // Test with default value specified and parameter omitted
  189. defaultLogs := extractBody(c, container.LogsOptions{Timestamps: true, ShowStdout: true, Until: "0"})
  190. assert.DeepEqual(c, defaultLogs, allLogs)
  191. }