docker_api_logs_test.go 6.5 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/pkg/stdcopy"
  15. "github.com/docker/docker/testutil"
  16. "github.com/docker/docker/testutil/request"
  17. "gotest.tools/v3/assert"
  18. )
  19. func (s *DockerAPISuite) TestLogsAPIWithStdout(c *testing.T) {
  20. out, _ := dockerCmd(c, "run", "-d", "-t", "busybox", "/bin/sh", "-c", "while true; do echo hello; sleep 1; done")
  21. id := strings.TrimSpace(out)
  22. assert.NilError(c, waitRun(id))
  23. type logOut struct {
  24. out string
  25. err error
  26. }
  27. chLog := make(chan logOut, 1)
  28. res, body, err := request.Get(testutil.GetContext(c), fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&timestamps=1", id))
  29. assert.NilError(c, err)
  30. assert.Equal(c, res.StatusCode, http.StatusOK)
  31. go func() {
  32. defer body.Close()
  33. out, err := bufio.NewReader(body).ReadString('\n')
  34. if err != nil {
  35. chLog <- logOut{"", err}
  36. return
  37. }
  38. chLog <- logOut{strings.TrimSpace(out), err}
  39. }()
  40. select {
  41. case l := <-chLog:
  42. assert.NilError(c, l.err)
  43. if !strings.HasSuffix(l.out, "hello") {
  44. c.Fatalf("expected log output to container 'hello', but it does not")
  45. }
  46. case <-time.After(30 * time.Second):
  47. c.Fatal("timeout waiting for logs to exit")
  48. }
  49. }
  50. func (s *DockerAPISuite) TestLogsAPINoStdoutNorStderr(c *testing.T) {
  51. name := "logs_test"
  52. dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
  53. apiClient, err := client.NewClientWithOpts(client.FromEnv)
  54. assert.NilError(c, err)
  55. defer apiClient.Close()
  56. _, err = apiClient.ContainerLogs(testutil.GetContext(c), name, container.LogsOptions{})
  57. assert.ErrorContains(c, err, "Bad parameters: you must choose at least one stream")
  58. }
  59. // Regression test for #12704
  60. func (s *DockerAPISuite) TestLogsAPIFollowEmptyOutput(c *testing.T) {
  61. name := "logs_test"
  62. t0 := time.Now()
  63. dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "sleep", "10")
  64. _, body, err := request.Get(testutil.GetContext(c), fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name))
  65. t1 := time.Now()
  66. assert.NilError(c, err)
  67. body.Close()
  68. elapsed := t1.Sub(t0).Seconds()
  69. if elapsed > 20.0 {
  70. c.Fatalf("HTTP response was not immediate (elapsed %.1fs)", elapsed)
  71. }
  72. }
  73. func (s *DockerAPISuite) TestLogsAPIContainerNotFound(c *testing.T) {
  74. name := "nonExistentContainer"
  75. resp, _, err := request.Get(testutil.GetContext(c), fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name))
  76. assert.NilError(c, err)
  77. assert.Equal(c, resp.StatusCode, http.StatusNotFound)
  78. }
  79. func (s *DockerAPISuite) TestLogsAPIUntilFutureFollow(c *testing.T) {
  80. testRequires(c, DaemonIsLinux)
  81. name := "logsuntilfuturefollow"
  82. dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", "while true; do date +%s; sleep 1; done")
  83. assert.NilError(c, waitRun(name))
  84. untilSecs := 5
  85. untilDur, err := time.ParseDuration(fmt.Sprintf("%ds", untilSecs))
  86. assert.NilError(c, err)
  87. until := daemonTime(c).Add(untilDur)
  88. client, err := client.NewClientWithOpts(client.FromEnv)
  89. if err != nil {
  90. c.Fatal(err)
  91. }
  92. reader, err := client.ContainerLogs(testutil.GetContext(c), name, container.LogsOptions{
  93. Until: until.Format(time.RFC3339Nano),
  94. Follow: true,
  95. ShowStdout: true,
  96. Timestamps: true,
  97. })
  98. assert.NilError(c, err)
  99. type logOut struct {
  100. out string
  101. err error
  102. }
  103. chLog := make(chan logOut)
  104. stop := make(chan struct{})
  105. defer close(stop)
  106. go func() {
  107. bufReader := bufio.NewReader(reader)
  108. defer reader.Close()
  109. for i := 0; i < untilSecs; i++ {
  110. out, _, err := bufReader.ReadLine()
  111. if err != nil {
  112. if err == io.EOF {
  113. return
  114. }
  115. select {
  116. case <-stop:
  117. return
  118. case chLog <- logOut{"", err}:
  119. }
  120. return
  121. }
  122. select {
  123. case <-stop:
  124. return
  125. case chLog <- logOut{strings.TrimSpace(string(out)), err}:
  126. }
  127. }
  128. }()
  129. for i := 0; i < untilSecs; i++ {
  130. select {
  131. case l := <-chLog:
  132. assert.NilError(c, l.err)
  133. i, err := strconv.ParseInt(strings.Split(l.out, " ")[1], 10, 64)
  134. assert.NilError(c, err)
  135. assert.Assert(c, time.Unix(i, 0).UnixNano() <= until.UnixNano())
  136. case <-time.After(20 * time.Second):
  137. c.Fatal("timeout waiting for logs to exit")
  138. }
  139. }
  140. }
  141. func (s *DockerAPISuite) TestLogsAPIUntil(c *testing.T) {
  142. testRequires(c, MinimumAPIVersion("1.34"))
  143. name := "logsuntil"
  144. dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; sleep 1; done")
  145. client, 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 := client.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. name := "logsuntildefaultval"
  172. dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; done")
  173. client, 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 := client.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. }