docker_api_logs_test.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "strconv"
  10. "strings"
  11. "testing"
  12. "time"
  13. "github.com/docker/docker/api/types"
  14. "github.com/docker/docker/client"
  15. "github.com/docker/docker/pkg/stdcopy"
  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(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. cli, err := client.NewClientWithOpts(client.FromEnv)
  54. assert.NilError(c, err)
  55. defer cli.Close()
  56. _, err = cli.ContainerLogs(context.Background(), name, types.ContainerLogsOptions{})
  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(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(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. cfg := types.ContainerLogsOptions{Until: until.Format(time.RFC3339Nano), Follow: true, ShowStdout: true, Timestamps: true}
  93. reader, err := client.ContainerLogs(context.Background(), name, cfg)
  94. assert.NilError(c, err)
  95. type logOut struct {
  96. out string
  97. err error
  98. }
  99. chLog := make(chan logOut)
  100. stop := make(chan struct{})
  101. defer close(stop)
  102. go func() {
  103. bufReader := bufio.NewReader(reader)
  104. defer reader.Close()
  105. for i := 0; i < untilSecs; i++ {
  106. out, _, err := bufReader.ReadLine()
  107. if err != nil {
  108. if err == io.EOF {
  109. return
  110. }
  111. select {
  112. case <-stop:
  113. return
  114. case chLog <- logOut{"", err}:
  115. }
  116. return
  117. }
  118. select {
  119. case <-stop:
  120. return
  121. case chLog <- logOut{strings.TrimSpace(string(out)), err}:
  122. }
  123. }
  124. }()
  125. for i := 0; i < untilSecs; i++ {
  126. select {
  127. case l := <-chLog:
  128. assert.NilError(c, l.err)
  129. i, err := strconv.ParseInt(strings.Split(l.out, " ")[1], 10, 64)
  130. assert.NilError(c, err)
  131. assert.Assert(c, time.Unix(i, 0).UnixNano() <= until.UnixNano())
  132. case <-time.After(20 * time.Second):
  133. c.Fatal("timeout waiting for logs to exit")
  134. }
  135. }
  136. }
  137. func (s *DockerAPISuite) TestLogsAPIUntil(c *testing.T) {
  138. testRequires(c, MinimumAPIVersion("1.34"))
  139. name := "logsuntil"
  140. dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; sleep 1; done")
  141. client, err := client.NewClientWithOpts(client.FromEnv)
  142. if err != nil {
  143. c.Fatal(err)
  144. }
  145. extractBody := func(c *testing.T, cfg types.ContainerLogsOptions) []string {
  146. reader, err := client.ContainerLogs(context.Background(), name, cfg)
  147. assert.NilError(c, err)
  148. actualStdout := new(bytes.Buffer)
  149. actualStderr := io.Discard
  150. _, err = stdcopy.StdCopy(actualStdout, actualStderr, reader)
  151. assert.NilError(c, err)
  152. return strings.Split(actualStdout.String(), "\n")
  153. }
  154. // Get timestamp of second log line
  155. allLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true})
  156. assert.Assert(c, len(allLogs) >= 3)
  157. t, err := time.Parse(time.RFC3339Nano, strings.Split(allLogs[1], " ")[0])
  158. assert.NilError(c, err)
  159. until := t.Format(time.RFC3339Nano)
  160. // Get logs until the timestamp of second line, i.e. first two lines
  161. logs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true, Until: until})
  162. // Ensure log lines after cut-off are excluded
  163. logsString := strings.Join(logs, "\n")
  164. assert.Assert(c, !strings.Contains(logsString, "log3"), "unexpected log message returned, until=%v", until)
  165. }
  166. func (s *DockerAPISuite) TestLogsAPIUntilDefaultValue(c *testing.T) {
  167. name := "logsuntildefaultval"
  168. dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; done")
  169. client, err := client.NewClientWithOpts(client.FromEnv)
  170. if err != nil {
  171. c.Fatal(err)
  172. }
  173. extractBody := func(c *testing.T, cfg types.ContainerLogsOptions) []string {
  174. reader, err := client.ContainerLogs(context.Background(), name, cfg)
  175. assert.NilError(c, err)
  176. actualStdout := new(bytes.Buffer)
  177. actualStderr := io.Discard
  178. _, err = stdcopy.StdCopy(actualStdout, actualStderr, reader)
  179. assert.NilError(c, err)
  180. return strings.Split(actualStdout.String(), "\n")
  181. }
  182. // Get timestamp of second log line
  183. allLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true})
  184. // Test with default value specified and parameter omitted
  185. defaultLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true, Until: "0"})
  186. assert.DeepEqual(c, defaultLogs, allLogs)
  187. }